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, RewrapBehavior, WordsCompletionMode, all_language_settings,
  113        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, TaskTemplate, TaskVariables};
  135
  136pub use lsp::CompletionContext;
  137use lsp::{
  138    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  139    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  140};
  141
  142use language::BufferSnapshot;
  143use movement::TextLayoutDetails;
  144pub use multi_buffer::{
  145    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  146    ToOffset, ToPoint,
  147};
  148use multi_buffer::{
  149    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  150    MultiOrSingleBufferOffsetRange, PathKey, ToOffsetUtf16,
  151};
  152use parking_lot::Mutex;
  153use project::{
  154    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  155    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  156    TaskSourceKind,
  157    debugger::breakpoint_store::Breakpoint,
  158    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  159    project_settings::{GitGutterSetting, ProjectSettings},
  160};
  161use rand::prelude::*;
  162use rpc::{ErrorExt, proto::*};
  163use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  164use selections_collection::{
  165    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  166};
  167use serde::{Deserialize, Serialize};
  168use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  169use smallvec::SmallVec;
  170use snippet::Snippet;
  171use std::sync::Arc;
  172use std::{
  173    any::TypeId,
  174    borrow::Cow,
  175    cell::RefCell,
  176    cmp::{self, Ordering, Reverse},
  177    mem,
  178    num::NonZeroU32,
  179    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  180    path::{Path, PathBuf},
  181    rc::Rc,
  182    time::{Duration, Instant},
  183};
  184pub use sum_tree::Bias;
  185use sum_tree::TreeMap;
  186use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  187use theme::{
  188    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  189    observe_buffer_font_size_adjustment,
  190};
  191use ui::{
  192    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  193    IconSize, Key, Tooltip, h_flex, prelude::*,
  194};
  195use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  196use workspace::{
  197    Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  198    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  199    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  200    item::{ItemHandle, PreviewTabsSettings},
  201    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  202    searchable::SearchEvent,
  203};
  204
  205use crate::hover_links::{find_url, find_url_from_range};
  206use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  207
  208pub const FILE_HEADER_HEIGHT: u32 = 2;
  209pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  210pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  211const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  212const MAX_LINE_LEN: usize = 1024;
  213const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  214const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  215pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  216#[doc(hidden)]
  217pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  218
  219pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  220pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  221pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  222
  223pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  224pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  225pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  226
  227pub type RenderDiffHunkControlsFn = Arc<
  228    dyn Fn(
  229        u32,
  230        &DiffHunkStatus,
  231        Range<Anchor>,
  232        bool,
  233        Pixels,
  234        &Entity<Editor>,
  235        &mut Window,
  236        &mut App,
  237    ) -> AnyElement,
  238>;
  239
  240const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  241    alt: true,
  242    shift: true,
  243    control: false,
  244    platform: false,
  245    function: false,
  246};
  247
  248#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  249pub enum InlayId {
  250    InlineCompletion(usize),
  251    Hint(usize),
  252}
  253
  254impl InlayId {
  255    fn id(&self) -> usize {
  256        match self {
  257            Self::InlineCompletion(id) => *id,
  258            Self::Hint(id) => *id,
  259        }
  260    }
  261}
  262
  263pub enum DebugCurrentRowHighlight {}
  264enum DocumentHighlightRead {}
  265enum DocumentHighlightWrite {}
  266enum InputComposition {}
  267enum SelectedTextHighlight {}
  268
  269#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  270pub enum Navigated {
  271    Yes,
  272    No,
  273}
  274
  275impl Navigated {
  276    pub fn from_bool(yes: bool) -> Navigated {
  277        if yes { Navigated::Yes } else { Navigated::No }
  278    }
  279}
  280
  281#[derive(Debug, Clone, PartialEq, Eq)]
  282enum DisplayDiffHunk {
  283    Folded {
  284        display_row: DisplayRow,
  285    },
  286    Unfolded {
  287        is_created_file: bool,
  288        diff_base_byte_range: Range<usize>,
  289        display_row_range: Range<DisplayRow>,
  290        multi_buffer_range: Range<Anchor>,
  291        status: DiffHunkStatus,
  292    },
  293}
  294
  295pub enum HideMouseCursorOrigin {
  296    TypingAction,
  297    MovementAction,
  298}
  299
  300pub fn init_settings(cx: &mut App) {
  301    EditorSettings::register(cx);
  302}
  303
  304pub fn init(cx: &mut App) {
  305    init_settings(cx);
  306
  307    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  308
  309    workspace::register_project_item::<Editor>(cx);
  310    workspace::FollowableViewRegistry::register::<Editor>(cx);
  311    workspace::register_serializable_item::<Editor>(cx);
  312
  313    cx.observe_new(
  314        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  315            workspace.register_action(Editor::new_file);
  316            workspace.register_action(Editor::new_file_vertical);
  317            workspace.register_action(Editor::new_file_horizontal);
  318            workspace.register_action(Editor::cancel_language_server_work);
  319        },
  320    )
  321    .detach();
  322
  323    cx.on_action(move |_: &workspace::NewFile, cx| {
  324        let app_state = workspace::AppState::global(cx);
  325        if let Some(app_state) = app_state.upgrade() {
  326            workspace::open_new(
  327                Default::default(),
  328                app_state,
  329                cx,
  330                |workspace, window, cx| {
  331                    Editor::new_file(workspace, &Default::default(), window, cx)
  332                },
  333            )
  334            .detach();
  335        }
  336    });
  337    cx.on_action(move |_: &workspace::NewWindow, cx| {
  338        let app_state = workspace::AppState::global(cx);
  339        if let Some(app_state) = app_state.upgrade() {
  340            workspace::open_new(
  341                Default::default(),
  342                app_state,
  343                cx,
  344                |workspace, window, cx| {
  345                    cx.activate(true);
  346                    Editor::new_file(workspace, &Default::default(), window, cx)
  347                },
  348            )
  349            .detach();
  350        }
  351    });
  352}
  353
  354pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  355    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  356}
  357
  358pub struct SearchWithinRange;
  359
  360trait InvalidationRegion {
  361    fn ranges(&self) -> &[Range<Anchor>];
  362}
  363
  364#[derive(Clone, Debug, PartialEq)]
  365pub enum SelectPhase {
  366    Begin {
  367        position: DisplayPoint,
  368        add: bool,
  369        click_count: usize,
  370    },
  371    BeginColumnar {
  372        position: DisplayPoint,
  373        reset: bool,
  374        goal_column: u32,
  375    },
  376    Extend {
  377        position: DisplayPoint,
  378        click_count: usize,
  379    },
  380    Update {
  381        position: DisplayPoint,
  382        goal_column: u32,
  383        scroll_delta: gpui::Point<f32>,
  384    },
  385    End,
  386}
  387
  388#[derive(Clone, Debug)]
  389pub enum SelectMode {
  390    Character,
  391    Word(Range<Anchor>),
  392    Line(Range<Anchor>),
  393    All,
  394}
  395
  396#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  397pub enum EditorMode {
  398    SingleLine { auto_width: bool },
  399    AutoHeight { max_lines: usize },
  400    Full,
  401}
  402
  403#[derive(Copy, Clone, Debug)]
  404pub enum SoftWrap {
  405    /// Prefer not to wrap at all.
  406    ///
  407    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  408    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  409    GitDiff,
  410    /// Prefer a single line generally, unless an overly long line is encountered.
  411    None,
  412    /// Soft wrap lines that exceed the editor width.
  413    EditorWidth,
  414    /// Soft wrap lines at the preferred line length.
  415    Column(u32),
  416    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  417    Bounded(u32),
  418}
  419
  420#[derive(Clone)]
  421pub struct EditorStyle {
  422    pub background: Hsla,
  423    pub local_player: PlayerColor,
  424    pub text: TextStyle,
  425    pub scrollbar_width: Pixels,
  426    pub syntax: Arc<SyntaxTheme>,
  427    pub status: StatusColors,
  428    pub inlay_hints_style: HighlightStyle,
  429    pub inline_completion_styles: InlineCompletionStyles,
  430    pub unnecessary_code_fade: f32,
  431}
  432
  433impl Default for EditorStyle {
  434    fn default() -> Self {
  435        Self {
  436            background: Hsla::default(),
  437            local_player: PlayerColor::default(),
  438            text: TextStyle::default(),
  439            scrollbar_width: Pixels::default(),
  440            syntax: Default::default(),
  441            // HACK: Status colors don't have a real default.
  442            // We should look into removing the status colors from the editor
  443            // style and retrieve them directly from the theme.
  444            status: StatusColors::dark(),
  445            inlay_hints_style: HighlightStyle::default(),
  446            inline_completion_styles: InlineCompletionStyles {
  447                insertion: HighlightStyle::default(),
  448                whitespace: HighlightStyle::default(),
  449            },
  450            unnecessary_code_fade: Default::default(),
  451        }
  452    }
  453}
  454
  455pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  456    let show_background = language_settings::language_settings(None, None, cx)
  457        .inlay_hints
  458        .show_background;
  459
  460    HighlightStyle {
  461        color: Some(cx.theme().status().hint),
  462        background_color: show_background.then(|| cx.theme().status().hint_background),
  463        ..HighlightStyle::default()
  464    }
  465}
  466
  467pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  468    InlineCompletionStyles {
  469        insertion: HighlightStyle {
  470            color: Some(cx.theme().status().predictive),
  471            ..HighlightStyle::default()
  472        },
  473        whitespace: HighlightStyle {
  474            background_color: Some(cx.theme().status().created_background),
  475            ..HighlightStyle::default()
  476        },
  477    }
  478}
  479
  480type CompletionId = usize;
  481
  482pub(crate) enum EditDisplayMode {
  483    TabAccept,
  484    DiffPopover,
  485    Inline,
  486}
  487
  488enum InlineCompletion {
  489    Edit {
  490        edits: Vec<(Range<Anchor>, String)>,
  491        edit_preview: Option<EditPreview>,
  492        display_mode: EditDisplayMode,
  493        snapshot: BufferSnapshot,
  494    },
  495    Move {
  496        target: Anchor,
  497        snapshot: BufferSnapshot,
  498    },
  499}
  500
  501struct InlineCompletionState {
  502    inlay_ids: Vec<InlayId>,
  503    completion: InlineCompletion,
  504    completion_id: Option<SharedString>,
  505    invalidation_range: Range<Anchor>,
  506}
  507
  508enum EditPredictionSettings {
  509    Disabled,
  510    Enabled {
  511        show_in_menu: bool,
  512        preview_requires_modifier: bool,
  513    },
  514}
  515
  516enum InlineCompletionHighlight {}
  517
  518#[derive(Debug, Clone)]
  519struct InlineDiagnostic {
  520    message: SharedString,
  521    group_id: usize,
  522    is_primary: bool,
  523    start: Point,
  524    severity: DiagnosticSeverity,
  525}
  526
  527pub enum MenuInlineCompletionsPolicy {
  528    Never,
  529    ByProvider,
  530}
  531
  532pub enum EditPredictionPreview {
  533    /// Modifier is not pressed
  534    Inactive { released_too_fast: bool },
  535    /// Modifier pressed
  536    Active {
  537        since: Instant,
  538        previous_scroll_position: Option<ScrollAnchor>,
  539    },
  540}
  541
  542impl EditPredictionPreview {
  543    pub fn released_too_fast(&self) -> bool {
  544        match self {
  545            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  546            EditPredictionPreview::Active { .. } => false,
  547        }
  548    }
  549
  550    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  551        if let EditPredictionPreview::Active {
  552            previous_scroll_position,
  553            ..
  554        } = self
  555        {
  556            *previous_scroll_position = scroll_position;
  557        }
  558    }
  559}
  560
  561pub struct ContextMenuOptions {
  562    pub min_entries_visible: usize,
  563    pub max_entries_visible: usize,
  564    pub placement: Option<ContextMenuPlacement>,
  565}
  566
  567#[derive(Debug, Clone, PartialEq, Eq)]
  568pub enum ContextMenuPlacement {
  569    Above,
  570    Below,
  571}
  572
  573#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  574struct EditorActionId(usize);
  575
  576impl EditorActionId {
  577    pub fn post_inc(&mut self) -> Self {
  578        let answer = self.0;
  579
  580        *self = Self(answer + 1);
  581
  582        Self(answer)
  583    }
  584}
  585
  586// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  587// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  588
  589type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  590type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  591
  592#[derive(Default)]
  593struct ScrollbarMarkerState {
  594    scrollbar_size: Size<Pixels>,
  595    dirty: bool,
  596    markers: Arc<[PaintQuad]>,
  597    pending_refresh: Option<Task<Result<()>>>,
  598}
  599
  600impl ScrollbarMarkerState {
  601    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  602        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  603    }
  604}
  605
  606#[derive(Clone, Debug)]
  607struct RunnableTasks {
  608    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  609    offset: multi_buffer::Anchor,
  610    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  611    column: u32,
  612    // Values of all named captures, including those starting with '_'
  613    extra_variables: HashMap<String, String>,
  614    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  615    context_range: Range<BufferOffset>,
  616}
  617
  618impl RunnableTasks {
  619    fn resolve<'a>(
  620        &'a self,
  621        cx: &'a task::TaskContext,
  622    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  623        self.templates.iter().filter_map(|(kind, template)| {
  624            template
  625                .resolve_task(&kind.to_id_base(), cx)
  626                .map(|task| (kind.clone(), task))
  627        })
  628    }
  629}
  630
  631#[derive(Clone)]
  632struct ResolvedTasks {
  633    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  634    position: Anchor,
  635}
  636
  637#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  638struct BufferOffset(usize);
  639
  640// Addons allow storing per-editor state in other crates (e.g. Vim)
  641pub trait Addon: 'static {
  642    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  643
  644    fn render_buffer_header_controls(
  645        &self,
  646        _: &ExcerptInfo,
  647        _: &Window,
  648        _: &App,
  649    ) -> Option<AnyElement> {
  650        None
  651    }
  652
  653    fn to_any(&self) -> &dyn std::any::Any;
  654}
  655
  656/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  657///
  658/// See the [module level documentation](self) for more information.
  659pub struct Editor {
  660    focus_handle: FocusHandle,
  661    last_focused_descendant: Option<WeakFocusHandle>,
  662    /// The text buffer being edited
  663    buffer: Entity<MultiBuffer>,
  664    /// Map of how text in the buffer should be displayed.
  665    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  666    pub display_map: Entity<DisplayMap>,
  667    pub selections: SelectionsCollection,
  668    pub scroll_manager: ScrollManager,
  669    /// When inline assist editors are linked, they all render cursors because
  670    /// typing enters text into each of them, even the ones that aren't focused.
  671    pub(crate) show_cursor_when_unfocused: bool,
  672    columnar_selection_tail: Option<Anchor>,
  673    add_selections_state: Option<AddSelectionsState>,
  674    select_next_state: Option<SelectNextState>,
  675    select_prev_state: Option<SelectNextState>,
  676    selection_history: SelectionHistory,
  677    autoclose_regions: Vec<AutocloseRegion>,
  678    snippet_stack: InvalidationStack<SnippetState>,
  679    select_syntax_node_history: SelectSyntaxNodeHistory,
  680    ime_transaction: Option<TransactionId>,
  681    active_diagnostics: Option<ActiveDiagnosticGroup>,
  682    show_inline_diagnostics: bool,
  683    inline_diagnostics_update: Task<()>,
  684    inline_diagnostics_enabled: bool,
  685    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  686    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  687    hard_wrap: Option<usize>,
  688
  689    // TODO: make this a access method
  690    pub project: Option<Entity<Project>>,
  691    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  692    completion_provider: Option<Box<dyn CompletionProvider>>,
  693    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  694    blink_manager: Entity<BlinkManager>,
  695    show_cursor_names: bool,
  696    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  697    pub show_local_selections: bool,
  698    mode: EditorMode,
  699    show_breadcrumbs: bool,
  700    show_gutter: bool,
  701    show_scrollbars: bool,
  702    show_line_numbers: Option<bool>,
  703    use_relative_line_numbers: Option<bool>,
  704    show_git_diff_gutter: Option<bool>,
  705    show_code_actions: Option<bool>,
  706    show_runnables: Option<bool>,
  707    show_breakpoints: Option<bool>,
  708    show_wrap_guides: Option<bool>,
  709    show_indent_guides: Option<bool>,
  710    placeholder_text: Option<Arc<str>>,
  711    highlight_order: usize,
  712    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  713    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  714    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  715    scrollbar_marker_state: ScrollbarMarkerState,
  716    active_indent_guides_state: ActiveIndentGuidesState,
  717    nav_history: Option<ItemNavHistory>,
  718    context_menu: RefCell<Option<CodeContextMenu>>,
  719    context_menu_options: Option<ContextMenuOptions>,
  720    mouse_context_menu: Option<MouseContextMenu>,
  721    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  722    signature_help_state: SignatureHelpState,
  723    auto_signature_help: Option<bool>,
  724    find_all_references_task_sources: Vec<Anchor>,
  725    next_completion_id: CompletionId,
  726    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  727    code_actions_task: Option<Task<Result<()>>>,
  728    selection_highlight_task: Option<Task<()>>,
  729    document_highlights_task: Option<Task<()>>,
  730    linked_editing_range_task: Option<Task<Option<()>>>,
  731    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  732    pending_rename: Option<RenameState>,
  733    searchable: bool,
  734    cursor_shape: CursorShape,
  735    current_line_highlight: Option<CurrentLineHighlight>,
  736    collapse_matches: bool,
  737    autoindent_mode: Option<AutoindentMode>,
  738    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  739    input_enabled: bool,
  740    use_modal_editing: bool,
  741    read_only: bool,
  742    leader_peer_id: Option<PeerId>,
  743    remote_id: Option<ViewId>,
  744    hover_state: HoverState,
  745    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  746    gutter_hovered: bool,
  747    hovered_link_state: Option<HoveredLinkState>,
  748    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  749    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  750    active_inline_completion: Option<InlineCompletionState>,
  751    /// Used to prevent flickering as the user types while the menu is open
  752    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  753    edit_prediction_settings: EditPredictionSettings,
  754    inline_completions_hidden_for_vim_mode: bool,
  755    show_inline_completions_override: Option<bool>,
  756    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  757    edit_prediction_preview: EditPredictionPreview,
  758    edit_prediction_indent_conflict: bool,
  759    edit_prediction_requires_modifier_in_indent_conflict: bool,
  760    inlay_hint_cache: InlayHintCache,
  761    next_inlay_id: usize,
  762    _subscriptions: Vec<Subscription>,
  763    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  764    gutter_dimensions: GutterDimensions,
  765    style: Option<EditorStyle>,
  766    text_style_refinement: Option<TextStyleRefinement>,
  767    next_editor_action_id: EditorActionId,
  768    editor_actions:
  769        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  770    use_autoclose: bool,
  771    use_auto_surround: bool,
  772    auto_replace_emoji_shortcode: bool,
  773    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  774    show_git_blame_gutter: bool,
  775    show_git_blame_inline: bool,
  776    show_git_blame_inline_delay_task: Option<Task<()>>,
  777    pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
  778    git_blame_inline_enabled: bool,
  779    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  780    serialize_dirty_buffers: bool,
  781    show_selection_menu: Option<bool>,
  782    blame: Option<Entity<GitBlame>>,
  783    blame_subscription: Option<Subscription>,
  784    custom_context_menu: Option<
  785        Box<
  786            dyn 'static
  787                + Fn(
  788                    &mut Self,
  789                    DisplayPoint,
  790                    &mut Window,
  791                    &mut Context<Self>,
  792                ) -> Option<Entity<ui::ContextMenu>>,
  793        >,
  794    >,
  795    last_bounds: Option<Bounds<Pixels>>,
  796    last_position_map: Option<Rc<PositionMap>>,
  797    expect_bounds_change: Option<Bounds<Pixels>>,
  798    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  799    tasks_update_task: Option<Task<()>>,
  800    breakpoint_store: Option<Entity<BreakpointStore>>,
  801    /// Allow's a user to create a breakpoint by selecting this indicator
  802    /// It should be None while a user is not hovering over the gutter
  803    /// Otherwise it represents the point that the breakpoint will be shown
  804    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  805    in_project_search: bool,
  806    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  807    breadcrumb_header: Option<String>,
  808    focused_block: Option<FocusedBlock>,
  809    next_scroll_position: NextScrollCursorCenterTopBottom,
  810    addons: HashMap<TypeId, Box<dyn Addon>>,
  811    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  812    load_diff_task: Option<Shared<Task<()>>>,
  813    selection_mark_mode: bool,
  814    toggle_fold_multiple_buffers: Task<()>,
  815    _scroll_cursor_center_top_bottom_task: Task<()>,
  816    serialize_selections: Task<()>,
  817    serialize_folds: Task<()>,
  818    mouse_cursor_hidden: bool,
  819    hide_mouse_mode: HideMouseMode,
  820}
  821
  822#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  823enum NextScrollCursorCenterTopBottom {
  824    #[default]
  825    Center,
  826    Top,
  827    Bottom,
  828}
  829
  830impl NextScrollCursorCenterTopBottom {
  831    fn next(&self) -> Self {
  832        match self {
  833            Self::Center => Self::Top,
  834            Self::Top => Self::Bottom,
  835            Self::Bottom => Self::Center,
  836        }
  837    }
  838}
  839
  840#[derive(Clone)]
  841pub struct EditorSnapshot {
  842    pub mode: EditorMode,
  843    show_gutter: bool,
  844    show_line_numbers: Option<bool>,
  845    show_git_diff_gutter: Option<bool>,
  846    show_code_actions: Option<bool>,
  847    show_runnables: Option<bool>,
  848    show_breakpoints: Option<bool>,
  849    git_blame_gutter_max_author_length: Option<usize>,
  850    pub display_snapshot: DisplaySnapshot,
  851    pub placeholder_text: Option<Arc<str>>,
  852    is_focused: bool,
  853    scroll_anchor: ScrollAnchor,
  854    ongoing_scroll: OngoingScroll,
  855    current_line_highlight: CurrentLineHighlight,
  856    gutter_hovered: bool,
  857}
  858
  859#[derive(Default, Debug, Clone, Copy)]
  860pub struct GutterDimensions {
  861    pub left_padding: Pixels,
  862    pub right_padding: Pixels,
  863    pub width: Pixels,
  864    pub margin: Pixels,
  865    pub git_blame_entries_width: Option<Pixels>,
  866}
  867
  868impl GutterDimensions {
  869    /// The full width of the space taken up by the gutter.
  870    pub fn full_width(&self) -> Pixels {
  871        self.margin + self.width
  872    }
  873
  874    /// The width of the space reserved for the fold indicators,
  875    /// use alongside 'justify_end' and `gutter_width` to
  876    /// right align content with the line numbers
  877    pub fn fold_area_width(&self) -> Pixels {
  878        self.margin + self.right_padding
  879    }
  880}
  881
  882#[derive(Debug)]
  883pub struct RemoteSelection {
  884    pub replica_id: ReplicaId,
  885    pub selection: Selection<Anchor>,
  886    pub cursor_shape: CursorShape,
  887    pub peer_id: PeerId,
  888    pub line_mode: bool,
  889    pub participant_index: Option<ParticipantIndex>,
  890    pub user_name: Option<SharedString>,
  891}
  892
  893#[derive(Clone, Debug)]
  894struct SelectionHistoryEntry {
  895    selections: Arc<[Selection<Anchor>]>,
  896    select_next_state: Option<SelectNextState>,
  897    select_prev_state: Option<SelectNextState>,
  898    add_selections_state: Option<AddSelectionsState>,
  899}
  900
  901enum SelectionHistoryMode {
  902    Normal,
  903    Undoing,
  904    Redoing,
  905}
  906
  907#[derive(Clone, PartialEq, Eq, Hash)]
  908struct HoveredCursor {
  909    replica_id: u16,
  910    selection_id: usize,
  911}
  912
  913impl Default for SelectionHistoryMode {
  914    fn default() -> Self {
  915        Self::Normal
  916    }
  917}
  918
  919#[derive(Default)]
  920struct SelectionHistory {
  921    #[allow(clippy::type_complexity)]
  922    selections_by_transaction:
  923        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  924    mode: SelectionHistoryMode,
  925    undo_stack: VecDeque<SelectionHistoryEntry>,
  926    redo_stack: VecDeque<SelectionHistoryEntry>,
  927}
  928
  929impl SelectionHistory {
  930    fn insert_transaction(
  931        &mut self,
  932        transaction_id: TransactionId,
  933        selections: Arc<[Selection<Anchor>]>,
  934    ) {
  935        self.selections_by_transaction
  936            .insert(transaction_id, (selections, None));
  937    }
  938
  939    #[allow(clippy::type_complexity)]
  940    fn transaction(
  941        &self,
  942        transaction_id: TransactionId,
  943    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  944        self.selections_by_transaction.get(&transaction_id)
  945    }
  946
  947    #[allow(clippy::type_complexity)]
  948    fn transaction_mut(
  949        &mut self,
  950        transaction_id: TransactionId,
  951    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  952        self.selections_by_transaction.get_mut(&transaction_id)
  953    }
  954
  955    fn push(&mut self, entry: SelectionHistoryEntry) {
  956        if !entry.selections.is_empty() {
  957            match self.mode {
  958                SelectionHistoryMode::Normal => {
  959                    self.push_undo(entry);
  960                    self.redo_stack.clear();
  961                }
  962                SelectionHistoryMode::Undoing => self.push_redo(entry),
  963                SelectionHistoryMode::Redoing => self.push_undo(entry),
  964            }
  965        }
  966    }
  967
  968    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  969        if self
  970            .undo_stack
  971            .back()
  972            .map_or(true, |e| e.selections != entry.selections)
  973        {
  974            self.undo_stack.push_back(entry);
  975            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  976                self.undo_stack.pop_front();
  977            }
  978        }
  979    }
  980
  981    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  982        if self
  983            .redo_stack
  984            .back()
  985            .map_or(true, |e| e.selections != entry.selections)
  986        {
  987            self.redo_stack.push_back(entry);
  988            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  989                self.redo_stack.pop_front();
  990            }
  991        }
  992    }
  993}
  994
  995struct RowHighlight {
  996    index: usize,
  997    range: Range<Anchor>,
  998    color: Hsla,
  999    should_autoscroll: bool,
 1000}
 1001
 1002#[derive(Clone, Debug)]
 1003struct AddSelectionsState {
 1004    above: bool,
 1005    stack: Vec<usize>,
 1006}
 1007
 1008#[derive(Clone)]
 1009struct SelectNextState {
 1010    query: AhoCorasick,
 1011    wordwise: bool,
 1012    done: bool,
 1013}
 1014
 1015impl std::fmt::Debug for SelectNextState {
 1016    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1017        f.debug_struct(std::any::type_name::<Self>())
 1018            .field("wordwise", &self.wordwise)
 1019            .field("done", &self.done)
 1020            .finish()
 1021    }
 1022}
 1023
 1024#[derive(Debug)]
 1025struct AutocloseRegion {
 1026    selection_id: usize,
 1027    range: Range<Anchor>,
 1028    pair: BracketPair,
 1029}
 1030
 1031#[derive(Debug)]
 1032struct SnippetState {
 1033    ranges: Vec<Vec<Range<Anchor>>>,
 1034    active_index: usize,
 1035    choices: Vec<Option<Vec<String>>>,
 1036}
 1037
 1038#[doc(hidden)]
 1039pub struct RenameState {
 1040    pub range: Range<Anchor>,
 1041    pub old_name: Arc<str>,
 1042    pub editor: Entity<Editor>,
 1043    block_id: CustomBlockId,
 1044}
 1045
 1046struct InvalidationStack<T>(Vec<T>);
 1047
 1048struct RegisteredInlineCompletionProvider {
 1049    provider: Arc<dyn InlineCompletionProviderHandle>,
 1050    _subscription: Subscription,
 1051}
 1052
 1053#[derive(Debug, PartialEq, Eq)]
 1054struct ActiveDiagnosticGroup {
 1055    primary_range: Range<Anchor>,
 1056    primary_message: String,
 1057    group_id: usize,
 1058    blocks: HashMap<CustomBlockId, Diagnostic>,
 1059    is_valid: bool,
 1060}
 1061
 1062#[derive(Serialize, Deserialize, Clone, Debug)]
 1063pub struct ClipboardSelection {
 1064    /// The number of bytes in this selection.
 1065    pub len: usize,
 1066    /// Whether this was a full-line selection.
 1067    pub is_entire_line: bool,
 1068    /// The indentation of the first line when this content was originally copied.
 1069    pub first_line_indent: u32,
 1070}
 1071
 1072// selections, scroll behavior, was newest selection reversed
 1073type SelectSyntaxNodeHistoryState = (
 1074    Box<[Selection<usize>]>,
 1075    SelectSyntaxNodeScrollBehavior,
 1076    bool,
 1077);
 1078
 1079#[derive(Default)]
 1080struct SelectSyntaxNodeHistory {
 1081    stack: Vec<SelectSyntaxNodeHistoryState>,
 1082    // disable temporarily to allow changing selections without losing the stack
 1083    pub disable_clearing: bool,
 1084}
 1085
 1086impl SelectSyntaxNodeHistory {
 1087    pub fn try_clear(&mut self) {
 1088        if !self.disable_clearing {
 1089            self.stack.clear();
 1090        }
 1091    }
 1092
 1093    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1094        self.stack.push(selection);
 1095    }
 1096
 1097    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1098        self.stack.pop()
 1099    }
 1100}
 1101
 1102enum SelectSyntaxNodeScrollBehavior {
 1103    CursorTop,
 1104    FitSelection,
 1105    CursorBottom,
 1106}
 1107
 1108#[derive(Debug)]
 1109pub(crate) struct NavigationData {
 1110    cursor_anchor: Anchor,
 1111    cursor_position: Point,
 1112    scroll_anchor: ScrollAnchor,
 1113    scroll_top_row: u32,
 1114}
 1115
 1116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1117pub enum GotoDefinitionKind {
 1118    Symbol,
 1119    Declaration,
 1120    Type,
 1121    Implementation,
 1122}
 1123
 1124#[derive(Debug, Clone)]
 1125enum InlayHintRefreshReason {
 1126    ModifiersChanged(bool),
 1127    Toggle(bool),
 1128    SettingsChange(InlayHintSettings),
 1129    NewLinesShown,
 1130    BufferEdited(HashSet<Arc<Language>>),
 1131    RefreshRequested,
 1132    ExcerptsRemoved(Vec<ExcerptId>),
 1133}
 1134
 1135impl InlayHintRefreshReason {
 1136    fn description(&self) -> &'static str {
 1137        match self {
 1138            Self::ModifiersChanged(_) => "modifiers changed",
 1139            Self::Toggle(_) => "toggle",
 1140            Self::SettingsChange(_) => "settings change",
 1141            Self::NewLinesShown => "new lines shown",
 1142            Self::BufferEdited(_) => "buffer edited",
 1143            Self::RefreshRequested => "refresh requested",
 1144            Self::ExcerptsRemoved(_) => "excerpts removed",
 1145        }
 1146    }
 1147}
 1148
 1149pub enum FormatTarget {
 1150    Buffers,
 1151    Ranges(Vec<Range<MultiBufferPoint>>),
 1152}
 1153
 1154pub(crate) struct FocusedBlock {
 1155    id: BlockId,
 1156    focus_handle: WeakFocusHandle,
 1157}
 1158
 1159#[derive(Clone)]
 1160enum JumpData {
 1161    MultiBufferRow {
 1162        row: MultiBufferRow,
 1163        line_offset_from_top: u32,
 1164    },
 1165    MultiBufferPoint {
 1166        excerpt_id: ExcerptId,
 1167        position: Point,
 1168        anchor: text::Anchor,
 1169        line_offset_from_top: u32,
 1170    },
 1171}
 1172
 1173pub enum MultibufferSelectionMode {
 1174    First,
 1175    All,
 1176}
 1177
 1178#[derive(Clone, Copy, Debug, Default)]
 1179pub struct RewrapOptions {
 1180    pub override_language_settings: bool,
 1181    pub preserve_existing_whitespace: bool,
 1182}
 1183
 1184impl Editor {
 1185    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1186        let buffer = cx.new(|cx| Buffer::local("", cx));
 1187        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1188        Self::new(
 1189            EditorMode::SingleLine { auto_width: false },
 1190            buffer,
 1191            None,
 1192            window,
 1193            cx,
 1194        )
 1195    }
 1196
 1197    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1198        let buffer = cx.new(|cx| Buffer::local("", cx));
 1199        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1200        Self::new(EditorMode::Full, buffer, None, window, cx)
 1201    }
 1202
 1203    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1204        let buffer = cx.new(|cx| Buffer::local("", cx));
 1205        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1206        Self::new(
 1207            EditorMode::SingleLine { auto_width: true },
 1208            buffer,
 1209            None,
 1210            window,
 1211            cx,
 1212        )
 1213    }
 1214
 1215    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1216        let buffer = cx.new(|cx| Buffer::local("", cx));
 1217        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1218        Self::new(
 1219            EditorMode::AutoHeight { max_lines },
 1220            buffer,
 1221            None,
 1222            window,
 1223            cx,
 1224        )
 1225    }
 1226
 1227    pub fn for_buffer(
 1228        buffer: Entity<Buffer>,
 1229        project: Option<Entity<Project>>,
 1230        window: &mut Window,
 1231        cx: &mut Context<Self>,
 1232    ) -> Self {
 1233        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1234        Self::new(EditorMode::Full, buffer, project, window, cx)
 1235    }
 1236
 1237    pub fn for_multibuffer(
 1238        buffer: Entity<MultiBuffer>,
 1239        project: Option<Entity<Project>>,
 1240        window: &mut Window,
 1241        cx: &mut Context<Self>,
 1242    ) -> Self {
 1243        Self::new(EditorMode::Full, buffer, project, window, cx)
 1244    }
 1245
 1246    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1247        let mut clone = Self::new(
 1248            self.mode,
 1249            self.buffer.clone(),
 1250            self.project.clone(),
 1251            window,
 1252            cx,
 1253        );
 1254        self.display_map.update(cx, |display_map, cx| {
 1255            let snapshot = display_map.snapshot(cx);
 1256            clone.display_map.update(cx, |display_map, cx| {
 1257                display_map.set_state(&snapshot, cx);
 1258            });
 1259        });
 1260        clone.folds_did_change(cx);
 1261        clone.selections.clone_state(&self.selections);
 1262        clone.scroll_manager.clone_state(&self.scroll_manager);
 1263        clone.searchable = self.searchable;
 1264        clone
 1265    }
 1266
 1267    pub fn new(
 1268        mode: EditorMode,
 1269        buffer: Entity<MultiBuffer>,
 1270        project: Option<Entity<Project>>,
 1271        window: &mut Window,
 1272        cx: &mut Context<Self>,
 1273    ) -> Self {
 1274        let style = window.text_style();
 1275        let font_size = style.font_size.to_pixels(window.rem_size());
 1276        let editor = cx.entity().downgrade();
 1277        let fold_placeholder = FoldPlaceholder {
 1278            constrain_width: true,
 1279            render: Arc::new(move |fold_id, fold_range, cx| {
 1280                let editor = editor.clone();
 1281                div()
 1282                    .id(fold_id)
 1283                    .bg(cx.theme().colors().ghost_element_background)
 1284                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1285                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1286                    .rounded_xs()
 1287                    .size_full()
 1288                    .cursor_pointer()
 1289                    .child("")
 1290                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1291                    .on_click(move |_, _window, cx| {
 1292                        editor
 1293                            .update(cx, |editor, cx| {
 1294                                editor.unfold_ranges(
 1295                                    &[fold_range.start..fold_range.end],
 1296                                    true,
 1297                                    false,
 1298                                    cx,
 1299                                );
 1300                                cx.stop_propagation();
 1301                            })
 1302                            .ok();
 1303                    })
 1304                    .into_any()
 1305            }),
 1306            merge_adjacent: true,
 1307            ..Default::default()
 1308        };
 1309        let display_map = cx.new(|cx| {
 1310            DisplayMap::new(
 1311                buffer.clone(),
 1312                style.font(),
 1313                font_size,
 1314                None,
 1315                FILE_HEADER_HEIGHT,
 1316                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1317                fold_placeholder,
 1318                cx,
 1319            )
 1320        });
 1321
 1322        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1323
 1324        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1325
 1326        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1327            .then(|| language_settings::SoftWrap::None);
 1328
 1329        let mut project_subscriptions = Vec::new();
 1330        if mode == EditorMode::Full {
 1331            if let Some(project) = project.as_ref() {
 1332                project_subscriptions.push(cx.subscribe_in(
 1333                    project,
 1334                    window,
 1335                    |editor, _, event, window, cx| match event {
 1336                        project::Event::RefreshCodeLens => {
 1337                            // we always query lens with actions, without storing them, always refreshing them
 1338                        }
 1339                        project::Event::RefreshInlayHints => {
 1340                            editor
 1341                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1342                        }
 1343                        project::Event::SnippetEdit(id, snippet_edits) => {
 1344                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1345                                let focus_handle = editor.focus_handle(cx);
 1346                                if focus_handle.is_focused(window) {
 1347                                    let snapshot = buffer.read(cx).snapshot();
 1348                                    for (range, snippet) in snippet_edits {
 1349                                        let editor_range =
 1350                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1351                                        editor
 1352                                            .insert_snippet(
 1353                                                &[editor_range],
 1354                                                snippet.clone(),
 1355                                                window,
 1356                                                cx,
 1357                                            )
 1358                                            .ok();
 1359                                    }
 1360                                }
 1361                            }
 1362                        }
 1363                        _ => {}
 1364                    },
 1365                ));
 1366                if let Some(task_inventory) = project
 1367                    .read(cx)
 1368                    .task_store()
 1369                    .read(cx)
 1370                    .task_inventory()
 1371                    .cloned()
 1372                {
 1373                    project_subscriptions.push(cx.observe_in(
 1374                        &task_inventory,
 1375                        window,
 1376                        |editor, _, window, cx| {
 1377                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1378                        },
 1379                    ));
 1380                };
 1381
 1382                project_subscriptions.push(cx.subscribe_in(
 1383                    &project.read(cx).breakpoint_store(),
 1384                    window,
 1385                    |editor, _, event, window, cx| match event {
 1386                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1387                            editor.go_to_active_debug_line(window, cx);
 1388                        }
 1389                        _ => {}
 1390                    },
 1391                ));
 1392            }
 1393        }
 1394
 1395        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1396
 1397        let inlay_hint_settings =
 1398            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1399        let focus_handle = cx.focus_handle();
 1400        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1401            .detach();
 1402        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1403            .detach();
 1404        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1405            .detach();
 1406        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1407            .detach();
 1408
 1409        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1410            Some(false)
 1411        } else {
 1412            None
 1413        };
 1414
 1415        let breakpoint_store = match (mode, project.as_ref()) {
 1416            (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1417            _ => None,
 1418        };
 1419
 1420        let mut code_action_providers = Vec::new();
 1421        let mut load_uncommitted_diff = None;
 1422        if let Some(project) = project.clone() {
 1423            load_uncommitted_diff = Some(
 1424                get_uncommitted_diff_for_buffer(
 1425                    &project,
 1426                    buffer.read(cx).all_buffers(),
 1427                    buffer.clone(),
 1428                    cx,
 1429                )
 1430                .shared(),
 1431            );
 1432            code_action_providers.push(Rc::new(project) as Rc<_>);
 1433        }
 1434
 1435        let mut this = Self {
 1436            focus_handle,
 1437            show_cursor_when_unfocused: false,
 1438            last_focused_descendant: None,
 1439            buffer: buffer.clone(),
 1440            display_map: display_map.clone(),
 1441            selections,
 1442            scroll_manager: ScrollManager::new(cx),
 1443            columnar_selection_tail: None,
 1444            add_selections_state: None,
 1445            select_next_state: None,
 1446            select_prev_state: None,
 1447            selection_history: Default::default(),
 1448            autoclose_regions: Default::default(),
 1449            snippet_stack: Default::default(),
 1450            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1451            ime_transaction: Default::default(),
 1452            active_diagnostics: None,
 1453            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1454            inline_diagnostics_update: Task::ready(()),
 1455            inline_diagnostics: Vec::new(),
 1456            soft_wrap_mode_override,
 1457            hard_wrap: None,
 1458            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1459            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1460            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1461            project,
 1462            blink_manager: blink_manager.clone(),
 1463            show_local_selections: true,
 1464            show_scrollbars: true,
 1465            mode,
 1466            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1467            show_gutter: mode == EditorMode::Full,
 1468            show_line_numbers: None,
 1469            use_relative_line_numbers: None,
 1470            show_git_diff_gutter: None,
 1471            show_code_actions: None,
 1472            show_runnables: None,
 1473            show_breakpoints: None,
 1474            show_wrap_guides: None,
 1475            show_indent_guides,
 1476            placeholder_text: None,
 1477            highlight_order: 0,
 1478            highlighted_rows: HashMap::default(),
 1479            background_highlights: Default::default(),
 1480            gutter_highlights: TreeMap::default(),
 1481            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1482            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1483            nav_history: None,
 1484            context_menu: RefCell::new(None),
 1485            context_menu_options: None,
 1486            mouse_context_menu: None,
 1487            completion_tasks: Default::default(),
 1488            signature_help_state: SignatureHelpState::default(),
 1489            auto_signature_help: None,
 1490            find_all_references_task_sources: Vec::new(),
 1491            next_completion_id: 0,
 1492            next_inlay_id: 0,
 1493            code_action_providers,
 1494            available_code_actions: Default::default(),
 1495            code_actions_task: Default::default(),
 1496            selection_highlight_task: Default::default(),
 1497            document_highlights_task: Default::default(),
 1498            linked_editing_range_task: Default::default(),
 1499            pending_rename: Default::default(),
 1500            searchable: true,
 1501            cursor_shape: EditorSettings::get_global(cx)
 1502                .cursor_shape
 1503                .unwrap_or_default(),
 1504            current_line_highlight: None,
 1505            autoindent_mode: Some(AutoindentMode::EachLine),
 1506            collapse_matches: false,
 1507            workspace: None,
 1508            input_enabled: true,
 1509            use_modal_editing: mode == EditorMode::Full,
 1510            read_only: false,
 1511            use_autoclose: true,
 1512            use_auto_surround: true,
 1513            auto_replace_emoji_shortcode: false,
 1514            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1515            leader_peer_id: None,
 1516            remote_id: None,
 1517            hover_state: Default::default(),
 1518            pending_mouse_down: None,
 1519            hovered_link_state: Default::default(),
 1520            edit_prediction_provider: None,
 1521            active_inline_completion: None,
 1522            stale_inline_completion_in_menu: None,
 1523            edit_prediction_preview: EditPredictionPreview::Inactive {
 1524                released_too_fast: false,
 1525            },
 1526            inline_diagnostics_enabled: mode == EditorMode::Full,
 1527            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1528
 1529            gutter_hovered: false,
 1530            pixel_position_of_newest_cursor: None,
 1531            last_bounds: None,
 1532            last_position_map: None,
 1533            expect_bounds_change: None,
 1534            gutter_dimensions: GutterDimensions::default(),
 1535            style: None,
 1536            show_cursor_names: false,
 1537            hovered_cursors: Default::default(),
 1538            next_editor_action_id: EditorActionId::default(),
 1539            editor_actions: Rc::default(),
 1540            inline_completions_hidden_for_vim_mode: false,
 1541            show_inline_completions_override: None,
 1542            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1543            edit_prediction_settings: EditPredictionSettings::Disabled,
 1544            edit_prediction_indent_conflict: false,
 1545            edit_prediction_requires_modifier_in_indent_conflict: true,
 1546            custom_context_menu: None,
 1547            show_git_blame_gutter: false,
 1548            show_git_blame_inline: false,
 1549            show_selection_menu: None,
 1550            show_git_blame_inline_delay_task: None,
 1551            git_blame_inline_tooltip: None,
 1552            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1553            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1554            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1555                .session
 1556                .restore_unsaved_buffers,
 1557            blame: None,
 1558            blame_subscription: None,
 1559            tasks: Default::default(),
 1560
 1561            breakpoint_store,
 1562            gutter_breakpoint_indicator: (None, None),
 1563            _subscriptions: vec![
 1564                cx.observe(&buffer, Self::on_buffer_changed),
 1565                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1566                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1567                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1568                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1569                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1570                cx.observe_window_activation(window, |editor, window, cx| {
 1571                    let active = window.is_window_active();
 1572                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1573                        if active {
 1574                            blink_manager.enable(cx);
 1575                        } else {
 1576                            blink_manager.disable(cx);
 1577                        }
 1578                    });
 1579                }),
 1580            ],
 1581            tasks_update_task: None,
 1582            linked_edit_ranges: Default::default(),
 1583            in_project_search: false,
 1584            previous_search_ranges: None,
 1585            breadcrumb_header: None,
 1586            focused_block: None,
 1587            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1588            addons: HashMap::default(),
 1589            registered_buffers: HashMap::default(),
 1590            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1591            selection_mark_mode: false,
 1592            toggle_fold_multiple_buffers: Task::ready(()),
 1593            serialize_selections: Task::ready(()),
 1594            serialize_folds: Task::ready(()),
 1595            text_style_refinement: None,
 1596            load_diff_task: load_uncommitted_diff,
 1597            mouse_cursor_hidden: false,
 1598            hide_mouse_mode: EditorSettings::get_global(cx)
 1599                .hide_mouse
 1600                .unwrap_or_default(),
 1601        };
 1602        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1603            this._subscriptions
 1604                .push(cx.observe(breakpoints, |_, _, cx| {
 1605                    cx.notify();
 1606                }));
 1607        }
 1608        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1609        this._subscriptions.extend(project_subscriptions);
 1610        this._subscriptions
 1611            .push(cx.subscribe_self(|editor, e: &EditorEvent, cx| {
 1612                if let EditorEvent::SelectionsChanged { local } = e {
 1613                    if *local {
 1614                        let new_anchor = editor.scroll_manager.anchor();
 1615                        editor.update_restoration_data(cx, move |data| {
 1616                            data.scroll_anchor = new_anchor;
 1617                        });
 1618                    }
 1619                }
 1620            }));
 1621
 1622        this.end_selection(window, cx);
 1623        this.scroll_manager.show_scrollbars(window, cx);
 1624        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1625
 1626        if mode == EditorMode::Full {
 1627            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1628            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1629
 1630            if this.git_blame_inline_enabled {
 1631                this.git_blame_inline_enabled = true;
 1632                this.start_git_blame_inline(false, window, cx);
 1633            }
 1634
 1635            this.go_to_active_debug_line(window, cx);
 1636
 1637            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1638                if let Some(project) = this.project.as_ref() {
 1639                    let handle = project.update(cx, |project, cx| {
 1640                        project.register_buffer_with_language_servers(&buffer, cx)
 1641                    });
 1642                    this.registered_buffers
 1643                        .insert(buffer.read(cx).remote_id(), handle);
 1644                }
 1645            }
 1646        }
 1647
 1648        this.report_editor_event("Editor Opened", None, cx);
 1649        this
 1650    }
 1651
 1652    pub fn deploy_mouse_context_menu(
 1653        &mut self,
 1654        position: gpui::Point<Pixels>,
 1655        context_menu: Entity<ContextMenu>,
 1656        window: &mut Window,
 1657        cx: &mut Context<Self>,
 1658    ) {
 1659        self.mouse_context_menu = Some(MouseContextMenu::new(
 1660            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1661            context_menu,
 1662            window,
 1663            cx,
 1664        ));
 1665    }
 1666
 1667    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1668        self.mouse_context_menu
 1669            .as_ref()
 1670            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1671    }
 1672
 1673    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1674        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1675    }
 1676
 1677    fn key_context_internal(
 1678        &self,
 1679        has_active_edit_prediction: bool,
 1680        window: &Window,
 1681        cx: &App,
 1682    ) -> KeyContext {
 1683        let mut key_context = KeyContext::new_with_defaults();
 1684        key_context.add("Editor");
 1685        let mode = match self.mode {
 1686            EditorMode::SingleLine { .. } => "single_line",
 1687            EditorMode::AutoHeight { .. } => "auto_height",
 1688            EditorMode::Full => "full",
 1689        };
 1690
 1691        if EditorSettings::jupyter_enabled(cx) {
 1692            key_context.add("jupyter");
 1693        }
 1694
 1695        key_context.set("mode", mode);
 1696        if self.pending_rename.is_some() {
 1697            key_context.add("renaming");
 1698        }
 1699
 1700        match self.context_menu.borrow().as_ref() {
 1701            Some(CodeContextMenu::Completions(_)) => {
 1702                key_context.add("menu");
 1703                key_context.add("showing_completions");
 1704            }
 1705            Some(CodeContextMenu::CodeActions(_)) => {
 1706                key_context.add("menu");
 1707                key_context.add("showing_code_actions")
 1708            }
 1709            None => {}
 1710        }
 1711
 1712        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1713        if !self.focus_handle(cx).contains_focused(window, cx)
 1714            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1715        {
 1716            for addon in self.addons.values() {
 1717                addon.extend_key_context(&mut key_context, cx)
 1718            }
 1719        }
 1720
 1721        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1722            if let Some(extension) = singleton_buffer
 1723                .read(cx)
 1724                .file()
 1725                .and_then(|file| file.path().extension()?.to_str())
 1726            {
 1727                key_context.set("extension", extension.to_string());
 1728            }
 1729        } else {
 1730            key_context.add("multibuffer");
 1731        }
 1732
 1733        if has_active_edit_prediction {
 1734            if self.edit_prediction_in_conflict() {
 1735                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1736            } else {
 1737                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1738                key_context.add("copilot_suggestion");
 1739            }
 1740        }
 1741
 1742        if self.selection_mark_mode {
 1743            key_context.add("selection_mode");
 1744        }
 1745
 1746        key_context
 1747    }
 1748
 1749    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 1750        self.mouse_cursor_hidden = match origin {
 1751            HideMouseCursorOrigin::TypingAction => {
 1752                matches!(
 1753                    self.hide_mouse_mode,
 1754                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 1755                )
 1756            }
 1757            HideMouseCursorOrigin::MovementAction => {
 1758                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 1759            }
 1760        };
 1761    }
 1762
 1763    pub fn edit_prediction_in_conflict(&self) -> bool {
 1764        if !self.show_edit_predictions_in_menu() {
 1765            return false;
 1766        }
 1767
 1768        let showing_completions = self
 1769            .context_menu
 1770            .borrow()
 1771            .as_ref()
 1772            .map_or(false, |context| {
 1773                matches!(context, CodeContextMenu::Completions(_))
 1774            });
 1775
 1776        showing_completions
 1777            || self.edit_prediction_requires_modifier()
 1778            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1779            // bindings to insert tab characters.
 1780            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1781    }
 1782
 1783    pub fn accept_edit_prediction_keybind(
 1784        &self,
 1785        window: &Window,
 1786        cx: &App,
 1787    ) -> AcceptEditPredictionBinding {
 1788        let key_context = self.key_context_internal(true, window, cx);
 1789        let in_conflict = self.edit_prediction_in_conflict();
 1790
 1791        AcceptEditPredictionBinding(
 1792            window
 1793                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1794                .into_iter()
 1795                .filter(|binding| {
 1796                    !in_conflict
 1797                        || binding
 1798                            .keystrokes()
 1799                            .first()
 1800                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1801                })
 1802                .rev()
 1803                .min_by_key(|binding| {
 1804                    binding
 1805                        .keystrokes()
 1806                        .first()
 1807                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1808                }),
 1809        )
 1810    }
 1811
 1812    pub fn new_file(
 1813        workspace: &mut Workspace,
 1814        _: &workspace::NewFile,
 1815        window: &mut Window,
 1816        cx: &mut Context<Workspace>,
 1817    ) {
 1818        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1819            "Failed to create buffer",
 1820            window,
 1821            cx,
 1822            |e, _, _| match e.error_code() {
 1823                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1824                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1825                e.error_tag("required").unwrap_or("the latest version")
 1826            )),
 1827                _ => None,
 1828            },
 1829        );
 1830    }
 1831
 1832    pub fn new_in_workspace(
 1833        workspace: &mut Workspace,
 1834        window: &mut Window,
 1835        cx: &mut Context<Workspace>,
 1836    ) -> Task<Result<Entity<Editor>>> {
 1837        let project = workspace.project().clone();
 1838        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1839
 1840        cx.spawn_in(window, async move |workspace, cx| {
 1841            let buffer = create.await?;
 1842            workspace.update_in(cx, |workspace, window, cx| {
 1843                let editor =
 1844                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1845                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1846                editor
 1847            })
 1848        })
 1849    }
 1850
 1851    fn new_file_vertical(
 1852        workspace: &mut Workspace,
 1853        _: &workspace::NewFileSplitVertical,
 1854        window: &mut Window,
 1855        cx: &mut Context<Workspace>,
 1856    ) {
 1857        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1858    }
 1859
 1860    fn new_file_horizontal(
 1861        workspace: &mut Workspace,
 1862        _: &workspace::NewFileSplitHorizontal,
 1863        window: &mut Window,
 1864        cx: &mut Context<Workspace>,
 1865    ) {
 1866        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1867    }
 1868
 1869    fn new_file_in_direction(
 1870        workspace: &mut Workspace,
 1871        direction: SplitDirection,
 1872        window: &mut Window,
 1873        cx: &mut Context<Workspace>,
 1874    ) {
 1875        let project = workspace.project().clone();
 1876        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1877
 1878        cx.spawn_in(window, async move |workspace, cx| {
 1879            let buffer = create.await?;
 1880            workspace.update_in(cx, move |workspace, window, cx| {
 1881                workspace.split_item(
 1882                    direction,
 1883                    Box::new(
 1884                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1885                    ),
 1886                    window,
 1887                    cx,
 1888                )
 1889            })?;
 1890            anyhow::Ok(())
 1891        })
 1892        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1893            match e.error_code() {
 1894                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1895                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1896                e.error_tag("required").unwrap_or("the latest version")
 1897            )),
 1898                _ => None,
 1899            }
 1900        });
 1901    }
 1902
 1903    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1904        self.leader_peer_id
 1905    }
 1906
 1907    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1908        &self.buffer
 1909    }
 1910
 1911    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1912        self.workspace.as_ref()?.0.upgrade()
 1913    }
 1914
 1915    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1916        self.buffer().read(cx).title(cx)
 1917    }
 1918
 1919    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1920        let git_blame_gutter_max_author_length = self
 1921            .render_git_blame_gutter(cx)
 1922            .then(|| {
 1923                if let Some(blame) = self.blame.as_ref() {
 1924                    let max_author_length =
 1925                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1926                    Some(max_author_length)
 1927                } else {
 1928                    None
 1929                }
 1930            })
 1931            .flatten();
 1932
 1933        EditorSnapshot {
 1934            mode: self.mode,
 1935            show_gutter: self.show_gutter,
 1936            show_line_numbers: self.show_line_numbers,
 1937            show_git_diff_gutter: self.show_git_diff_gutter,
 1938            show_code_actions: self.show_code_actions,
 1939            show_runnables: self.show_runnables,
 1940            show_breakpoints: self.show_breakpoints,
 1941            git_blame_gutter_max_author_length,
 1942            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1943            scroll_anchor: self.scroll_manager.anchor(),
 1944            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1945            placeholder_text: self.placeholder_text.clone(),
 1946            is_focused: self.focus_handle.is_focused(window),
 1947            current_line_highlight: self
 1948                .current_line_highlight
 1949                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1950            gutter_hovered: self.gutter_hovered,
 1951        }
 1952    }
 1953
 1954    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1955        self.buffer.read(cx).language_at(point, cx)
 1956    }
 1957
 1958    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1959        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1960    }
 1961
 1962    pub fn active_excerpt(
 1963        &self,
 1964        cx: &App,
 1965    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1966        self.buffer
 1967            .read(cx)
 1968            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1969    }
 1970
 1971    pub fn mode(&self) -> EditorMode {
 1972        self.mode
 1973    }
 1974
 1975    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1976        self.collaboration_hub.as_deref()
 1977    }
 1978
 1979    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1980        self.collaboration_hub = Some(hub);
 1981    }
 1982
 1983    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1984        self.in_project_search = in_project_search;
 1985    }
 1986
 1987    pub fn set_custom_context_menu(
 1988        &mut self,
 1989        f: impl 'static
 1990        + Fn(
 1991            &mut Self,
 1992            DisplayPoint,
 1993            &mut Window,
 1994            &mut Context<Self>,
 1995        ) -> Option<Entity<ui::ContextMenu>>,
 1996    ) {
 1997        self.custom_context_menu = Some(Box::new(f))
 1998    }
 1999
 2000    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2001        self.completion_provider = provider;
 2002    }
 2003
 2004    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2005        self.semantics_provider.clone()
 2006    }
 2007
 2008    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2009        self.semantics_provider = provider;
 2010    }
 2011
 2012    pub fn set_edit_prediction_provider<T>(
 2013        &mut self,
 2014        provider: Option<Entity<T>>,
 2015        window: &mut Window,
 2016        cx: &mut Context<Self>,
 2017    ) where
 2018        T: EditPredictionProvider,
 2019    {
 2020        self.edit_prediction_provider =
 2021            provider.map(|provider| RegisteredInlineCompletionProvider {
 2022                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2023                    if this.focus_handle.is_focused(window) {
 2024                        this.update_visible_inline_completion(window, cx);
 2025                    }
 2026                }),
 2027                provider: Arc::new(provider),
 2028            });
 2029        self.update_edit_prediction_settings(cx);
 2030        self.refresh_inline_completion(false, false, window, cx);
 2031    }
 2032
 2033    pub fn placeholder_text(&self) -> Option<&str> {
 2034        self.placeholder_text.as_deref()
 2035    }
 2036
 2037    pub fn set_placeholder_text(
 2038        &mut self,
 2039        placeholder_text: impl Into<Arc<str>>,
 2040        cx: &mut Context<Self>,
 2041    ) {
 2042        let placeholder_text = Some(placeholder_text.into());
 2043        if self.placeholder_text != placeholder_text {
 2044            self.placeholder_text = placeholder_text;
 2045            cx.notify();
 2046        }
 2047    }
 2048
 2049    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2050        self.cursor_shape = cursor_shape;
 2051
 2052        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2053        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2054
 2055        cx.notify();
 2056    }
 2057
 2058    pub fn set_current_line_highlight(
 2059        &mut self,
 2060        current_line_highlight: Option<CurrentLineHighlight>,
 2061    ) {
 2062        self.current_line_highlight = current_line_highlight;
 2063    }
 2064
 2065    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2066        self.collapse_matches = collapse_matches;
 2067    }
 2068
 2069    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2070        let buffers = self.buffer.read(cx).all_buffers();
 2071        let Some(project) = self.project.as_ref() else {
 2072            return;
 2073        };
 2074        project.update(cx, |project, cx| {
 2075            for buffer in buffers {
 2076                self.registered_buffers
 2077                    .entry(buffer.read(cx).remote_id())
 2078                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2079            }
 2080        })
 2081    }
 2082
 2083    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2084        if self.collapse_matches {
 2085            return range.start..range.start;
 2086        }
 2087        range.clone()
 2088    }
 2089
 2090    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2091        if self.display_map.read(cx).clip_at_line_ends != clip {
 2092            self.display_map
 2093                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2094        }
 2095    }
 2096
 2097    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2098        self.input_enabled = input_enabled;
 2099    }
 2100
 2101    pub fn set_inline_completions_hidden_for_vim_mode(
 2102        &mut self,
 2103        hidden: bool,
 2104        window: &mut Window,
 2105        cx: &mut Context<Self>,
 2106    ) {
 2107        if hidden != self.inline_completions_hidden_for_vim_mode {
 2108            self.inline_completions_hidden_for_vim_mode = hidden;
 2109            if hidden {
 2110                self.update_visible_inline_completion(window, cx);
 2111            } else {
 2112                self.refresh_inline_completion(true, false, window, cx);
 2113            }
 2114        }
 2115    }
 2116
 2117    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2118        self.menu_inline_completions_policy = value;
 2119    }
 2120
 2121    pub fn set_autoindent(&mut self, autoindent: bool) {
 2122        if autoindent {
 2123            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2124        } else {
 2125            self.autoindent_mode = None;
 2126        }
 2127    }
 2128
 2129    pub fn read_only(&self, cx: &App) -> bool {
 2130        self.read_only || self.buffer.read(cx).read_only()
 2131    }
 2132
 2133    pub fn set_read_only(&mut self, read_only: bool) {
 2134        self.read_only = read_only;
 2135    }
 2136
 2137    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2138        self.use_autoclose = autoclose;
 2139    }
 2140
 2141    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2142        self.use_auto_surround = auto_surround;
 2143    }
 2144
 2145    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2146        self.auto_replace_emoji_shortcode = auto_replace;
 2147    }
 2148
 2149    pub fn toggle_edit_predictions(
 2150        &mut self,
 2151        _: &ToggleEditPrediction,
 2152        window: &mut Window,
 2153        cx: &mut Context<Self>,
 2154    ) {
 2155        if self.show_inline_completions_override.is_some() {
 2156            self.set_show_edit_predictions(None, window, cx);
 2157        } else {
 2158            let show_edit_predictions = !self.edit_predictions_enabled();
 2159            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2160        }
 2161    }
 2162
 2163    pub fn set_show_edit_predictions(
 2164        &mut self,
 2165        show_edit_predictions: Option<bool>,
 2166        window: &mut Window,
 2167        cx: &mut Context<Self>,
 2168    ) {
 2169        self.show_inline_completions_override = show_edit_predictions;
 2170        self.update_edit_prediction_settings(cx);
 2171
 2172        if let Some(false) = show_edit_predictions {
 2173            self.discard_inline_completion(false, cx);
 2174        } else {
 2175            self.refresh_inline_completion(false, true, window, cx);
 2176        }
 2177    }
 2178
 2179    fn inline_completions_disabled_in_scope(
 2180        &self,
 2181        buffer: &Entity<Buffer>,
 2182        buffer_position: language::Anchor,
 2183        cx: &App,
 2184    ) -> bool {
 2185        let snapshot = buffer.read(cx).snapshot();
 2186        let settings = snapshot.settings_at(buffer_position, cx);
 2187
 2188        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2189            return false;
 2190        };
 2191
 2192        scope.override_name().map_or(false, |scope_name| {
 2193            settings
 2194                .edit_predictions_disabled_in
 2195                .iter()
 2196                .any(|s| s == scope_name)
 2197        })
 2198    }
 2199
 2200    pub fn set_use_modal_editing(&mut self, to: bool) {
 2201        self.use_modal_editing = to;
 2202    }
 2203
 2204    pub fn use_modal_editing(&self) -> bool {
 2205        self.use_modal_editing
 2206    }
 2207
 2208    fn selections_did_change(
 2209        &mut self,
 2210        local: bool,
 2211        old_cursor_position: &Anchor,
 2212        show_completions: bool,
 2213        window: &mut Window,
 2214        cx: &mut Context<Self>,
 2215    ) {
 2216        window.invalidate_character_coordinates();
 2217
 2218        // Copy selections to primary selection buffer
 2219        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2220        if local {
 2221            let selections = self.selections.all::<usize>(cx);
 2222            let buffer_handle = self.buffer.read(cx).read(cx);
 2223
 2224            let mut text = String::new();
 2225            for (index, selection) in selections.iter().enumerate() {
 2226                let text_for_selection = buffer_handle
 2227                    .text_for_range(selection.start..selection.end)
 2228                    .collect::<String>();
 2229
 2230                text.push_str(&text_for_selection);
 2231                if index != selections.len() - 1 {
 2232                    text.push('\n');
 2233                }
 2234            }
 2235
 2236            if !text.is_empty() {
 2237                cx.write_to_primary(ClipboardItem::new_string(text));
 2238            }
 2239        }
 2240
 2241        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2242            self.buffer.update(cx, |buffer, cx| {
 2243                buffer.set_active_selections(
 2244                    &self.selections.disjoint_anchors(),
 2245                    self.selections.line_mode,
 2246                    self.cursor_shape,
 2247                    cx,
 2248                )
 2249            });
 2250        }
 2251        let display_map = self
 2252            .display_map
 2253            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2254        let buffer = &display_map.buffer_snapshot;
 2255        self.add_selections_state = None;
 2256        self.select_next_state = None;
 2257        self.select_prev_state = None;
 2258        self.select_syntax_node_history.try_clear();
 2259        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2260        self.snippet_stack
 2261            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2262        self.take_rename(false, window, cx);
 2263
 2264        let new_cursor_position = self.selections.newest_anchor().head();
 2265
 2266        self.push_to_nav_history(
 2267            *old_cursor_position,
 2268            Some(new_cursor_position.to_point(buffer)),
 2269            false,
 2270            cx,
 2271        );
 2272
 2273        if local {
 2274            let new_cursor_position = self.selections.newest_anchor().head();
 2275            let mut context_menu = self.context_menu.borrow_mut();
 2276            let completion_menu = match context_menu.as_ref() {
 2277                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2278                _ => {
 2279                    *context_menu = None;
 2280                    None
 2281                }
 2282            };
 2283            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2284                if !self.registered_buffers.contains_key(&buffer_id) {
 2285                    if let Some(project) = self.project.as_ref() {
 2286                        project.update(cx, |project, cx| {
 2287                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2288                                return;
 2289                            };
 2290                            self.registered_buffers.insert(
 2291                                buffer_id,
 2292                                project.register_buffer_with_language_servers(&buffer, cx),
 2293                            );
 2294                        })
 2295                    }
 2296                }
 2297            }
 2298
 2299            if let Some(completion_menu) = completion_menu {
 2300                let cursor_position = new_cursor_position.to_offset(buffer);
 2301                let (word_range, kind) =
 2302                    buffer.surrounding_word(completion_menu.initial_position, true);
 2303                if kind == Some(CharKind::Word)
 2304                    && word_range.to_inclusive().contains(&cursor_position)
 2305                {
 2306                    let mut completion_menu = completion_menu.clone();
 2307                    drop(context_menu);
 2308
 2309                    let query = Self::completion_query(buffer, cursor_position);
 2310                    cx.spawn(async move |this, cx| {
 2311                        completion_menu
 2312                            .filter(query.as_deref(), cx.background_executor().clone())
 2313                            .await;
 2314
 2315                        this.update(cx, |this, cx| {
 2316                            let mut context_menu = this.context_menu.borrow_mut();
 2317                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2318                            else {
 2319                                return;
 2320                            };
 2321
 2322                            if menu.id > completion_menu.id {
 2323                                return;
 2324                            }
 2325
 2326                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2327                            drop(context_menu);
 2328                            cx.notify();
 2329                        })
 2330                    })
 2331                    .detach();
 2332
 2333                    if show_completions {
 2334                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2335                    }
 2336                } else {
 2337                    drop(context_menu);
 2338                    self.hide_context_menu(window, cx);
 2339                }
 2340            } else {
 2341                drop(context_menu);
 2342            }
 2343
 2344            hide_hover(self, cx);
 2345
 2346            if old_cursor_position.to_display_point(&display_map).row()
 2347                != new_cursor_position.to_display_point(&display_map).row()
 2348            {
 2349                self.available_code_actions.take();
 2350            }
 2351            self.refresh_code_actions(window, cx);
 2352            self.refresh_document_highlights(cx);
 2353            self.refresh_selected_text_highlights(window, cx);
 2354            refresh_matching_bracket_highlights(self, window, cx);
 2355            self.update_visible_inline_completion(window, cx);
 2356            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2357            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2358            if self.git_blame_inline_enabled {
 2359                self.start_inline_blame_timer(window, cx);
 2360            }
 2361        }
 2362
 2363        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2364        cx.emit(EditorEvent::SelectionsChanged { local });
 2365
 2366        let selections = &self.selections.disjoint;
 2367        if selections.len() == 1 {
 2368            cx.emit(SearchEvent::ActiveMatchChanged)
 2369        }
 2370        if local && self.is_singleton(cx) {
 2371            let inmemory_selections = selections.iter().map(|s| s.range()).collect();
 2372            self.update_restoration_data(cx, |data| {
 2373                data.selections = inmemory_selections;
 2374            });
 2375
 2376            if WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2377            {
 2378                if let Some(workspace_id) =
 2379                    self.workspace.as_ref().and_then(|workspace| workspace.1)
 2380                {
 2381                    let snapshot = self.buffer().read(cx).snapshot(cx);
 2382                    let selections = selections.clone();
 2383                    let background_executor = cx.background_executor().clone();
 2384                    let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2385                    self.serialize_selections = cx.background_spawn(async move {
 2386                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2387                    let db_selections = selections
 2388                        .iter()
 2389                        .map(|selection| {
 2390                            (
 2391                                selection.start.to_offset(&snapshot),
 2392                                selection.end.to_offset(&snapshot),
 2393                            )
 2394                        })
 2395                        .collect();
 2396
 2397                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2398                        .await
 2399                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2400                        .log_err();
 2401                });
 2402                }
 2403            }
 2404        }
 2405
 2406        cx.notify();
 2407    }
 2408
 2409    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2410        if !self.is_singleton(cx)
 2411            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
 2412        {
 2413            return;
 2414        }
 2415
 2416        let snapshot = self.buffer().read(cx).snapshot(cx);
 2417        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2418            display_map
 2419                .snapshot(cx)
 2420                .folds_in_range(0..snapshot.len())
 2421                .map(|fold| fold.range.deref().clone())
 2422                .collect()
 2423        });
 2424        self.update_restoration_data(cx, |data| {
 2425            data.folds = inmemory_folds;
 2426        });
 2427
 2428        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2429            return;
 2430        };
 2431        let background_executor = cx.background_executor().clone();
 2432        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2433        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2434            display_map
 2435                .snapshot(cx)
 2436                .folds_in_range(0..snapshot.len())
 2437                .map(|fold| {
 2438                    (
 2439                        fold.range.start.to_offset(&snapshot),
 2440                        fold.range.end.to_offset(&snapshot),
 2441                    )
 2442                })
 2443                .collect()
 2444        });
 2445        self.serialize_folds = cx.background_spawn(async move {
 2446            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2447            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2448                .await
 2449                .with_context(|| {
 2450                    format!(
 2451                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2452                    )
 2453                })
 2454                .log_err();
 2455        });
 2456    }
 2457
 2458    pub fn sync_selections(
 2459        &mut self,
 2460        other: Entity<Editor>,
 2461        cx: &mut Context<Self>,
 2462    ) -> gpui::Subscription {
 2463        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2464        self.selections.change_with(cx, |selections| {
 2465            selections.select_anchors(other_selections);
 2466        });
 2467
 2468        let other_subscription =
 2469            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2470                EditorEvent::SelectionsChanged { local: true } => {
 2471                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2472                    if other_selections.is_empty() {
 2473                        return;
 2474                    }
 2475                    this.selections.change_with(cx, |selections| {
 2476                        selections.select_anchors(other_selections);
 2477                    });
 2478                }
 2479                _ => {}
 2480            });
 2481
 2482        let this_subscription =
 2483            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2484                EditorEvent::SelectionsChanged { local: true } => {
 2485                    let these_selections = this.selections.disjoint.to_vec();
 2486                    if these_selections.is_empty() {
 2487                        return;
 2488                    }
 2489                    other.update(cx, |other_editor, cx| {
 2490                        other_editor.selections.change_with(cx, |selections| {
 2491                            selections.select_anchors(these_selections);
 2492                        })
 2493                    });
 2494                }
 2495                _ => {}
 2496            });
 2497
 2498        Subscription::join(other_subscription, this_subscription)
 2499    }
 2500
 2501    pub fn change_selections<R>(
 2502        &mut self,
 2503        autoscroll: Option<Autoscroll>,
 2504        window: &mut Window,
 2505        cx: &mut Context<Self>,
 2506        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2507    ) -> R {
 2508        self.change_selections_inner(autoscroll, true, window, cx, change)
 2509    }
 2510
 2511    fn change_selections_inner<R>(
 2512        &mut self,
 2513        autoscroll: Option<Autoscroll>,
 2514        request_completions: bool,
 2515        window: &mut Window,
 2516        cx: &mut Context<Self>,
 2517        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2518    ) -> R {
 2519        let old_cursor_position = self.selections.newest_anchor().head();
 2520        self.push_to_selection_history();
 2521
 2522        let (changed, result) = self.selections.change_with(cx, change);
 2523
 2524        if changed {
 2525            if let Some(autoscroll) = autoscroll {
 2526                self.request_autoscroll(autoscroll, cx);
 2527            }
 2528            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2529
 2530            if self.should_open_signature_help_automatically(
 2531                &old_cursor_position,
 2532                self.signature_help_state.backspace_pressed(),
 2533                cx,
 2534            ) {
 2535                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2536            }
 2537            self.signature_help_state.set_backspace_pressed(false);
 2538        }
 2539
 2540        result
 2541    }
 2542
 2543    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2544    where
 2545        I: IntoIterator<Item = (Range<S>, T)>,
 2546        S: ToOffset,
 2547        T: Into<Arc<str>>,
 2548    {
 2549        if self.read_only(cx) {
 2550            return;
 2551        }
 2552
 2553        self.buffer
 2554            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2555    }
 2556
 2557    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2558    where
 2559        I: IntoIterator<Item = (Range<S>, T)>,
 2560        S: ToOffset,
 2561        T: Into<Arc<str>>,
 2562    {
 2563        if self.read_only(cx) {
 2564            return;
 2565        }
 2566
 2567        self.buffer.update(cx, |buffer, cx| {
 2568            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2569        });
 2570    }
 2571
 2572    pub fn edit_with_block_indent<I, S, T>(
 2573        &mut self,
 2574        edits: I,
 2575        original_indent_columns: Vec<Option<u32>>,
 2576        cx: &mut Context<Self>,
 2577    ) where
 2578        I: IntoIterator<Item = (Range<S>, T)>,
 2579        S: ToOffset,
 2580        T: Into<Arc<str>>,
 2581    {
 2582        if self.read_only(cx) {
 2583            return;
 2584        }
 2585
 2586        self.buffer.update(cx, |buffer, cx| {
 2587            buffer.edit(
 2588                edits,
 2589                Some(AutoindentMode::Block {
 2590                    original_indent_columns,
 2591                }),
 2592                cx,
 2593            )
 2594        });
 2595    }
 2596
 2597    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2598        self.hide_context_menu(window, cx);
 2599
 2600        match phase {
 2601            SelectPhase::Begin {
 2602                position,
 2603                add,
 2604                click_count,
 2605            } => self.begin_selection(position, add, click_count, window, cx),
 2606            SelectPhase::BeginColumnar {
 2607                position,
 2608                goal_column,
 2609                reset,
 2610            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2611            SelectPhase::Extend {
 2612                position,
 2613                click_count,
 2614            } => self.extend_selection(position, click_count, window, cx),
 2615            SelectPhase::Update {
 2616                position,
 2617                goal_column,
 2618                scroll_delta,
 2619            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2620            SelectPhase::End => self.end_selection(window, cx),
 2621        }
 2622    }
 2623
 2624    fn extend_selection(
 2625        &mut self,
 2626        position: DisplayPoint,
 2627        click_count: usize,
 2628        window: &mut Window,
 2629        cx: &mut Context<Self>,
 2630    ) {
 2631        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2632        let tail = self.selections.newest::<usize>(cx).tail();
 2633        self.begin_selection(position, false, click_count, window, cx);
 2634
 2635        let position = position.to_offset(&display_map, Bias::Left);
 2636        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2637
 2638        let mut pending_selection = self
 2639            .selections
 2640            .pending_anchor()
 2641            .expect("extend_selection not called with pending selection");
 2642        if position >= tail {
 2643            pending_selection.start = tail_anchor;
 2644        } else {
 2645            pending_selection.end = tail_anchor;
 2646            pending_selection.reversed = true;
 2647        }
 2648
 2649        let mut pending_mode = self.selections.pending_mode().unwrap();
 2650        match &mut pending_mode {
 2651            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2652            _ => {}
 2653        }
 2654
 2655        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2656            s.set_pending(pending_selection, pending_mode)
 2657        });
 2658    }
 2659
 2660    fn begin_selection(
 2661        &mut self,
 2662        position: DisplayPoint,
 2663        add: bool,
 2664        click_count: usize,
 2665        window: &mut Window,
 2666        cx: &mut Context<Self>,
 2667    ) {
 2668        if !self.focus_handle.is_focused(window) {
 2669            self.last_focused_descendant = None;
 2670            window.focus(&self.focus_handle);
 2671        }
 2672
 2673        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2674        let buffer = &display_map.buffer_snapshot;
 2675        let newest_selection = self.selections.newest_anchor().clone();
 2676        let position = display_map.clip_point(position, Bias::Left);
 2677
 2678        let start;
 2679        let end;
 2680        let mode;
 2681        let mut auto_scroll;
 2682        match click_count {
 2683            1 => {
 2684                start = buffer.anchor_before(position.to_point(&display_map));
 2685                end = start;
 2686                mode = SelectMode::Character;
 2687                auto_scroll = true;
 2688            }
 2689            2 => {
 2690                let range = movement::surrounding_word(&display_map, position);
 2691                start = buffer.anchor_before(range.start.to_point(&display_map));
 2692                end = buffer.anchor_before(range.end.to_point(&display_map));
 2693                mode = SelectMode::Word(start..end);
 2694                auto_scroll = true;
 2695            }
 2696            3 => {
 2697                let position = display_map
 2698                    .clip_point(position, Bias::Left)
 2699                    .to_point(&display_map);
 2700                let line_start = display_map.prev_line_boundary(position).0;
 2701                let next_line_start = buffer.clip_point(
 2702                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2703                    Bias::Left,
 2704                );
 2705                start = buffer.anchor_before(line_start);
 2706                end = buffer.anchor_before(next_line_start);
 2707                mode = SelectMode::Line(start..end);
 2708                auto_scroll = true;
 2709            }
 2710            _ => {
 2711                start = buffer.anchor_before(0);
 2712                end = buffer.anchor_before(buffer.len());
 2713                mode = SelectMode::All;
 2714                auto_scroll = false;
 2715            }
 2716        }
 2717        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2718
 2719        let point_to_delete: Option<usize> = {
 2720            let selected_points: Vec<Selection<Point>> =
 2721                self.selections.disjoint_in_range(start..end, cx);
 2722
 2723            if !add || click_count > 1 {
 2724                None
 2725            } else if !selected_points.is_empty() {
 2726                Some(selected_points[0].id)
 2727            } else {
 2728                let clicked_point_already_selected =
 2729                    self.selections.disjoint.iter().find(|selection| {
 2730                        selection.start.to_point(buffer) == start.to_point(buffer)
 2731                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2732                    });
 2733
 2734                clicked_point_already_selected.map(|selection| selection.id)
 2735            }
 2736        };
 2737
 2738        let selections_count = self.selections.count();
 2739
 2740        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2741            if let Some(point_to_delete) = point_to_delete {
 2742                s.delete(point_to_delete);
 2743
 2744                if selections_count == 1 {
 2745                    s.set_pending_anchor_range(start..end, mode);
 2746                }
 2747            } else {
 2748                if !add {
 2749                    s.clear_disjoint();
 2750                } else if click_count > 1 {
 2751                    s.delete(newest_selection.id)
 2752                }
 2753
 2754                s.set_pending_anchor_range(start..end, mode);
 2755            }
 2756        });
 2757    }
 2758
 2759    fn begin_columnar_selection(
 2760        &mut self,
 2761        position: DisplayPoint,
 2762        goal_column: u32,
 2763        reset: bool,
 2764        window: &mut Window,
 2765        cx: &mut Context<Self>,
 2766    ) {
 2767        if !self.focus_handle.is_focused(window) {
 2768            self.last_focused_descendant = None;
 2769            window.focus(&self.focus_handle);
 2770        }
 2771
 2772        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2773
 2774        if reset {
 2775            let pointer_position = display_map
 2776                .buffer_snapshot
 2777                .anchor_before(position.to_point(&display_map));
 2778
 2779            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2780                s.clear_disjoint();
 2781                s.set_pending_anchor_range(
 2782                    pointer_position..pointer_position,
 2783                    SelectMode::Character,
 2784                );
 2785            });
 2786        }
 2787
 2788        let tail = self.selections.newest::<Point>(cx).tail();
 2789        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2790
 2791        if !reset {
 2792            self.select_columns(
 2793                tail.to_display_point(&display_map),
 2794                position,
 2795                goal_column,
 2796                &display_map,
 2797                window,
 2798                cx,
 2799            );
 2800        }
 2801    }
 2802
 2803    fn update_selection(
 2804        &mut self,
 2805        position: DisplayPoint,
 2806        goal_column: u32,
 2807        scroll_delta: gpui::Point<f32>,
 2808        window: &mut Window,
 2809        cx: &mut Context<Self>,
 2810    ) {
 2811        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2812
 2813        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2814            let tail = tail.to_display_point(&display_map);
 2815            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2816        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2817            let buffer = self.buffer.read(cx).snapshot(cx);
 2818            let head;
 2819            let tail;
 2820            let mode = self.selections.pending_mode().unwrap();
 2821            match &mode {
 2822                SelectMode::Character => {
 2823                    head = position.to_point(&display_map);
 2824                    tail = pending.tail().to_point(&buffer);
 2825                }
 2826                SelectMode::Word(original_range) => {
 2827                    let original_display_range = original_range.start.to_display_point(&display_map)
 2828                        ..original_range.end.to_display_point(&display_map);
 2829                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2830                        ..original_display_range.end.to_point(&display_map);
 2831                    if movement::is_inside_word(&display_map, position)
 2832                        || original_display_range.contains(&position)
 2833                    {
 2834                        let word_range = movement::surrounding_word(&display_map, position);
 2835                        if word_range.start < original_display_range.start {
 2836                            head = word_range.start.to_point(&display_map);
 2837                        } else {
 2838                            head = word_range.end.to_point(&display_map);
 2839                        }
 2840                    } else {
 2841                        head = position.to_point(&display_map);
 2842                    }
 2843
 2844                    if head <= original_buffer_range.start {
 2845                        tail = original_buffer_range.end;
 2846                    } else {
 2847                        tail = original_buffer_range.start;
 2848                    }
 2849                }
 2850                SelectMode::Line(original_range) => {
 2851                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2852
 2853                    let position = display_map
 2854                        .clip_point(position, Bias::Left)
 2855                        .to_point(&display_map);
 2856                    let line_start = display_map.prev_line_boundary(position).0;
 2857                    let next_line_start = buffer.clip_point(
 2858                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2859                        Bias::Left,
 2860                    );
 2861
 2862                    if line_start < original_range.start {
 2863                        head = line_start
 2864                    } else {
 2865                        head = next_line_start
 2866                    }
 2867
 2868                    if head <= original_range.start {
 2869                        tail = original_range.end;
 2870                    } else {
 2871                        tail = original_range.start;
 2872                    }
 2873                }
 2874                SelectMode::All => {
 2875                    return;
 2876                }
 2877            };
 2878
 2879            if head < tail {
 2880                pending.start = buffer.anchor_before(head);
 2881                pending.end = buffer.anchor_before(tail);
 2882                pending.reversed = true;
 2883            } else {
 2884                pending.start = buffer.anchor_before(tail);
 2885                pending.end = buffer.anchor_before(head);
 2886                pending.reversed = false;
 2887            }
 2888
 2889            self.change_selections(None, window, cx, |s| {
 2890                s.set_pending(pending, mode);
 2891            });
 2892        } else {
 2893            log::error!("update_selection dispatched with no pending selection");
 2894            return;
 2895        }
 2896
 2897        self.apply_scroll_delta(scroll_delta, window, cx);
 2898        cx.notify();
 2899    }
 2900
 2901    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2902        self.columnar_selection_tail.take();
 2903        if self.selections.pending_anchor().is_some() {
 2904            let selections = self.selections.all::<usize>(cx);
 2905            self.change_selections(None, window, cx, |s| {
 2906                s.select(selections);
 2907                s.clear_pending();
 2908            });
 2909        }
 2910    }
 2911
 2912    fn select_columns(
 2913        &mut self,
 2914        tail: DisplayPoint,
 2915        head: DisplayPoint,
 2916        goal_column: u32,
 2917        display_map: &DisplaySnapshot,
 2918        window: &mut Window,
 2919        cx: &mut Context<Self>,
 2920    ) {
 2921        let start_row = cmp::min(tail.row(), head.row());
 2922        let end_row = cmp::max(tail.row(), head.row());
 2923        let start_column = cmp::min(tail.column(), goal_column);
 2924        let end_column = cmp::max(tail.column(), goal_column);
 2925        let reversed = start_column < tail.column();
 2926
 2927        let selection_ranges = (start_row.0..=end_row.0)
 2928            .map(DisplayRow)
 2929            .filter_map(|row| {
 2930                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2931                    let start = display_map
 2932                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2933                        .to_point(display_map);
 2934                    let end = display_map
 2935                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2936                        .to_point(display_map);
 2937                    if reversed {
 2938                        Some(end..start)
 2939                    } else {
 2940                        Some(start..end)
 2941                    }
 2942                } else {
 2943                    None
 2944                }
 2945            })
 2946            .collect::<Vec<_>>();
 2947
 2948        self.change_selections(None, window, cx, |s| {
 2949            s.select_ranges(selection_ranges);
 2950        });
 2951        cx.notify();
 2952    }
 2953
 2954    pub fn has_pending_nonempty_selection(&self) -> bool {
 2955        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2956            Some(Selection { start, end, .. }) => start != end,
 2957            None => false,
 2958        };
 2959
 2960        pending_nonempty_selection
 2961            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2962    }
 2963
 2964    pub fn has_pending_selection(&self) -> bool {
 2965        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2966    }
 2967
 2968    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2969        self.selection_mark_mode = false;
 2970
 2971        if self.clear_expanded_diff_hunks(cx) {
 2972            cx.notify();
 2973            return;
 2974        }
 2975        if self.dismiss_menus_and_popups(true, window, cx) {
 2976            return;
 2977        }
 2978
 2979        if self.mode == EditorMode::Full
 2980            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2981        {
 2982            return;
 2983        }
 2984
 2985        cx.propagate();
 2986    }
 2987
 2988    pub fn dismiss_menus_and_popups(
 2989        &mut self,
 2990        is_user_requested: bool,
 2991        window: &mut Window,
 2992        cx: &mut Context<Self>,
 2993    ) -> bool {
 2994        if self.take_rename(false, window, cx).is_some() {
 2995            return true;
 2996        }
 2997
 2998        if hide_hover(self, cx) {
 2999            return true;
 3000        }
 3001
 3002        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3003            return true;
 3004        }
 3005
 3006        if self.hide_context_menu(window, cx).is_some() {
 3007            return true;
 3008        }
 3009
 3010        if self.mouse_context_menu.take().is_some() {
 3011            return true;
 3012        }
 3013
 3014        if is_user_requested && self.discard_inline_completion(true, cx) {
 3015            return true;
 3016        }
 3017
 3018        if self.snippet_stack.pop().is_some() {
 3019            return true;
 3020        }
 3021
 3022        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3023            self.dismiss_diagnostics(cx);
 3024            return true;
 3025        }
 3026
 3027        false
 3028    }
 3029
 3030    fn linked_editing_ranges_for(
 3031        &self,
 3032        selection: Range<text::Anchor>,
 3033        cx: &App,
 3034    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3035        if self.linked_edit_ranges.is_empty() {
 3036            return None;
 3037        }
 3038        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3039            selection.end.buffer_id.and_then(|end_buffer_id| {
 3040                if selection.start.buffer_id != Some(end_buffer_id) {
 3041                    return None;
 3042                }
 3043                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3044                let snapshot = buffer.read(cx).snapshot();
 3045                self.linked_edit_ranges
 3046                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3047                    .map(|ranges| (ranges, snapshot, buffer))
 3048            })?;
 3049        use text::ToOffset as TO;
 3050        // find offset from the start of current range to current cursor position
 3051        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3052
 3053        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3054        let start_difference = start_offset - start_byte_offset;
 3055        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3056        let end_difference = end_offset - start_byte_offset;
 3057        // Current range has associated linked ranges.
 3058        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3059        for range in linked_ranges.iter() {
 3060            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3061            let end_offset = start_offset + end_difference;
 3062            let start_offset = start_offset + start_difference;
 3063            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3064                continue;
 3065            }
 3066            if self.selections.disjoint_anchor_ranges().any(|s| {
 3067                if s.start.buffer_id != selection.start.buffer_id
 3068                    || s.end.buffer_id != selection.end.buffer_id
 3069                {
 3070                    return false;
 3071                }
 3072                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3073                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3074            }) {
 3075                continue;
 3076            }
 3077            let start = buffer_snapshot.anchor_after(start_offset);
 3078            let end = buffer_snapshot.anchor_after(end_offset);
 3079            linked_edits
 3080                .entry(buffer.clone())
 3081                .or_default()
 3082                .push(start..end);
 3083        }
 3084        Some(linked_edits)
 3085    }
 3086
 3087    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3088        let text: Arc<str> = text.into();
 3089
 3090        if self.read_only(cx) {
 3091            return;
 3092        }
 3093
 3094        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3095
 3096        let selections = self.selections.all_adjusted(cx);
 3097        let mut bracket_inserted = false;
 3098        let mut edits = Vec::new();
 3099        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3100        let mut new_selections = Vec::with_capacity(selections.len());
 3101        let mut new_autoclose_regions = Vec::new();
 3102        let snapshot = self.buffer.read(cx).read(cx);
 3103
 3104        for (selection, autoclose_region) in
 3105            self.selections_with_autoclose_regions(selections, &snapshot)
 3106        {
 3107            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3108                // Determine if the inserted text matches the opening or closing
 3109                // bracket of any of this language's bracket pairs.
 3110                let mut bracket_pair = None;
 3111                let mut is_bracket_pair_start = false;
 3112                let mut is_bracket_pair_end = false;
 3113                if !text.is_empty() {
 3114                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3115                    //  and they are removing the character that triggered IME popup.
 3116                    for (pair, enabled) in scope.brackets() {
 3117                        if !pair.close && !pair.surround {
 3118                            continue;
 3119                        }
 3120
 3121                        if enabled && pair.start.ends_with(text.as_ref()) {
 3122                            let prefix_len = pair.start.len() - text.len();
 3123                            let preceding_text_matches_prefix = prefix_len == 0
 3124                                || (selection.start.column >= (prefix_len as u32)
 3125                                    && snapshot.contains_str_at(
 3126                                        Point::new(
 3127                                            selection.start.row,
 3128                                            selection.start.column - (prefix_len as u32),
 3129                                        ),
 3130                                        &pair.start[..prefix_len],
 3131                                    ));
 3132                            if preceding_text_matches_prefix {
 3133                                bracket_pair = Some(pair.clone());
 3134                                is_bracket_pair_start = true;
 3135                                break;
 3136                            }
 3137                        }
 3138                        if pair.end.as_str() == text.as_ref() {
 3139                            bracket_pair = Some(pair.clone());
 3140                            is_bracket_pair_end = true;
 3141                            break;
 3142                        }
 3143                    }
 3144                }
 3145
 3146                if let Some(bracket_pair) = bracket_pair {
 3147                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3148                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3149                    let auto_surround =
 3150                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3151                    if selection.is_empty() {
 3152                        if is_bracket_pair_start {
 3153                            // If the inserted text is a suffix of an opening bracket and the
 3154                            // selection is preceded by the rest of the opening bracket, then
 3155                            // insert the closing bracket.
 3156                            let following_text_allows_autoclose = snapshot
 3157                                .chars_at(selection.start)
 3158                                .next()
 3159                                .map_or(true, |c| scope.should_autoclose_before(c));
 3160
 3161                            let preceding_text_allows_autoclose = selection.start.column == 0
 3162                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3163                                    true,
 3164                                    |c| {
 3165                                        bracket_pair.start != bracket_pair.end
 3166                                            || !snapshot
 3167                                                .char_classifier_at(selection.start)
 3168                                                .is_word(c)
 3169                                    },
 3170                                );
 3171
 3172                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3173                                && bracket_pair.start.len() == 1
 3174                            {
 3175                                let target = bracket_pair.start.chars().next().unwrap();
 3176                                let current_line_count = snapshot
 3177                                    .reversed_chars_at(selection.start)
 3178                                    .take_while(|&c| c != '\n')
 3179                                    .filter(|&c| c == target)
 3180                                    .count();
 3181                                current_line_count % 2 == 1
 3182                            } else {
 3183                                false
 3184                            };
 3185
 3186                            if autoclose
 3187                                && bracket_pair.close
 3188                                && following_text_allows_autoclose
 3189                                && preceding_text_allows_autoclose
 3190                                && !is_closing_quote
 3191                            {
 3192                                let anchor = snapshot.anchor_before(selection.end);
 3193                                new_selections.push((selection.map(|_| anchor), text.len()));
 3194                                new_autoclose_regions.push((
 3195                                    anchor,
 3196                                    text.len(),
 3197                                    selection.id,
 3198                                    bracket_pair.clone(),
 3199                                ));
 3200                                edits.push((
 3201                                    selection.range(),
 3202                                    format!("{}{}", text, bracket_pair.end).into(),
 3203                                ));
 3204                                bracket_inserted = true;
 3205                                continue;
 3206                            }
 3207                        }
 3208
 3209                        if let Some(region) = autoclose_region {
 3210                            // If the selection is followed by an auto-inserted closing bracket,
 3211                            // then don't insert that closing bracket again; just move the selection
 3212                            // past the closing bracket.
 3213                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3214                                && text.as_ref() == region.pair.end.as_str();
 3215                            if should_skip {
 3216                                let anchor = snapshot.anchor_after(selection.end);
 3217                                new_selections
 3218                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3219                                continue;
 3220                            }
 3221                        }
 3222
 3223                        let always_treat_brackets_as_autoclosed = snapshot
 3224                            .language_settings_at(selection.start, cx)
 3225                            .always_treat_brackets_as_autoclosed;
 3226                        if always_treat_brackets_as_autoclosed
 3227                            && is_bracket_pair_end
 3228                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3229                        {
 3230                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3231                            // and the inserted text is a closing bracket and the selection is followed
 3232                            // by the closing bracket then move the selection past the closing bracket.
 3233                            let anchor = snapshot.anchor_after(selection.end);
 3234                            new_selections.push((selection.map(|_| anchor), text.len()));
 3235                            continue;
 3236                        }
 3237                    }
 3238                    // If an opening bracket is 1 character long and is typed while
 3239                    // text is selected, then surround that text with the bracket pair.
 3240                    else if auto_surround
 3241                        && bracket_pair.surround
 3242                        && is_bracket_pair_start
 3243                        && bracket_pair.start.chars().count() == 1
 3244                    {
 3245                        edits.push((selection.start..selection.start, text.clone()));
 3246                        edits.push((
 3247                            selection.end..selection.end,
 3248                            bracket_pair.end.as_str().into(),
 3249                        ));
 3250                        bracket_inserted = true;
 3251                        new_selections.push((
 3252                            Selection {
 3253                                id: selection.id,
 3254                                start: snapshot.anchor_after(selection.start),
 3255                                end: snapshot.anchor_before(selection.end),
 3256                                reversed: selection.reversed,
 3257                                goal: selection.goal,
 3258                            },
 3259                            0,
 3260                        ));
 3261                        continue;
 3262                    }
 3263                }
 3264            }
 3265
 3266            if self.auto_replace_emoji_shortcode
 3267                && selection.is_empty()
 3268                && text.as_ref().ends_with(':')
 3269            {
 3270                if let Some(possible_emoji_short_code) =
 3271                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3272                {
 3273                    if !possible_emoji_short_code.is_empty() {
 3274                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3275                            let emoji_shortcode_start = Point::new(
 3276                                selection.start.row,
 3277                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3278                            );
 3279
 3280                            // Remove shortcode from buffer
 3281                            edits.push((
 3282                                emoji_shortcode_start..selection.start,
 3283                                "".to_string().into(),
 3284                            ));
 3285                            new_selections.push((
 3286                                Selection {
 3287                                    id: selection.id,
 3288                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3289                                    end: snapshot.anchor_before(selection.start),
 3290                                    reversed: selection.reversed,
 3291                                    goal: selection.goal,
 3292                                },
 3293                                0,
 3294                            ));
 3295
 3296                            // Insert emoji
 3297                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3298                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3299                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3300
 3301                            continue;
 3302                        }
 3303                    }
 3304                }
 3305            }
 3306
 3307            // If not handling any auto-close operation, then just replace the selected
 3308            // text with the given input and move the selection to the end of the
 3309            // newly inserted text.
 3310            let anchor = snapshot.anchor_after(selection.end);
 3311            if !self.linked_edit_ranges.is_empty() {
 3312                let start_anchor = snapshot.anchor_before(selection.start);
 3313
 3314                let is_word_char = text.chars().next().map_or(true, |char| {
 3315                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3316                    classifier.is_word(char)
 3317                });
 3318
 3319                if is_word_char {
 3320                    if let Some(ranges) = self
 3321                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3322                    {
 3323                        for (buffer, edits) in ranges {
 3324                            linked_edits
 3325                                .entry(buffer.clone())
 3326                                .or_default()
 3327                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3328                        }
 3329                    }
 3330                }
 3331            }
 3332
 3333            new_selections.push((selection.map(|_| anchor), 0));
 3334            edits.push((selection.start..selection.end, text.clone()));
 3335        }
 3336
 3337        drop(snapshot);
 3338
 3339        self.transact(window, cx, |this, window, cx| {
 3340            let initial_buffer_versions =
 3341                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3342
 3343            this.buffer.update(cx, |buffer, cx| {
 3344                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3345            });
 3346            for (buffer, edits) in linked_edits {
 3347                buffer.update(cx, |buffer, cx| {
 3348                    let snapshot = buffer.snapshot();
 3349                    let edits = edits
 3350                        .into_iter()
 3351                        .map(|(range, text)| {
 3352                            use text::ToPoint as TP;
 3353                            let end_point = TP::to_point(&range.end, &snapshot);
 3354                            let start_point = TP::to_point(&range.start, &snapshot);
 3355                            (start_point..end_point, text)
 3356                        })
 3357                        .sorted_by_key(|(range, _)| range.start);
 3358                    buffer.edit(edits, None, cx);
 3359                })
 3360            }
 3361            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3362            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3363            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3364            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3365                .zip(new_selection_deltas)
 3366                .map(|(selection, delta)| Selection {
 3367                    id: selection.id,
 3368                    start: selection.start + delta,
 3369                    end: selection.end + delta,
 3370                    reversed: selection.reversed,
 3371                    goal: SelectionGoal::None,
 3372                })
 3373                .collect::<Vec<_>>();
 3374
 3375            let mut i = 0;
 3376            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3377                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3378                let start = map.buffer_snapshot.anchor_before(position);
 3379                let end = map.buffer_snapshot.anchor_after(position);
 3380                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3381                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3382                        Ordering::Less => i += 1,
 3383                        Ordering::Greater => break,
 3384                        Ordering::Equal => {
 3385                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3386                                Ordering::Less => i += 1,
 3387                                Ordering::Equal => break,
 3388                                Ordering::Greater => break,
 3389                            }
 3390                        }
 3391                    }
 3392                }
 3393                this.autoclose_regions.insert(
 3394                    i,
 3395                    AutocloseRegion {
 3396                        selection_id,
 3397                        range: start..end,
 3398                        pair,
 3399                    },
 3400                );
 3401            }
 3402
 3403            let had_active_inline_completion = this.has_active_inline_completion();
 3404            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3405                s.select(new_selections)
 3406            });
 3407
 3408            if !bracket_inserted {
 3409                if let Some(on_type_format_task) =
 3410                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3411                {
 3412                    on_type_format_task.detach_and_log_err(cx);
 3413                }
 3414            }
 3415
 3416            let editor_settings = EditorSettings::get_global(cx);
 3417            if bracket_inserted
 3418                && (editor_settings.auto_signature_help
 3419                    || editor_settings.show_signature_help_after_edits)
 3420            {
 3421                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3422            }
 3423
 3424            let trigger_in_words =
 3425                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3426            if this.hard_wrap.is_some() {
 3427                let latest: Range<Point> = this.selections.newest(cx).range();
 3428                if latest.is_empty()
 3429                    && this
 3430                        .buffer()
 3431                        .read(cx)
 3432                        .snapshot(cx)
 3433                        .line_len(MultiBufferRow(latest.start.row))
 3434                        == latest.start.column
 3435                {
 3436                    this.rewrap_impl(
 3437                        RewrapOptions {
 3438                            override_language_settings: true,
 3439                            preserve_existing_whitespace: true,
 3440                        },
 3441                        cx,
 3442                    )
 3443                }
 3444            }
 3445            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3446            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3447            this.refresh_inline_completion(true, false, window, cx);
 3448            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3449        });
 3450    }
 3451
 3452    fn find_possible_emoji_shortcode_at_position(
 3453        snapshot: &MultiBufferSnapshot,
 3454        position: Point,
 3455    ) -> Option<String> {
 3456        let mut chars = Vec::new();
 3457        let mut found_colon = false;
 3458        for char in snapshot.reversed_chars_at(position).take(100) {
 3459            // Found a possible emoji shortcode in the middle of the buffer
 3460            if found_colon {
 3461                if char.is_whitespace() {
 3462                    chars.reverse();
 3463                    return Some(chars.iter().collect());
 3464                }
 3465                // If the previous character is not a whitespace, we are in the middle of a word
 3466                // and we only want to complete the shortcode if the word is made up of other emojis
 3467                let mut containing_word = String::new();
 3468                for ch in snapshot
 3469                    .reversed_chars_at(position)
 3470                    .skip(chars.len() + 1)
 3471                    .take(100)
 3472                {
 3473                    if ch.is_whitespace() {
 3474                        break;
 3475                    }
 3476                    containing_word.push(ch);
 3477                }
 3478                let containing_word = containing_word.chars().rev().collect::<String>();
 3479                if util::word_consists_of_emojis(containing_word.as_str()) {
 3480                    chars.reverse();
 3481                    return Some(chars.iter().collect());
 3482                }
 3483            }
 3484
 3485            if char.is_whitespace() || !char.is_ascii() {
 3486                return None;
 3487            }
 3488            if char == ':' {
 3489                found_colon = true;
 3490            } else {
 3491                chars.push(char);
 3492            }
 3493        }
 3494        // Found a possible emoji shortcode at the beginning of the buffer
 3495        chars.reverse();
 3496        Some(chars.iter().collect())
 3497    }
 3498
 3499    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3500        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3501        self.transact(window, cx, |this, window, cx| {
 3502            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3503                let selections = this.selections.all::<usize>(cx);
 3504                let multi_buffer = this.buffer.read(cx);
 3505                let buffer = multi_buffer.snapshot(cx);
 3506                selections
 3507                    .iter()
 3508                    .map(|selection| {
 3509                        let start_point = selection.start.to_point(&buffer);
 3510                        let mut indent =
 3511                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3512                        indent.len = cmp::min(indent.len, start_point.column);
 3513                        let start = selection.start;
 3514                        let end = selection.end;
 3515                        let selection_is_empty = start == end;
 3516                        let language_scope = buffer.language_scope_at(start);
 3517                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3518                            &language_scope
 3519                        {
 3520                            let insert_extra_newline =
 3521                                insert_extra_newline_brackets(&buffer, start..end, language)
 3522                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3523
 3524                            // Comment extension on newline is allowed only for cursor selections
 3525                            let comment_delimiter = maybe!({
 3526                                if !selection_is_empty {
 3527                                    return None;
 3528                                }
 3529
 3530                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3531                                    return None;
 3532                                }
 3533
 3534                                let delimiters = language.line_comment_prefixes();
 3535                                let max_len_of_delimiter =
 3536                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3537                                let (snapshot, range) =
 3538                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3539
 3540                                let mut index_of_first_non_whitespace = 0;
 3541                                let comment_candidate = snapshot
 3542                                    .chars_for_range(range)
 3543                                    .skip_while(|c| {
 3544                                        let should_skip = c.is_whitespace();
 3545                                        if should_skip {
 3546                                            index_of_first_non_whitespace += 1;
 3547                                        }
 3548                                        should_skip
 3549                                    })
 3550                                    .take(max_len_of_delimiter)
 3551                                    .collect::<String>();
 3552                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3553                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3554                                })?;
 3555                                let cursor_is_placed_after_comment_marker =
 3556                                    index_of_first_non_whitespace + comment_prefix.len()
 3557                                        <= start_point.column as usize;
 3558                                if cursor_is_placed_after_comment_marker {
 3559                                    Some(comment_prefix.clone())
 3560                                } else {
 3561                                    None
 3562                                }
 3563                            });
 3564                            (comment_delimiter, insert_extra_newline)
 3565                        } else {
 3566                            (None, false)
 3567                        };
 3568
 3569                        let capacity_for_delimiter = comment_delimiter
 3570                            .as_deref()
 3571                            .map(str::len)
 3572                            .unwrap_or_default();
 3573                        let mut new_text =
 3574                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3575                        new_text.push('\n');
 3576                        new_text.extend(indent.chars());
 3577                        if let Some(delimiter) = &comment_delimiter {
 3578                            new_text.push_str(delimiter);
 3579                        }
 3580                        if insert_extra_newline {
 3581                            new_text = new_text.repeat(2);
 3582                        }
 3583
 3584                        let anchor = buffer.anchor_after(end);
 3585                        let new_selection = selection.map(|_| anchor);
 3586                        (
 3587                            (start..end, new_text),
 3588                            (insert_extra_newline, new_selection),
 3589                        )
 3590                    })
 3591                    .unzip()
 3592            };
 3593
 3594            this.edit_with_autoindent(edits, cx);
 3595            let buffer = this.buffer.read(cx).snapshot(cx);
 3596            let new_selections = selection_fixup_info
 3597                .into_iter()
 3598                .map(|(extra_newline_inserted, new_selection)| {
 3599                    let mut cursor = new_selection.end.to_point(&buffer);
 3600                    if extra_newline_inserted {
 3601                        cursor.row -= 1;
 3602                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3603                    }
 3604                    new_selection.map(|_| cursor)
 3605                })
 3606                .collect();
 3607
 3608            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3609                s.select(new_selections)
 3610            });
 3611            this.refresh_inline_completion(true, false, window, cx);
 3612        });
 3613    }
 3614
 3615    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3616        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3617
 3618        let buffer = self.buffer.read(cx);
 3619        let snapshot = buffer.snapshot(cx);
 3620
 3621        let mut edits = Vec::new();
 3622        let mut rows = Vec::new();
 3623
 3624        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3625            let cursor = selection.head();
 3626            let row = cursor.row;
 3627
 3628            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3629
 3630            let newline = "\n".to_string();
 3631            edits.push((start_of_line..start_of_line, newline));
 3632
 3633            rows.push(row + rows_inserted as u32);
 3634        }
 3635
 3636        self.transact(window, cx, |editor, window, cx| {
 3637            editor.edit(edits, cx);
 3638
 3639            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3640                let mut index = 0;
 3641                s.move_cursors_with(|map, _, _| {
 3642                    let row = rows[index];
 3643                    index += 1;
 3644
 3645                    let point = Point::new(row, 0);
 3646                    let boundary = map.next_line_boundary(point).1;
 3647                    let clipped = map.clip_point(boundary, Bias::Left);
 3648
 3649                    (clipped, SelectionGoal::None)
 3650                });
 3651            });
 3652
 3653            let mut indent_edits = Vec::new();
 3654            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3655            for row in rows {
 3656                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3657                for (row, indent) in indents {
 3658                    if indent.len == 0 {
 3659                        continue;
 3660                    }
 3661
 3662                    let text = match indent.kind {
 3663                        IndentKind::Space => " ".repeat(indent.len as usize),
 3664                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3665                    };
 3666                    let point = Point::new(row.0, 0);
 3667                    indent_edits.push((point..point, text));
 3668                }
 3669            }
 3670            editor.edit(indent_edits, cx);
 3671        });
 3672    }
 3673
 3674    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3675        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3676
 3677        let buffer = self.buffer.read(cx);
 3678        let snapshot = buffer.snapshot(cx);
 3679
 3680        let mut edits = Vec::new();
 3681        let mut rows = Vec::new();
 3682        let mut rows_inserted = 0;
 3683
 3684        for selection in self.selections.all_adjusted(cx) {
 3685            let cursor = selection.head();
 3686            let row = cursor.row;
 3687
 3688            let point = Point::new(row + 1, 0);
 3689            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3690
 3691            let newline = "\n".to_string();
 3692            edits.push((start_of_line..start_of_line, newline));
 3693
 3694            rows_inserted += 1;
 3695            rows.push(row + rows_inserted);
 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 insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3737        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3738            original_indent_columns: Vec::new(),
 3739        });
 3740        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3741    }
 3742
 3743    fn insert_with_autoindent_mode(
 3744        &mut self,
 3745        text: &str,
 3746        autoindent_mode: Option<AutoindentMode>,
 3747        window: &mut Window,
 3748        cx: &mut Context<Self>,
 3749    ) {
 3750        if self.read_only(cx) {
 3751            return;
 3752        }
 3753
 3754        let text: Arc<str> = text.into();
 3755        self.transact(window, cx, |this, window, cx| {
 3756            let old_selections = this.selections.all_adjusted(cx);
 3757            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3758                let anchors = {
 3759                    let snapshot = buffer.read(cx);
 3760                    old_selections
 3761                        .iter()
 3762                        .map(|s| {
 3763                            let anchor = snapshot.anchor_after(s.head());
 3764                            s.map(|_| anchor)
 3765                        })
 3766                        .collect::<Vec<_>>()
 3767                };
 3768                buffer.edit(
 3769                    old_selections
 3770                        .iter()
 3771                        .map(|s| (s.start..s.end, text.clone())),
 3772                    autoindent_mode,
 3773                    cx,
 3774                );
 3775                anchors
 3776            });
 3777
 3778            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3779                s.select_anchors(selection_anchors);
 3780            });
 3781
 3782            cx.notify();
 3783        });
 3784    }
 3785
 3786    fn trigger_completion_on_input(
 3787        &mut self,
 3788        text: &str,
 3789        trigger_in_words: bool,
 3790        window: &mut Window,
 3791        cx: &mut Context<Self>,
 3792    ) {
 3793        let ignore_completion_provider = self
 3794            .context_menu
 3795            .borrow()
 3796            .as_ref()
 3797            .map(|menu| match menu {
 3798                CodeContextMenu::Completions(completions_menu) => {
 3799                    completions_menu.ignore_completion_provider
 3800                }
 3801                CodeContextMenu::CodeActions(_) => false,
 3802            })
 3803            .unwrap_or(false);
 3804
 3805        if ignore_completion_provider {
 3806            self.show_word_completions(&ShowWordCompletions, window, cx);
 3807        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3808            self.show_completions(
 3809                &ShowCompletions {
 3810                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3811                },
 3812                window,
 3813                cx,
 3814            );
 3815        } else {
 3816            self.hide_context_menu(window, cx);
 3817        }
 3818    }
 3819
 3820    fn is_completion_trigger(
 3821        &self,
 3822        text: &str,
 3823        trigger_in_words: bool,
 3824        cx: &mut Context<Self>,
 3825    ) -> bool {
 3826        let position = self.selections.newest_anchor().head();
 3827        let multibuffer = self.buffer.read(cx);
 3828        let Some(buffer) = position
 3829            .buffer_id
 3830            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3831        else {
 3832            return false;
 3833        };
 3834
 3835        if let Some(completion_provider) = &self.completion_provider {
 3836            completion_provider.is_completion_trigger(
 3837                &buffer,
 3838                position.text_anchor,
 3839                text,
 3840                trigger_in_words,
 3841                cx,
 3842            )
 3843        } else {
 3844            false
 3845        }
 3846    }
 3847
 3848    /// If any empty selections is touching the start of its innermost containing autoclose
 3849    /// region, expand it to select the brackets.
 3850    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3851        let selections = self.selections.all::<usize>(cx);
 3852        let buffer = self.buffer.read(cx).read(cx);
 3853        let new_selections = self
 3854            .selections_with_autoclose_regions(selections, &buffer)
 3855            .map(|(mut selection, region)| {
 3856                if !selection.is_empty() {
 3857                    return selection;
 3858                }
 3859
 3860                if let Some(region) = region {
 3861                    let mut range = region.range.to_offset(&buffer);
 3862                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3863                        range.start -= region.pair.start.len();
 3864                        if buffer.contains_str_at(range.start, &region.pair.start)
 3865                            && buffer.contains_str_at(range.end, &region.pair.end)
 3866                        {
 3867                            range.end += region.pair.end.len();
 3868                            selection.start = range.start;
 3869                            selection.end = range.end;
 3870
 3871                            return selection;
 3872                        }
 3873                    }
 3874                }
 3875
 3876                let always_treat_brackets_as_autoclosed = buffer
 3877                    .language_settings_at(selection.start, cx)
 3878                    .always_treat_brackets_as_autoclosed;
 3879
 3880                if !always_treat_brackets_as_autoclosed {
 3881                    return selection;
 3882                }
 3883
 3884                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3885                    for (pair, enabled) in scope.brackets() {
 3886                        if !enabled || !pair.close {
 3887                            continue;
 3888                        }
 3889
 3890                        if buffer.contains_str_at(selection.start, &pair.end) {
 3891                            let pair_start_len = pair.start.len();
 3892                            if buffer.contains_str_at(
 3893                                selection.start.saturating_sub(pair_start_len),
 3894                                &pair.start,
 3895                            ) {
 3896                                selection.start -= pair_start_len;
 3897                                selection.end += pair.end.len();
 3898
 3899                                return selection;
 3900                            }
 3901                        }
 3902                    }
 3903                }
 3904
 3905                selection
 3906            })
 3907            .collect();
 3908
 3909        drop(buffer);
 3910        self.change_selections(None, window, cx, |selections| {
 3911            selections.select(new_selections)
 3912        });
 3913    }
 3914
 3915    /// Iterate the given selections, and for each one, find the smallest surrounding
 3916    /// autoclose region. This uses the ordering of the selections and the autoclose
 3917    /// regions to avoid repeated comparisons.
 3918    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3919        &'a self,
 3920        selections: impl IntoIterator<Item = Selection<D>>,
 3921        buffer: &'a MultiBufferSnapshot,
 3922    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3923        let mut i = 0;
 3924        let mut regions = self.autoclose_regions.as_slice();
 3925        selections.into_iter().map(move |selection| {
 3926            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3927
 3928            let mut enclosing = None;
 3929            while let Some(pair_state) = regions.get(i) {
 3930                if pair_state.range.end.to_offset(buffer) < range.start {
 3931                    regions = &regions[i + 1..];
 3932                    i = 0;
 3933                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3934                    break;
 3935                } else {
 3936                    if pair_state.selection_id == selection.id {
 3937                        enclosing = Some(pair_state);
 3938                    }
 3939                    i += 1;
 3940                }
 3941            }
 3942
 3943            (selection, enclosing)
 3944        })
 3945    }
 3946
 3947    /// Remove any autoclose regions that no longer contain their selection.
 3948    fn invalidate_autoclose_regions(
 3949        &mut self,
 3950        mut selections: &[Selection<Anchor>],
 3951        buffer: &MultiBufferSnapshot,
 3952    ) {
 3953        self.autoclose_regions.retain(|state| {
 3954            let mut i = 0;
 3955            while let Some(selection) = selections.get(i) {
 3956                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3957                    selections = &selections[1..];
 3958                    continue;
 3959                }
 3960                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3961                    break;
 3962                }
 3963                if selection.id == state.selection_id {
 3964                    return true;
 3965                } else {
 3966                    i += 1;
 3967                }
 3968            }
 3969            false
 3970        });
 3971    }
 3972
 3973    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3974        let offset = position.to_offset(buffer);
 3975        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3976        if offset > word_range.start && kind == Some(CharKind::Word) {
 3977            Some(
 3978                buffer
 3979                    .text_for_range(word_range.start..offset)
 3980                    .collect::<String>(),
 3981            )
 3982        } else {
 3983            None
 3984        }
 3985    }
 3986
 3987    pub fn toggle_inlay_hints(
 3988        &mut self,
 3989        _: &ToggleInlayHints,
 3990        _: &mut Window,
 3991        cx: &mut Context<Self>,
 3992    ) {
 3993        self.refresh_inlay_hints(
 3994            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3995            cx,
 3996        );
 3997    }
 3998
 3999    pub fn inlay_hints_enabled(&self) -> bool {
 4000        self.inlay_hint_cache.enabled
 4001    }
 4002
 4003    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4004        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4005            return;
 4006        }
 4007
 4008        let reason_description = reason.description();
 4009        let ignore_debounce = matches!(
 4010            reason,
 4011            InlayHintRefreshReason::SettingsChange(_)
 4012                | InlayHintRefreshReason::Toggle(_)
 4013                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4014                | InlayHintRefreshReason::ModifiersChanged(_)
 4015        );
 4016        let (invalidate_cache, required_languages) = match reason {
 4017            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4018                match self.inlay_hint_cache.modifiers_override(enabled) {
 4019                    Some(enabled) => {
 4020                        if enabled {
 4021                            (InvalidationStrategy::RefreshRequested, None)
 4022                        } else {
 4023                            self.splice_inlays(
 4024                                &self
 4025                                    .visible_inlay_hints(cx)
 4026                                    .iter()
 4027                                    .map(|inlay| inlay.id)
 4028                                    .collect::<Vec<InlayId>>(),
 4029                                Vec::new(),
 4030                                cx,
 4031                            );
 4032                            return;
 4033                        }
 4034                    }
 4035                    None => return,
 4036                }
 4037            }
 4038            InlayHintRefreshReason::Toggle(enabled) => {
 4039                if self.inlay_hint_cache.toggle(enabled) {
 4040                    if enabled {
 4041                        (InvalidationStrategy::RefreshRequested, None)
 4042                    } else {
 4043                        self.splice_inlays(
 4044                            &self
 4045                                .visible_inlay_hints(cx)
 4046                                .iter()
 4047                                .map(|inlay| inlay.id)
 4048                                .collect::<Vec<InlayId>>(),
 4049                            Vec::new(),
 4050                            cx,
 4051                        );
 4052                        return;
 4053                    }
 4054                } else {
 4055                    return;
 4056                }
 4057            }
 4058            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4059                match self.inlay_hint_cache.update_settings(
 4060                    &self.buffer,
 4061                    new_settings,
 4062                    self.visible_inlay_hints(cx),
 4063                    cx,
 4064                ) {
 4065                    ControlFlow::Break(Some(InlaySplice {
 4066                        to_remove,
 4067                        to_insert,
 4068                    })) => {
 4069                        self.splice_inlays(&to_remove, to_insert, cx);
 4070                        return;
 4071                    }
 4072                    ControlFlow::Break(None) => return,
 4073                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4074                }
 4075            }
 4076            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4077                if let Some(InlaySplice {
 4078                    to_remove,
 4079                    to_insert,
 4080                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4081                {
 4082                    self.splice_inlays(&to_remove, to_insert, cx);
 4083                }
 4084                return;
 4085            }
 4086            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4087            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4088                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4089            }
 4090            InlayHintRefreshReason::RefreshRequested => {
 4091                (InvalidationStrategy::RefreshRequested, None)
 4092            }
 4093        };
 4094
 4095        if let Some(InlaySplice {
 4096            to_remove,
 4097            to_insert,
 4098        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4099            reason_description,
 4100            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4101            invalidate_cache,
 4102            ignore_debounce,
 4103            cx,
 4104        ) {
 4105            self.splice_inlays(&to_remove, to_insert, cx);
 4106        }
 4107    }
 4108
 4109    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4110        self.display_map
 4111            .read(cx)
 4112            .current_inlays()
 4113            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4114            .cloned()
 4115            .collect()
 4116    }
 4117
 4118    pub fn excerpts_for_inlay_hints_query(
 4119        &self,
 4120        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4121        cx: &mut Context<Editor>,
 4122    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4123        let Some(project) = self.project.as_ref() else {
 4124            return HashMap::default();
 4125        };
 4126        let project = project.read(cx);
 4127        let multi_buffer = self.buffer().read(cx);
 4128        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4129        let multi_buffer_visible_start = self
 4130            .scroll_manager
 4131            .anchor()
 4132            .anchor
 4133            .to_point(&multi_buffer_snapshot);
 4134        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4135            multi_buffer_visible_start
 4136                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4137            Bias::Left,
 4138        );
 4139        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4140        multi_buffer_snapshot
 4141            .range_to_buffer_ranges(multi_buffer_visible_range)
 4142            .into_iter()
 4143            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4144            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4145                let buffer_file = project::File::from_dyn(buffer.file())?;
 4146                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4147                let worktree_entry = buffer_worktree
 4148                    .read(cx)
 4149                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4150                if worktree_entry.is_ignored {
 4151                    return None;
 4152                }
 4153
 4154                let language = buffer.language()?;
 4155                if let Some(restrict_to_languages) = restrict_to_languages {
 4156                    if !restrict_to_languages.contains(language) {
 4157                        return None;
 4158                    }
 4159                }
 4160                Some((
 4161                    excerpt_id,
 4162                    (
 4163                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4164                        buffer.version().clone(),
 4165                        excerpt_visible_range,
 4166                    ),
 4167                ))
 4168            })
 4169            .collect()
 4170    }
 4171
 4172    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4173        TextLayoutDetails {
 4174            text_system: window.text_system().clone(),
 4175            editor_style: self.style.clone().unwrap(),
 4176            rem_size: window.rem_size(),
 4177            scroll_anchor: self.scroll_manager.anchor(),
 4178            visible_rows: self.visible_line_count(),
 4179            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4180        }
 4181    }
 4182
 4183    pub fn splice_inlays(
 4184        &self,
 4185        to_remove: &[InlayId],
 4186        to_insert: Vec<Inlay>,
 4187        cx: &mut Context<Self>,
 4188    ) {
 4189        self.display_map.update(cx, |display_map, cx| {
 4190            display_map.splice_inlays(to_remove, to_insert, cx)
 4191        });
 4192        cx.notify();
 4193    }
 4194
 4195    fn trigger_on_type_formatting(
 4196        &self,
 4197        input: String,
 4198        window: &mut Window,
 4199        cx: &mut Context<Self>,
 4200    ) -> Option<Task<Result<()>>> {
 4201        if input.len() != 1 {
 4202            return None;
 4203        }
 4204
 4205        let project = self.project.as_ref()?;
 4206        let position = self.selections.newest_anchor().head();
 4207        let (buffer, buffer_position) = self
 4208            .buffer
 4209            .read(cx)
 4210            .text_anchor_for_position(position, cx)?;
 4211
 4212        let settings = language_settings::language_settings(
 4213            buffer
 4214                .read(cx)
 4215                .language_at(buffer_position)
 4216                .map(|l| l.name()),
 4217            buffer.read(cx).file(),
 4218            cx,
 4219        );
 4220        if !settings.use_on_type_format {
 4221            return None;
 4222        }
 4223
 4224        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4225        // hence we do LSP request & edit on host side only — add formats to host's history.
 4226        let push_to_lsp_host_history = true;
 4227        // If this is not the host, append its history with new edits.
 4228        let push_to_client_history = project.read(cx).is_via_collab();
 4229
 4230        let on_type_formatting = project.update(cx, |project, cx| {
 4231            project.on_type_format(
 4232                buffer.clone(),
 4233                buffer_position,
 4234                input,
 4235                push_to_lsp_host_history,
 4236                cx,
 4237            )
 4238        });
 4239        Some(cx.spawn_in(window, async move |editor, cx| {
 4240            if let Some(transaction) = on_type_formatting.await? {
 4241                if push_to_client_history {
 4242                    buffer
 4243                        .update(cx, |buffer, _| {
 4244                            buffer.push_transaction(transaction, Instant::now());
 4245                        })
 4246                        .ok();
 4247                }
 4248                editor.update(cx, |editor, cx| {
 4249                    editor.refresh_document_highlights(cx);
 4250                })?;
 4251            }
 4252            Ok(())
 4253        }))
 4254    }
 4255
 4256    pub fn show_word_completions(
 4257        &mut self,
 4258        _: &ShowWordCompletions,
 4259        window: &mut Window,
 4260        cx: &mut Context<Self>,
 4261    ) {
 4262        self.open_completions_menu(true, None, window, cx);
 4263    }
 4264
 4265    pub fn show_completions(
 4266        &mut self,
 4267        options: &ShowCompletions,
 4268        window: &mut Window,
 4269        cx: &mut Context<Self>,
 4270    ) {
 4271        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4272    }
 4273
 4274    fn open_completions_menu(
 4275        &mut self,
 4276        ignore_completion_provider: bool,
 4277        trigger: Option<&str>,
 4278        window: &mut Window,
 4279        cx: &mut Context<Self>,
 4280    ) {
 4281        if self.pending_rename.is_some() {
 4282            return;
 4283        }
 4284        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4285            return;
 4286        }
 4287
 4288        let position = self.selections.newest_anchor().head();
 4289        if position.diff_base_anchor.is_some() {
 4290            return;
 4291        }
 4292        let (buffer, buffer_position) =
 4293            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4294                output
 4295            } else {
 4296                return;
 4297            };
 4298        let buffer_snapshot = buffer.read(cx).snapshot();
 4299        let show_completion_documentation = buffer_snapshot
 4300            .settings_at(buffer_position, cx)
 4301            .show_completion_documentation;
 4302
 4303        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4304
 4305        let trigger_kind = match trigger {
 4306            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4307                CompletionTriggerKind::TRIGGER_CHARACTER
 4308            }
 4309            _ => CompletionTriggerKind::INVOKED,
 4310        };
 4311        let completion_context = CompletionContext {
 4312            trigger_character: trigger.and_then(|trigger| {
 4313                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4314                    Some(String::from(trigger))
 4315                } else {
 4316                    None
 4317                }
 4318            }),
 4319            trigger_kind,
 4320        };
 4321
 4322        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4323        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4324            let word_to_exclude = buffer_snapshot
 4325                .text_for_range(old_range.clone())
 4326                .collect::<String>();
 4327            (
 4328                buffer_snapshot.anchor_before(old_range.start)
 4329                    ..buffer_snapshot.anchor_after(old_range.end),
 4330                Some(word_to_exclude),
 4331            )
 4332        } else {
 4333            (buffer_position..buffer_position, None)
 4334        };
 4335
 4336        let completion_settings = language_settings(
 4337            buffer_snapshot
 4338                .language_at(buffer_position)
 4339                .map(|language| language.name()),
 4340            buffer_snapshot.file(),
 4341            cx,
 4342        )
 4343        .completions;
 4344
 4345        // The document can be large, so stay in reasonable bounds when searching for words,
 4346        // otherwise completion pop-up might be slow to appear.
 4347        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4348        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4349        let min_word_search = buffer_snapshot.clip_point(
 4350            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4351            Bias::Left,
 4352        );
 4353        let max_word_search = buffer_snapshot.clip_point(
 4354            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4355            Bias::Right,
 4356        );
 4357        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4358            ..buffer_snapshot.point_to_offset(max_word_search);
 4359
 4360        let provider = self
 4361            .completion_provider
 4362            .as_ref()
 4363            .filter(|_| !ignore_completion_provider);
 4364        let skip_digits = query
 4365            .as_ref()
 4366            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4367
 4368        let (mut words, provided_completions) = match provider {
 4369            Some(provider) => {
 4370                let completions = provider.completions(
 4371                    position.excerpt_id,
 4372                    &buffer,
 4373                    buffer_position,
 4374                    completion_context,
 4375                    window,
 4376                    cx,
 4377                );
 4378
 4379                let words = match completion_settings.words {
 4380                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4381                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4382                        .background_spawn(async move {
 4383                            buffer_snapshot.words_in_range(WordsQuery {
 4384                                fuzzy_contents: None,
 4385                                range: word_search_range,
 4386                                skip_digits,
 4387                            })
 4388                        }),
 4389                };
 4390
 4391                (words, completions)
 4392            }
 4393            None => (
 4394                cx.background_spawn(async move {
 4395                    buffer_snapshot.words_in_range(WordsQuery {
 4396                        fuzzy_contents: None,
 4397                        range: word_search_range,
 4398                        skip_digits,
 4399                    })
 4400                }),
 4401                Task::ready(Ok(None)),
 4402            ),
 4403        };
 4404
 4405        let sort_completions = provider
 4406            .as_ref()
 4407            .map_or(false, |provider| provider.sort_completions());
 4408
 4409        let filter_completions = provider
 4410            .as_ref()
 4411            .map_or(true, |provider| provider.filter_completions());
 4412
 4413        let id = post_inc(&mut self.next_completion_id);
 4414        let task = cx.spawn_in(window, async move |editor, cx| {
 4415            async move {
 4416                editor.update(cx, |this, _| {
 4417                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4418                })?;
 4419
 4420                let mut completions = Vec::new();
 4421                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4422                    completions.extend(provided_completions);
 4423                    if completion_settings.words == WordsCompletionMode::Fallback {
 4424                        words = Task::ready(BTreeMap::default());
 4425                    }
 4426                }
 4427
 4428                let mut words = words.await;
 4429                if let Some(word_to_exclude) = &word_to_exclude {
 4430                    words.remove(word_to_exclude);
 4431                }
 4432                for lsp_completion in &completions {
 4433                    words.remove(&lsp_completion.new_text);
 4434                }
 4435                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4436                    old_range: old_range.clone(),
 4437                    new_text: word.clone(),
 4438                    label: CodeLabel::plain(word, None),
 4439                    icon_path: None,
 4440                    documentation: None,
 4441                    source: CompletionSource::BufferWord {
 4442                        word_range,
 4443                        resolved: false,
 4444                    },
 4445                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4446                    confirm: None,
 4447                }));
 4448
 4449                let menu = if completions.is_empty() {
 4450                    None
 4451                } else {
 4452                    let mut menu = CompletionsMenu::new(
 4453                        id,
 4454                        sort_completions,
 4455                        show_completion_documentation,
 4456                        ignore_completion_provider,
 4457                        position,
 4458                        buffer.clone(),
 4459                        completions.into(),
 4460                    );
 4461
 4462                    menu.filter(
 4463                        if filter_completions {
 4464                            query.as_deref()
 4465                        } else {
 4466                            None
 4467                        },
 4468                        cx.background_executor().clone(),
 4469                    )
 4470                    .await;
 4471
 4472                    menu.visible().then_some(menu)
 4473                };
 4474
 4475                editor.update_in(cx, |editor, window, cx| {
 4476                    match editor.context_menu.borrow().as_ref() {
 4477                        None => {}
 4478                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4479                            if prev_menu.id > id {
 4480                                return;
 4481                            }
 4482                        }
 4483                        _ => return,
 4484                    }
 4485
 4486                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4487                        let mut menu = menu.unwrap();
 4488                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4489
 4490                        *editor.context_menu.borrow_mut() =
 4491                            Some(CodeContextMenu::Completions(menu));
 4492
 4493                        if editor.show_edit_predictions_in_menu() {
 4494                            editor.update_visible_inline_completion(window, cx);
 4495                        } else {
 4496                            editor.discard_inline_completion(false, cx);
 4497                        }
 4498
 4499                        cx.notify();
 4500                    } else if editor.completion_tasks.len() <= 1 {
 4501                        // If there are no more completion tasks and the last menu was
 4502                        // empty, we should hide it.
 4503                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4504                        // If it was already hidden and we don't show inline
 4505                        // completions in the menu, we should also show the
 4506                        // inline-completion when available.
 4507                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4508                            editor.update_visible_inline_completion(window, cx);
 4509                        }
 4510                    }
 4511                })?;
 4512
 4513                anyhow::Ok(())
 4514            }
 4515            .log_err()
 4516            .await
 4517        });
 4518
 4519        self.completion_tasks.push((id, task));
 4520    }
 4521
 4522    #[cfg(feature = "test-support")]
 4523    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4524        let menu = self.context_menu.borrow();
 4525        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4526            let completions = menu.completions.borrow();
 4527            Some(completions.to_vec())
 4528        } else {
 4529            None
 4530        }
 4531    }
 4532
 4533    pub fn confirm_completion(
 4534        &mut self,
 4535        action: &ConfirmCompletion,
 4536        window: &mut Window,
 4537        cx: &mut Context<Self>,
 4538    ) -> Option<Task<Result<()>>> {
 4539        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4540        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4541    }
 4542
 4543    pub fn compose_completion(
 4544        &mut self,
 4545        action: &ComposeCompletion,
 4546        window: &mut Window,
 4547        cx: &mut Context<Self>,
 4548    ) -> Option<Task<Result<()>>> {
 4549        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4550        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4551    }
 4552
 4553    fn do_completion(
 4554        &mut self,
 4555        item_ix: Option<usize>,
 4556        intent: CompletionIntent,
 4557        window: &mut Window,
 4558        cx: &mut Context<Editor>,
 4559    ) -> Option<Task<Result<()>>> {
 4560        use language::ToOffset as _;
 4561
 4562        let completions_menu =
 4563            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4564                menu
 4565            } else {
 4566                return None;
 4567            };
 4568
 4569        let candidate_id = {
 4570            let entries = completions_menu.entries.borrow();
 4571            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4572            if self.show_edit_predictions_in_menu() {
 4573                self.discard_inline_completion(true, cx);
 4574            }
 4575            mat.candidate_id
 4576        };
 4577
 4578        let buffer_handle = completions_menu.buffer;
 4579        let completion = completions_menu
 4580            .completions
 4581            .borrow()
 4582            .get(candidate_id)?
 4583            .clone();
 4584        cx.stop_propagation();
 4585
 4586        let snippet;
 4587        let new_text;
 4588        if completion.is_snippet() {
 4589            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4590            new_text = snippet.as_ref().unwrap().text.clone();
 4591        } else {
 4592            snippet = None;
 4593            new_text = completion.new_text.clone();
 4594        };
 4595        let selections = self.selections.all::<usize>(cx);
 4596        let buffer = buffer_handle.read(cx);
 4597        let old_range = completion.old_range.to_offset(buffer);
 4598        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4599
 4600        let newest_selection = self.selections.newest_anchor();
 4601        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4602            return None;
 4603        }
 4604
 4605        let lookbehind = newest_selection
 4606            .start
 4607            .text_anchor
 4608            .to_offset(buffer)
 4609            .saturating_sub(old_range.start);
 4610        let lookahead = old_range
 4611            .end
 4612            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4613        let mut common_prefix_len = 0;
 4614        for (a, b) in old_text.chars().zip(new_text.chars()) {
 4615            if a == b {
 4616                common_prefix_len += a.len_utf8();
 4617            } else {
 4618                break;
 4619            }
 4620        }
 4621
 4622        let snapshot = self.buffer.read(cx).snapshot(cx);
 4623        let mut range_to_replace: Option<Range<usize>> = None;
 4624        let mut ranges = Vec::new();
 4625        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4626        for selection in &selections {
 4627            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4628                let start = selection.start.saturating_sub(lookbehind);
 4629                let end = selection.end + lookahead;
 4630                if selection.id == newest_selection.id {
 4631                    range_to_replace = Some(start + common_prefix_len..end);
 4632                }
 4633                ranges.push(start + common_prefix_len..end);
 4634            } else {
 4635                common_prefix_len = 0;
 4636                ranges.clear();
 4637                ranges.extend(selections.iter().map(|s| {
 4638                    if s.id == newest_selection.id {
 4639                        range_to_replace = Some(old_range.clone());
 4640                        old_range.clone()
 4641                    } else {
 4642                        s.start..s.end
 4643                    }
 4644                }));
 4645                break;
 4646            }
 4647            if !self.linked_edit_ranges.is_empty() {
 4648                let start_anchor = snapshot.anchor_before(selection.head());
 4649                let end_anchor = snapshot.anchor_after(selection.tail());
 4650                if let Some(ranges) = self
 4651                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4652                {
 4653                    for (buffer, edits) in ranges {
 4654                        linked_edits.entry(buffer.clone()).or_default().extend(
 4655                            edits
 4656                                .into_iter()
 4657                                .map(|range| (range, new_text[common_prefix_len..].to_owned())),
 4658                        );
 4659                    }
 4660                }
 4661            }
 4662        }
 4663        let text = &new_text[common_prefix_len..];
 4664
 4665        let utf16_range_to_replace = range_to_replace.map(|range| {
 4666            let newest_selection = self.selections.newest::<OffsetUtf16>(cx).range();
 4667            let selection_start_utf16 = newest_selection.start.0 as isize;
 4668
 4669            range.start.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
 4670                ..range.end.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
 4671        });
 4672        cx.emit(EditorEvent::InputHandled {
 4673            utf16_range_to_replace,
 4674            text: text.into(),
 4675        });
 4676
 4677        self.transact(window, cx, |this, window, cx| {
 4678            if let Some(mut snippet) = snippet {
 4679                snippet.text = text.to_string();
 4680                for tabstop in snippet
 4681                    .tabstops
 4682                    .iter_mut()
 4683                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4684                {
 4685                    tabstop.start -= common_prefix_len as isize;
 4686                    tabstop.end -= common_prefix_len as isize;
 4687                }
 4688
 4689                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4690            } else {
 4691                this.buffer.update(cx, |buffer, cx| {
 4692                    let edits = ranges.iter().map(|range| (range.clone(), text));
 4693                    let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
 4694                    {
 4695                        None
 4696                    } else {
 4697                        this.autoindent_mode.clone()
 4698                    };
 4699                    buffer.edit(edits, auto_indent, cx);
 4700                });
 4701            }
 4702            for (buffer, edits) in linked_edits {
 4703                buffer.update(cx, |buffer, cx| {
 4704                    let snapshot = buffer.snapshot();
 4705                    let edits = edits
 4706                        .into_iter()
 4707                        .map(|(range, text)| {
 4708                            use text::ToPoint as TP;
 4709                            let end_point = TP::to_point(&range.end, &snapshot);
 4710                            let start_point = TP::to_point(&range.start, &snapshot);
 4711                            (start_point..end_point, text)
 4712                        })
 4713                        .sorted_by_key(|(range, _)| range.start);
 4714                    buffer.edit(edits, None, cx);
 4715                })
 4716            }
 4717
 4718            this.refresh_inline_completion(true, false, window, cx);
 4719        });
 4720
 4721        let show_new_completions_on_confirm = completion
 4722            .confirm
 4723            .as_ref()
 4724            .map_or(false, |confirm| confirm(intent, window, cx));
 4725        if show_new_completions_on_confirm {
 4726            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4727        }
 4728
 4729        let provider = self.completion_provider.as_ref()?;
 4730        drop(completion);
 4731        let apply_edits = provider.apply_additional_edits_for_completion(
 4732            buffer_handle,
 4733            completions_menu.completions.clone(),
 4734            candidate_id,
 4735            true,
 4736            cx,
 4737        );
 4738
 4739        let editor_settings = EditorSettings::get_global(cx);
 4740        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4741            // After the code completion is finished, users often want to know what signatures are needed.
 4742            // so we should automatically call signature_help
 4743            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4744        }
 4745
 4746        Some(cx.foreground_executor().spawn(async move {
 4747            apply_edits.await?;
 4748            Ok(())
 4749        }))
 4750    }
 4751
 4752    pub fn toggle_code_actions(
 4753        &mut self,
 4754        action: &ToggleCodeActions,
 4755        window: &mut Window,
 4756        cx: &mut Context<Self>,
 4757    ) {
 4758        let mut context_menu = self.context_menu.borrow_mut();
 4759        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4760            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4761                // Toggle if we're selecting the same one
 4762                *context_menu = None;
 4763                cx.notify();
 4764                return;
 4765            } else {
 4766                // Otherwise, clear it and start a new one
 4767                *context_menu = None;
 4768                cx.notify();
 4769            }
 4770        }
 4771        drop(context_menu);
 4772        let snapshot = self.snapshot(window, cx);
 4773        let deployed_from_indicator = action.deployed_from_indicator;
 4774        let mut task = self.code_actions_task.take();
 4775        let action = action.clone();
 4776        cx.spawn_in(window, async move |editor, cx| {
 4777            while let Some(prev_task) = task {
 4778                prev_task.await.log_err();
 4779                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4780            }
 4781
 4782            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4783                if editor.focus_handle.is_focused(window) {
 4784                    let multibuffer_point = action
 4785                        .deployed_from_indicator
 4786                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4787                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4788                    let (buffer, buffer_row) = snapshot
 4789                        .buffer_snapshot
 4790                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4791                        .and_then(|(buffer_snapshot, range)| {
 4792                            editor
 4793                                .buffer
 4794                                .read(cx)
 4795                                .buffer(buffer_snapshot.remote_id())
 4796                                .map(|buffer| (buffer, range.start.row))
 4797                        })?;
 4798                    let (_, code_actions) = editor
 4799                        .available_code_actions
 4800                        .clone()
 4801                        .and_then(|(location, code_actions)| {
 4802                            let snapshot = location.buffer.read(cx).snapshot();
 4803                            let point_range = location.range.to_point(&snapshot);
 4804                            let point_range = point_range.start.row..=point_range.end.row;
 4805                            if point_range.contains(&buffer_row) {
 4806                                Some((location, code_actions))
 4807                            } else {
 4808                                None
 4809                            }
 4810                        })
 4811                        .unzip();
 4812                    let buffer_id = buffer.read(cx).remote_id();
 4813                    let tasks = editor
 4814                        .tasks
 4815                        .get(&(buffer_id, buffer_row))
 4816                        .map(|t| Arc::new(t.to_owned()));
 4817                    if tasks.is_none() && code_actions.is_none() {
 4818                        return None;
 4819                    }
 4820
 4821                    editor.completion_tasks.clear();
 4822                    editor.discard_inline_completion(false, cx);
 4823                    let task_context =
 4824                        tasks
 4825                            .as_ref()
 4826                            .zip(editor.project.clone())
 4827                            .map(|(tasks, project)| {
 4828                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4829                            });
 4830
 4831                    let debugger_flag = cx.has_flag::<Debugger>();
 4832
 4833                    Some(cx.spawn_in(window, async move |editor, cx| {
 4834                        let task_context = match task_context {
 4835                            Some(task_context) => task_context.await,
 4836                            None => None,
 4837                        };
 4838                        let resolved_tasks =
 4839                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4840                                Rc::new(ResolvedTasks {
 4841                                    templates: tasks.resolve(&task_context).collect(),
 4842                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4843                                        multibuffer_point.row,
 4844                                        tasks.column,
 4845                                    )),
 4846                                })
 4847                            });
 4848                        let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
 4849                            tasks
 4850                                .templates
 4851                                .iter()
 4852                                .filter(|task| {
 4853                                    if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 4854                                        debugger_flag
 4855                                    } else {
 4856                                        true
 4857                                    }
 4858                                })
 4859                                .count()
 4860                                == 1
 4861                        }) && code_actions
 4862                            .as_ref()
 4863                            .map_or(true, |actions| actions.is_empty());
 4864                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 4865                            *editor.context_menu.borrow_mut() =
 4866                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4867                                    buffer,
 4868                                    actions: CodeActionContents {
 4869                                        tasks: resolved_tasks,
 4870                                        actions: code_actions,
 4871                                    },
 4872                                    selected_item: Default::default(),
 4873                                    scroll_handle: UniformListScrollHandle::default(),
 4874                                    deployed_from_indicator,
 4875                                }));
 4876                            if spawn_straight_away {
 4877                                if let Some(task) = editor.confirm_code_action(
 4878                                    &ConfirmCodeAction { item_ix: Some(0) },
 4879                                    window,
 4880                                    cx,
 4881                                ) {
 4882                                    cx.notify();
 4883                                    return task;
 4884                                }
 4885                            }
 4886                            cx.notify();
 4887                            Task::ready(Ok(()))
 4888                        }) {
 4889                            task.await
 4890                        } else {
 4891                            Ok(())
 4892                        }
 4893                    }))
 4894                } else {
 4895                    Some(Task::ready(Ok(())))
 4896                }
 4897            })?;
 4898            if let Some(task) = spawned_test_task {
 4899                task.await?;
 4900            }
 4901
 4902            Ok::<_, anyhow::Error>(())
 4903        })
 4904        .detach_and_log_err(cx);
 4905    }
 4906
 4907    pub fn confirm_code_action(
 4908        &mut self,
 4909        action: &ConfirmCodeAction,
 4910        window: &mut Window,
 4911        cx: &mut Context<Self>,
 4912    ) -> Option<Task<Result<()>>> {
 4913        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4914
 4915        let actions_menu =
 4916            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4917                menu
 4918            } else {
 4919                return None;
 4920            };
 4921
 4922        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4923        let action = actions_menu.actions.get(action_ix)?;
 4924        let title = action.label();
 4925        let buffer = actions_menu.buffer;
 4926        let workspace = self.workspace()?;
 4927
 4928        match action {
 4929            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4930                match resolved_task.task_type() {
 4931                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 4932                        workspace::tasks::schedule_resolved_task(
 4933                            workspace,
 4934                            task_source_kind,
 4935                            resolved_task,
 4936                            false,
 4937                            cx,
 4938                        );
 4939
 4940                        Some(Task::ready(Ok(())))
 4941                    }),
 4942                    task::TaskType::Debug(debug_args) => {
 4943                        if debug_args.locator.is_some() {
 4944                            workspace.update(cx, |workspace, cx| {
 4945                                workspace::tasks::schedule_resolved_task(
 4946                                    workspace,
 4947                                    task_source_kind,
 4948                                    resolved_task,
 4949                                    false,
 4950                                    cx,
 4951                                );
 4952                            });
 4953
 4954                            return Some(Task::ready(Ok(())));
 4955                        }
 4956
 4957                        if let Some(project) = self.project.as_ref() {
 4958                            project
 4959                                .update(cx, |project, cx| {
 4960                                    project.start_debug_session(
 4961                                        resolved_task.resolved_debug_adapter_config().unwrap(),
 4962                                        cx,
 4963                                    )
 4964                                })
 4965                                .detach_and_log_err(cx);
 4966                            Some(Task::ready(Ok(())))
 4967                        } else {
 4968                            Some(Task::ready(Ok(())))
 4969                        }
 4970                    }
 4971                }
 4972            }
 4973            CodeActionsItem::CodeAction {
 4974                excerpt_id,
 4975                action,
 4976                provider,
 4977            } => {
 4978                let apply_code_action =
 4979                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4980                let workspace = workspace.downgrade();
 4981                Some(cx.spawn_in(window, async move |editor, cx| {
 4982                    let project_transaction = apply_code_action.await?;
 4983                    Self::open_project_transaction(
 4984                        &editor,
 4985                        workspace,
 4986                        project_transaction,
 4987                        title,
 4988                        cx,
 4989                    )
 4990                    .await
 4991                }))
 4992            }
 4993        }
 4994    }
 4995
 4996    pub async fn open_project_transaction(
 4997        this: &WeakEntity<Editor>,
 4998        workspace: WeakEntity<Workspace>,
 4999        transaction: ProjectTransaction,
 5000        title: String,
 5001        cx: &mut AsyncWindowContext,
 5002    ) -> Result<()> {
 5003        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5004        cx.update(|_, cx| {
 5005            entries.sort_unstable_by_key(|(buffer, _)| {
 5006                buffer.read(cx).file().map(|f| f.path().clone())
 5007            });
 5008        })?;
 5009
 5010        // If the project transaction's edits are all contained within this editor, then
 5011        // avoid opening a new editor to display them.
 5012
 5013        if let Some((buffer, transaction)) = entries.first() {
 5014            if entries.len() == 1 {
 5015                let excerpt = this.update(cx, |editor, cx| {
 5016                    editor
 5017                        .buffer()
 5018                        .read(cx)
 5019                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5020                })?;
 5021                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5022                    if excerpted_buffer == *buffer {
 5023                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5024                            let excerpt_range = excerpt_range.to_offset(buffer);
 5025                            buffer
 5026                                .edited_ranges_for_transaction::<usize>(transaction)
 5027                                .all(|range| {
 5028                                    excerpt_range.start <= range.start
 5029                                        && excerpt_range.end >= range.end
 5030                                })
 5031                        })?;
 5032
 5033                        if all_edits_within_excerpt {
 5034                            return Ok(());
 5035                        }
 5036                    }
 5037                }
 5038            }
 5039        } else {
 5040            return Ok(());
 5041        }
 5042
 5043        let mut ranges_to_highlight = Vec::new();
 5044        let excerpt_buffer = cx.new(|cx| {
 5045            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5046            for (buffer_handle, transaction) in &entries {
 5047                let edited_ranges = buffer_handle
 5048                    .read(cx)
 5049                    .edited_ranges_for_transaction::<Point>(transaction)
 5050                    .collect::<Vec<_>>();
 5051                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5052                    PathKey::for_buffer(buffer_handle, cx),
 5053                    buffer_handle.clone(),
 5054                    edited_ranges,
 5055                    DEFAULT_MULTIBUFFER_CONTEXT,
 5056                    cx,
 5057                );
 5058
 5059                ranges_to_highlight.extend(ranges);
 5060            }
 5061            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5062            multibuffer
 5063        })?;
 5064
 5065        workspace.update_in(cx, |workspace, window, cx| {
 5066            let project = workspace.project().clone();
 5067            let editor =
 5068                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5069            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5070            editor.update(cx, |editor, cx| {
 5071                editor.highlight_background::<Self>(
 5072                    &ranges_to_highlight,
 5073                    |theme| theme.editor_highlighted_line_background,
 5074                    cx,
 5075                );
 5076            });
 5077        })?;
 5078
 5079        Ok(())
 5080    }
 5081
 5082    pub fn clear_code_action_providers(&mut self) {
 5083        self.code_action_providers.clear();
 5084        self.available_code_actions.take();
 5085    }
 5086
 5087    pub fn add_code_action_provider(
 5088        &mut self,
 5089        provider: Rc<dyn CodeActionProvider>,
 5090        window: &mut Window,
 5091        cx: &mut Context<Self>,
 5092    ) {
 5093        if self
 5094            .code_action_providers
 5095            .iter()
 5096            .any(|existing_provider| existing_provider.id() == provider.id())
 5097        {
 5098            return;
 5099        }
 5100
 5101        self.code_action_providers.push(provider);
 5102        self.refresh_code_actions(window, cx);
 5103    }
 5104
 5105    pub fn remove_code_action_provider(
 5106        &mut self,
 5107        id: Arc<str>,
 5108        window: &mut Window,
 5109        cx: &mut Context<Self>,
 5110    ) {
 5111        self.code_action_providers
 5112            .retain(|provider| provider.id() != id);
 5113        self.refresh_code_actions(window, cx);
 5114    }
 5115
 5116    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5117        let buffer = self.buffer.read(cx);
 5118        let newest_selection = self.selections.newest_anchor().clone();
 5119        if newest_selection.head().diff_base_anchor.is_some() {
 5120            return None;
 5121        }
 5122        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5123        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5124        if start_buffer != end_buffer {
 5125            return None;
 5126        }
 5127
 5128        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5129            cx.background_executor()
 5130                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5131                .await;
 5132
 5133            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5134                let providers = this.code_action_providers.clone();
 5135                let tasks = this
 5136                    .code_action_providers
 5137                    .iter()
 5138                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5139                    .collect::<Vec<_>>();
 5140                (providers, tasks)
 5141            })?;
 5142
 5143            let mut actions = Vec::new();
 5144            for (provider, provider_actions) in
 5145                providers.into_iter().zip(future::join_all(tasks).await)
 5146            {
 5147                if let Some(provider_actions) = provider_actions.log_err() {
 5148                    actions.extend(provider_actions.into_iter().map(|action| {
 5149                        AvailableCodeAction {
 5150                            excerpt_id: newest_selection.start.excerpt_id,
 5151                            action,
 5152                            provider: provider.clone(),
 5153                        }
 5154                    }));
 5155                }
 5156            }
 5157
 5158            this.update(cx, |this, cx| {
 5159                this.available_code_actions = if actions.is_empty() {
 5160                    None
 5161                } else {
 5162                    Some((
 5163                        Location {
 5164                            buffer: start_buffer,
 5165                            range: start..end,
 5166                        },
 5167                        actions.into(),
 5168                    ))
 5169                };
 5170                cx.notify();
 5171            })
 5172        }));
 5173        None
 5174    }
 5175
 5176    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5177        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5178            self.show_git_blame_inline = false;
 5179
 5180            self.show_git_blame_inline_delay_task =
 5181                Some(cx.spawn_in(window, async move |this, cx| {
 5182                    cx.background_executor().timer(delay).await;
 5183
 5184                    this.update(cx, |this, cx| {
 5185                        this.show_git_blame_inline = true;
 5186                        cx.notify();
 5187                    })
 5188                    .log_err();
 5189                }));
 5190        }
 5191    }
 5192
 5193    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5194        if self.pending_rename.is_some() {
 5195            return None;
 5196        }
 5197
 5198        let provider = self.semantics_provider.clone()?;
 5199        let buffer = self.buffer.read(cx);
 5200        let newest_selection = self.selections.newest_anchor().clone();
 5201        let cursor_position = newest_selection.head();
 5202        let (cursor_buffer, cursor_buffer_position) =
 5203            buffer.text_anchor_for_position(cursor_position, cx)?;
 5204        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5205        if cursor_buffer != tail_buffer {
 5206            return None;
 5207        }
 5208        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5209        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5210            cx.background_executor()
 5211                .timer(Duration::from_millis(debounce))
 5212                .await;
 5213
 5214            let highlights = if let Some(highlights) = cx
 5215                .update(|cx| {
 5216                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5217                })
 5218                .ok()
 5219                .flatten()
 5220            {
 5221                highlights.await.log_err()
 5222            } else {
 5223                None
 5224            };
 5225
 5226            if let Some(highlights) = highlights {
 5227                this.update(cx, |this, cx| {
 5228                    if this.pending_rename.is_some() {
 5229                        return;
 5230                    }
 5231
 5232                    let buffer_id = cursor_position.buffer_id;
 5233                    let buffer = this.buffer.read(cx);
 5234                    if !buffer
 5235                        .text_anchor_for_position(cursor_position, cx)
 5236                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5237                    {
 5238                        return;
 5239                    }
 5240
 5241                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5242                    let mut write_ranges = Vec::new();
 5243                    let mut read_ranges = Vec::new();
 5244                    for highlight in highlights {
 5245                        for (excerpt_id, excerpt_range) in
 5246                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5247                        {
 5248                            let start = highlight
 5249                                .range
 5250                                .start
 5251                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5252                            let end = highlight
 5253                                .range
 5254                                .end
 5255                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5256                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5257                                continue;
 5258                            }
 5259
 5260                            let range = Anchor {
 5261                                buffer_id,
 5262                                excerpt_id,
 5263                                text_anchor: start,
 5264                                diff_base_anchor: None,
 5265                            }..Anchor {
 5266                                buffer_id,
 5267                                excerpt_id,
 5268                                text_anchor: end,
 5269                                diff_base_anchor: None,
 5270                            };
 5271                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5272                                write_ranges.push(range);
 5273                            } else {
 5274                                read_ranges.push(range);
 5275                            }
 5276                        }
 5277                    }
 5278
 5279                    this.highlight_background::<DocumentHighlightRead>(
 5280                        &read_ranges,
 5281                        |theme| theme.editor_document_highlight_read_background,
 5282                        cx,
 5283                    );
 5284                    this.highlight_background::<DocumentHighlightWrite>(
 5285                        &write_ranges,
 5286                        |theme| theme.editor_document_highlight_write_background,
 5287                        cx,
 5288                    );
 5289                    cx.notify();
 5290                })
 5291                .log_err();
 5292            }
 5293        }));
 5294        None
 5295    }
 5296
 5297    pub fn refresh_selected_text_highlights(
 5298        &mut self,
 5299        window: &mut Window,
 5300        cx: &mut Context<Editor>,
 5301    ) {
 5302        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5303            return;
 5304        }
 5305        self.selection_highlight_task.take();
 5306        if !EditorSettings::get_global(cx).selection_highlight {
 5307            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5308            return;
 5309        }
 5310        if self.selections.count() != 1 || self.selections.line_mode {
 5311            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5312            return;
 5313        }
 5314        let selection = self.selections.newest::<Point>(cx);
 5315        if selection.is_empty() || selection.start.row != selection.end.row {
 5316            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5317            return;
 5318        }
 5319        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5320        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5321            cx.background_executor()
 5322                .timer(Duration::from_millis(debounce))
 5323                .await;
 5324            let Some(Some(matches_task)) = editor
 5325                .update_in(cx, |editor, _, cx| {
 5326                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5327                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5328                        return None;
 5329                    }
 5330                    let selection = editor.selections.newest::<Point>(cx);
 5331                    if selection.is_empty() || selection.start.row != selection.end.row {
 5332                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5333                        return None;
 5334                    }
 5335                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5336                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5337                    if query.trim().is_empty() {
 5338                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5339                        return None;
 5340                    }
 5341                    Some(cx.background_spawn(async move {
 5342                        let mut ranges = Vec::new();
 5343                        let selection_anchors = selection.range().to_anchors(&buffer);
 5344                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5345                            for (search_buffer, search_range, excerpt_id) in
 5346                                buffer.range_to_buffer_ranges(range)
 5347                            {
 5348                                ranges.extend(
 5349                                    project::search::SearchQuery::text(
 5350                                        query.clone(),
 5351                                        false,
 5352                                        false,
 5353                                        false,
 5354                                        Default::default(),
 5355                                        Default::default(),
 5356                                        None,
 5357                                    )
 5358                                    .unwrap()
 5359                                    .search(search_buffer, Some(search_range.clone()))
 5360                                    .await
 5361                                    .into_iter()
 5362                                    .filter_map(
 5363                                        |match_range| {
 5364                                            let start = search_buffer.anchor_after(
 5365                                                search_range.start + match_range.start,
 5366                                            );
 5367                                            let end = search_buffer.anchor_before(
 5368                                                search_range.start + match_range.end,
 5369                                            );
 5370                                            let range = Anchor::range_in_buffer(
 5371                                                excerpt_id,
 5372                                                search_buffer.remote_id(),
 5373                                                start..end,
 5374                                            );
 5375                                            (range != selection_anchors).then_some(range)
 5376                                        },
 5377                                    ),
 5378                                );
 5379                            }
 5380                        }
 5381                        ranges
 5382                    }))
 5383                })
 5384                .log_err()
 5385            else {
 5386                return;
 5387            };
 5388            let matches = matches_task.await;
 5389            editor
 5390                .update_in(cx, |editor, _, cx| {
 5391                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5392                    if !matches.is_empty() {
 5393                        editor.highlight_background::<SelectedTextHighlight>(
 5394                            &matches,
 5395                            |theme| theme.editor_document_highlight_bracket_background,
 5396                            cx,
 5397                        )
 5398                    }
 5399                })
 5400                .log_err();
 5401        }));
 5402    }
 5403
 5404    pub fn refresh_inline_completion(
 5405        &mut self,
 5406        debounce: bool,
 5407        user_requested: bool,
 5408        window: &mut Window,
 5409        cx: &mut Context<Self>,
 5410    ) -> Option<()> {
 5411        let provider = self.edit_prediction_provider()?;
 5412        let cursor = self.selections.newest_anchor().head();
 5413        let (buffer, cursor_buffer_position) =
 5414            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5415
 5416        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5417            self.discard_inline_completion(false, cx);
 5418            return None;
 5419        }
 5420
 5421        if !user_requested
 5422            && (!self.should_show_edit_predictions()
 5423                || !self.is_focused(window)
 5424                || buffer.read(cx).is_empty())
 5425        {
 5426            self.discard_inline_completion(false, cx);
 5427            return None;
 5428        }
 5429
 5430        self.update_visible_inline_completion(window, cx);
 5431        provider.refresh(
 5432            self.project.clone(),
 5433            buffer,
 5434            cursor_buffer_position,
 5435            debounce,
 5436            cx,
 5437        );
 5438        Some(())
 5439    }
 5440
 5441    fn show_edit_predictions_in_menu(&self) -> bool {
 5442        match self.edit_prediction_settings {
 5443            EditPredictionSettings::Disabled => false,
 5444            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5445        }
 5446    }
 5447
 5448    pub fn edit_predictions_enabled(&self) -> bool {
 5449        match self.edit_prediction_settings {
 5450            EditPredictionSettings::Disabled => false,
 5451            EditPredictionSettings::Enabled { .. } => true,
 5452        }
 5453    }
 5454
 5455    fn edit_prediction_requires_modifier(&self) -> bool {
 5456        match self.edit_prediction_settings {
 5457            EditPredictionSettings::Disabled => false,
 5458            EditPredictionSettings::Enabled {
 5459                preview_requires_modifier,
 5460                ..
 5461            } => preview_requires_modifier,
 5462        }
 5463    }
 5464
 5465    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5466        if self.edit_prediction_provider.is_none() {
 5467            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5468        } else {
 5469            let selection = self.selections.newest_anchor();
 5470            let cursor = selection.head();
 5471
 5472            if let Some((buffer, cursor_buffer_position)) =
 5473                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5474            {
 5475                self.edit_prediction_settings =
 5476                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5477            }
 5478        }
 5479    }
 5480
 5481    fn edit_prediction_settings_at_position(
 5482        &self,
 5483        buffer: &Entity<Buffer>,
 5484        buffer_position: language::Anchor,
 5485        cx: &App,
 5486    ) -> EditPredictionSettings {
 5487        if self.mode != EditorMode::Full
 5488            || !self.show_inline_completions_override.unwrap_or(true)
 5489            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5490        {
 5491            return EditPredictionSettings::Disabled;
 5492        }
 5493
 5494        let buffer = buffer.read(cx);
 5495
 5496        let file = buffer.file();
 5497
 5498        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5499            return EditPredictionSettings::Disabled;
 5500        };
 5501
 5502        let by_provider = matches!(
 5503            self.menu_inline_completions_policy,
 5504            MenuInlineCompletionsPolicy::ByProvider
 5505        );
 5506
 5507        let show_in_menu = by_provider
 5508            && self
 5509                .edit_prediction_provider
 5510                .as_ref()
 5511                .map_or(false, |provider| {
 5512                    provider.provider.show_completions_in_menu()
 5513                });
 5514
 5515        let preview_requires_modifier =
 5516            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5517
 5518        EditPredictionSettings::Enabled {
 5519            show_in_menu,
 5520            preview_requires_modifier,
 5521        }
 5522    }
 5523
 5524    fn should_show_edit_predictions(&self) -> bool {
 5525        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5526    }
 5527
 5528    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5529        matches!(
 5530            self.edit_prediction_preview,
 5531            EditPredictionPreview::Active { .. }
 5532        )
 5533    }
 5534
 5535    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5536        let cursor = self.selections.newest_anchor().head();
 5537        if let Some((buffer, cursor_position)) =
 5538            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5539        {
 5540            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5541        } else {
 5542            false
 5543        }
 5544    }
 5545
 5546    fn edit_predictions_enabled_in_buffer(
 5547        &self,
 5548        buffer: &Entity<Buffer>,
 5549        buffer_position: language::Anchor,
 5550        cx: &App,
 5551    ) -> bool {
 5552        maybe!({
 5553            if self.read_only(cx) {
 5554                return Some(false);
 5555            }
 5556            let provider = self.edit_prediction_provider()?;
 5557            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5558                return Some(false);
 5559            }
 5560            let buffer = buffer.read(cx);
 5561            let Some(file) = buffer.file() else {
 5562                return Some(true);
 5563            };
 5564            let settings = all_language_settings(Some(file), cx);
 5565            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5566        })
 5567        .unwrap_or(false)
 5568    }
 5569
 5570    fn cycle_inline_completion(
 5571        &mut self,
 5572        direction: Direction,
 5573        window: &mut Window,
 5574        cx: &mut Context<Self>,
 5575    ) -> Option<()> {
 5576        let provider = self.edit_prediction_provider()?;
 5577        let cursor = self.selections.newest_anchor().head();
 5578        let (buffer, cursor_buffer_position) =
 5579            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5580        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5581            return None;
 5582        }
 5583
 5584        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5585        self.update_visible_inline_completion(window, cx);
 5586
 5587        Some(())
 5588    }
 5589
 5590    pub fn show_inline_completion(
 5591        &mut self,
 5592        _: &ShowEditPrediction,
 5593        window: &mut Window,
 5594        cx: &mut Context<Self>,
 5595    ) {
 5596        if !self.has_active_inline_completion() {
 5597            self.refresh_inline_completion(false, true, window, cx);
 5598            return;
 5599        }
 5600
 5601        self.update_visible_inline_completion(window, cx);
 5602    }
 5603
 5604    pub fn display_cursor_names(
 5605        &mut self,
 5606        _: &DisplayCursorNames,
 5607        window: &mut Window,
 5608        cx: &mut Context<Self>,
 5609    ) {
 5610        self.show_cursor_names(window, cx);
 5611    }
 5612
 5613    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5614        self.show_cursor_names = true;
 5615        cx.notify();
 5616        cx.spawn_in(window, async move |this, cx| {
 5617            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5618            this.update(cx, |this, cx| {
 5619                this.show_cursor_names = false;
 5620                cx.notify()
 5621            })
 5622            .ok()
 5623        })
 5624        .detach();
 5625    }
 5626
 5627    pub fn next_edit_prediction(
 5628        &mut self,
 5629        _: &NextEditPrediction,
 5630        window: &mut Window,
 5631        cx: &mut Context<Self>,
 5632    ) {
 5633        if self.has_active_inline_completion() {
 5634            self.cycle_inline_completion(Direction::Next, window, cx);
 5635        } else {
 5636            let is_copilot_disabled = self
 5637                .refresh_inline_completion(false, true, window, cx)
 5638                .is_none();
 5639            if is_copilot_disabled {
 5640                cx.propagate();
 5641            }
 5642        }
 5643    }
 5644
 5645    pub fn previous_edit_prediction(
 5646        &mut self,
 5647        _: &PreviousEditPrediction,
 5648        window: &mut Window,
 5649        cx: &mut Context<Self>,
 5650    ) {
 5651        if self.has_active_inline_completion() {
 5652            self.cycle_inline_completion(Direction::Prev, window, cx);
 5653        } else {
 5654            let is_copilot_disabled = self
 5655                .refresh_inline_completion(false, true, window, cx)
 5656                .is_none();
 5657            if is_copilot_disabled {
 5658                cx.propagate();
 5659            }
 5660        }
 5661    }
 5662
 5663    pub fn accept_edit_prediction(
 5664        &mut self,
 5665        _: &AcceptEditPrediction,
 5666        window: &mut Window,
 5667        cx: &mut Context<Self>,
 5668    ) {
 5669        if self.show_edit_predictions_in_menu() {
 5670            self.hide_context_menu(window, cx);
 5671        }
 5672
 5673        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5674            return;
 5675        };
 5676
 5677        self.report_inline_completion_event(
 5678            active_inline_completion.completion_id.clone(),
 5679            true,
 5680            cx,
 5681        );
 5682
 5683        match &active_inline_completion.completion {
 5684            InlineCompletion::Move { target, .. } => {
 5685                let target = *target;
 5686
 5687                if let Some(position_map) = &self.last_position_map {
 5688                    if position_map
 5689                        .visible_row_range
 5690                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5691                        || !self.edit_prediction_requires_modifier()
 5692                    {
 5693                        self.unfold_ranges(&[target..target], true, false, cx);
 5694                        // Note that this is also done in vim's handler of the Tab action.
 5695                        self.change_selections(
 5696                            Some(Autoscroll::newest()),
 5697                            window,
 5698                            cx,
 5699                            |selections| {
 5700                                selections.select_anchor_ranges([target..target]);
 5701                            },
 5702                        );
 5703                        self.clear_row_highlights::<EditPredictionPreview>();
 5704
 5705                        self.edit_prediction_preview
 5706                            .set_previous_scroll_position(None);
 5707                    } else {
 5708                        self.edit_prediction_preview
 5709                            .set_previous_scroll_position(Some(
 5710                                position_map.snapshot.scroll_anchor,
 5711                            ));
 5712
 5713                        self.highlight_rows::<EditPredictionPreview>(
 5714                            target..target,
 5715                            cx.theme().colors().editor_highlighted_line_background,
 5716                            true,
 5717                            cx,
 5718                        );
 5719                        self.request_autoscroll(Autoscroll::fit(), cx);
 5720                    }
 5721                }
 5722            }
 5723            InlineCompletion::Edit { edits, .. } => {
 5724                if let Some(provider) = self.edit_prediction_provider() {
 5725                    provider.accept(cx);
 5726                }
 5727
 5728                let snapshot = self.buffer.read(cx).snapshot(cx);
 5729                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5730
 5731                self.buffer.update(cx, |buffer, cx| {
 5732                    buffer.edit(edits.iter().cloned(), None, cx)
 5733                });
 5734
 5735                self.change_selections(None, window, cx, |s| {
 5736                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5737                });
 5738
 5739                self.update_visible_inline_completion(window, cx);
 5740                if self.active_inline_completion.is_none() {
 5741                    self.refresh_inline_completion(true, true, window, cx);
 5742                }
 5743
 5744                cx.notify();
 5745            }
 5746        }
 5747
 5748        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5749    }
 5750
 5751    pub fn accept_partial_inline_completion(
 5752        &mut self,
 5753        _: &AcceptPartialEditPrediction,
 5754        window: &mut Window,
 5755        cx: &mut Context<Self>,
 5756    ) {
 5757        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5758            return;
 5759        };
 5760        if self.selections.count() != 1 {
 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                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5774                    selections.select_anchor_ranges([target..target]);
 5775                });
 5776            }
 5777            InlineCompletion::Edit { edits, .. } => {
 5778                // Find an insertion that starts at the cursor position.
 5779                let snapshot = self.buffer.read(cx).snapshot(cx);
 5780                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5781                let insertion = edits.iter().find_map(|(range, text)| {
 5782                    let range = range.to_offset(&snapshot);
 5783                    if range.is_empty() && range.start == cursor_offset {
 5784                        Some(text)
 5785                    } else {
 5786                        None
 5787                    }
 5788                });
 5789
 5790                if let Some(text) = insertion {
 5791                    let mut partial_completion = text
 5792                        .chars()
 5793                        .by_ref()
 5794                        .take_while(|c| c.is_alphabetic())
 5795                        .collect::<String>();
 5796                    if partial_completion.is_empty() {
 5797                        partial_completion = text
 5798                            .chars()
 5799                            .by_ref()
 5800                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5801                            .collect::<String>();
 5802                    }
 5803
 5804                    cx.emit(EditorEvent::InputHandled {
 5805                        utf16_range_to_replace: None,
 5806                        text: partial_completion.clone().into(),
 5807                    });
 5808
 5809                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5810
 5811                    self.refresh_inline_completion(true, true, window, cx);
 5812                    cx.notify();
 5813                } else {
 5814                    self.accept_edit_prediction(&Default::default(), window, cx);
 5815                }
 5816            }
 5817        }
 5818    }
 5819
 5820    fn discard_inline_completion(
 5821        &mut self,
 5822        should_report_inline_completion_event: bool,
 5823        cx: &mut Context<Self>,
 5824    ) -> bool {
 5825        if should_report_inline_completion_event {
 5826            let completion_id = self
 5827                .active_inline_completion
 5828                .as_ref()
 5829                .and_then(|active_completion| active_completion.completion_id.clone());
 5830
 5831            self.report_inline_completion_event(completion_id, false, cx);
 5832        }
 5833
 5834        if let Some(provider) = self.edit_prediction_provider() {
 5835            provider.discard(cx);
 5836        }
 5837
 5838        self.take_active_inline_completion(cx)
 5839    }
 5840
 5841    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5842        let Some(provider) = self.edit_prediction_provider() else {
 5843            return;
 5844        };
 5845
 5846        let Some((_, buffer, _)) = self
 5847            .buffer
 5848            .read(cx)
 5849            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5850        else {
 5851            return;
 5852        };
 5853
 5854        let extension = buffer
 5855            .read(cx)
 5856            .file()
 5857            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5858
 5859        let event_type = match accepted {
 5860            true => "Edit Prediction Accepted",
 5861            false => "Edit Prediction Discarded",
 5862        };
 5863        telemetry::event!(
 5864            event_type,
 5865            provider = provider.name(),
 5866            prediction_id = id,
 5867            suggestion_accepted = accepted,
 5868            file_extension = extension,
 5869        );
 5870    }
 5871
 5872    pub fn has_active_inline_completion(&self) -> bool {
 5873        self.active_inline_completion.is_some()
 5874    }
 5875
 5876    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5877        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5878            return false;
 5879        };
 5880
 5881        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5882        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5883        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5884        true
 5885    }
 5886
 5887    /// Returns true when we're displaying the edit prediction popover below the cursor
 5888    /// like we are not previewing and the LSP autocomplete menu is visible
 5889    /// or we are in `when_holding_modifier` mode.
 5890    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5891        if self.edit_prediction_preview_is_active()
 5892            || !self.show_edit_predictions_in_menu()
 5893            || !self.edit_predictions_enabled()
 5894        {
 5895            return false;
 5896        }
 5897
 5898        if self.has_visible_completions_menu() {
 5899            return true;
 5900        }
 5901
 5902        has_completion && self.edit_prediction_requires_modifier()
 5903    }
 5904
 5905    fn handle_modifiers_changed(
 5906        &mut self,
 5907        modifiers: Modifiers,
 5908        position_map: &PositionMap,
 5909        window: &mut Window,
 5910        cx: &mut Context<Self>,
 5911    ) {
 5912        if self.show_edit_predictions_in_menu() {
 5913            self.update_edit_prediction_preview(&modifiers, window, cx);
 5914        }
 5915
 5916        self.update_selection_mode(&modifiers, position_map, window, cx);
 5917
 5918        let mouse_position = window.mouse_position();
 5919        if !position_map.text_hitbox.is_hovered(window) {
 5920            return;
 5921        }
 5922
 5923        self.update_hovered_link(
 5924            position_map.point_for_position(mouse_position),
 5925            &position_map.snapshot,
 5926            modifiers,
 5927            window,
 5928            cx,
 5929        )
 5930    }
 5931
 5932    fn update_selection_mode(
 5933        &mut self,
 5934        modifiers: &Modifiers,
 5935        position_map: &PositionMap,
 5936        window: &mut Window,
 5937        cx: &mut Context<Self>,
 5938    ) {
 5939        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5940            return;
 5941        }
 5942
 5943        let mouse_position = window.mouse_position();
 5944        let point_for_position = position_map.point_for_position(mouse_position);
 5945        let position = point_for_position.previous_valid;
 5946
 5947        self.select(
 5948            SelectPhase::BeginColumnar {
 5949                position,
 5950                reset: false,
 5951                goal_column: point_for_position.exact_unclipped.column(),
 5952            },
 5953            window,
 5954            cx,
 5955        );
 5956    }
 5957
 5958    fn update_edit_prediction_preview(
 5959        &mut self,
 5960        modifiers: &Modifiers,
 5961        window: &mut Window,
 5962        cx: &mut Context<Self>,
 5963    ) {
 5964        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5965        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5966            return;
 5967        };
 5968
 5969        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5970            if matches!(
 5971                self.edit_prediction_preview,
 5972                EditPredictionPreview::Inactive { .. }
 5973            ) {
 5974                self.edit_prediction_preview = EditPredictionPreview::Active {
 5975                    previous_scroll_position: None,
 5976                    since: Instant::now(),
 5977                };
 5978
 5979                self.update_visible_inline_completion(window, cx);
 5980                cx.notify();
 5981            }
 5982        } else if let EditPredictionPreview::Active {
 5983            previous_scroll_position,
 5984            since,
 5985        } = self.edit_prediction_preview
 5986        {
 5987            if let (Some(previous_scroll_position), Some(position_map)) =
 5988                (previous_scroll_position, self.last_position_map.as_ref())
 5989            {
 5990                self.set_scroll_position(
 5991                    previous_scroll_position
 5992                        .scroll_position(&position_map.snapshot.display_snapshot),
 5993                    window,
 5994                    cx,
 5995                );
 5996            }
 5997
 5998            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5999                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6000            };
 6001            self.clear_row_highlights::<EditPredictionPreview>();
 6002            self.update_visible_inline_completion(window, cx);
 6003            cx.notify();
 6004        }
 6005    }
 6006
 6007    fn update_visible_inline_completion(
 6008        &mut self,
 6009        _window: &mut Window,
 6010        cx: &mut Context<Self>,
 6011    ) -> Option<()> {
 6012        let selection = self.selections.newest_anchor();
 6013        let cursor = selection.head();
 6014        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6015        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6016        let excerpt_id = cursor.excerpt_id;
 6017
 6018        let show_in_menu = self.show_edit_predictions_in_menu();
 6019        let completions_menu_has_precedence = !show_in_menu
 6020            && (self.context_menu.borrow().is_some()
 6021                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6022
 6023        if completions_menu_has_precedence
 6024            || !offset_selection.is_empty()
 6025            || self
 6026                .active_inline_completion
 6027                .as_ref()
 6028                .map_or(false, |completion| {
 6029                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6030                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6031                    !invalidation_range.contains(&offset_selection.head())
 6032                })
 6033        {
 6034            self.discard_inline_completion(false, cx);
 6035            return None;
 6036        }
 6037
 6038        self.take_active_inline_completion(cx);
 6039        let Some(provider) = self.edit_prediction_provider() else {
 6040            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6041            return None;
 6042        };
 6043
 6044        let (buffer, cursor_buffer_position) =
 6045            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6046
 6047        self.edit_prediction_settings =
 6048            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6049
 6050        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6051
 6052        if self.edit_prediction_indent_conflict {
 6053            let cursor_point = cursor.to_point(&multibuffer);
 6054
 6055            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6056
 6057            if let Some((_, indent)) = indents.iter().next() {
 6058                if indent.len == cursor_point.column {
 6059                    self.edit_prediction_indent_conflict = false;
 6060                }
 6061            }
 6062        }
 6063
 6064        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6065        let edits = inline_completion
 6066            .edits
 6067            .into_iter()
 6068            .flat_map(|(range, new_text)| {
 6069                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6070                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6071                Some((start..end, new_text))
 6072            })
 6073            .collect::<Vec<_>>();
 6074        if edits.is_empty() {
 6075            return None;
 6076        }
 6077
 6078        let first_edit_start = edits.first().unwrap().0.start;
 6079        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6080        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6081
 6082        let last_edit_end = edits.last().unwrap().0.end;
 6083        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6084        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6085
 6086        let cursor_row = cursor.to_point(&multibuffer).row;
 6087
 6088        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6089
 6090        let mut inlay_ids = Vec::new();
 6091        let invalidation_row_range;
 6092        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6093            Some(cursor_row..edit_end_row)
 6094        } else if cursor_row > edit_end_row {
 6095            Some(edit_start_row..cursor_row)
 6096        } else {
 6097            None
 6098        };
 6099        let is_move =
 6100            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6101        let completion = if is_move {
 6102            invalidation_row_range =
 6103                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6104            let target = first_edit_start;
 6105            InlineCompletion::Move { target, snapshot }
 6106        } else {
 6107            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6108                && !self.inline_completions_hidden_for_vim_mode;
 6109
 6110            if show_completions_in_buffer {
 6111                if edits
 6112                    .iter()
 6113                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6114                {
 6115                    let mut inlays = Vec::new();
 6116                    for (range, new_text) in &edits {
 6117                        let inlay = Inlay::inline_completion(
 6118                            post_inc(&mut self.next_inlay_id),
 6119                            range.start,
 6120                            new_text.as_str(),
 6121                        );
 6122                        inlay_ids.push(inlay.id);
 6123                        inlays.push(inlay);
 6124                    }
 6125
 6126                    self.splice_inlays(&[], inlays, cx);
 6127                } else {
 6128                    let background_color = cx.theme().status().deleted_background;
 6129                    self.highlight_text::<InlineCompletionHighlight>(
 6130                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6131                        HighlightStyle {
 6132                            background_color: Some(background_color),
 6133                            ..Default::default()
 6134                        },
 6135                        cx,
 6136                    );
 6137                }
 6138            }
 6139
 6140            invalidation_row_range = edit_start_row..edit_end_row;
 6141
 6142            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6143                if provider.show_tab_accept_marker() {
 6144                    EditDisplayMode::TabAccept
 6145                } else {
 6146                    EditDisplayMode::Inline
 6147                }
 6148            } else {
 6149                EditDisplayMode::DiffPopover
 6150            };
 6151
 6152            InlineCompletion::Edit {
 6153                edits,
 6154                edit_preview: inline_completion.edit_preview,
 6155                display_mode,
 6156                snapshot,
 6157            }
 6158        };
 6159
 6160        let invalidation_range = multibuffer
 6161            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6162            ..multibuffer.anchor_after(Point::new(
 6163                invalidation_row_range.end,
 6164                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6165            ));
 6166
 6167        self.stale_inline_completion_in_menu = None;
 6168        self.active_inline_completion = Some(InlineCompletionState {
 6169            inlay_ids,
 6170            completion,
 6171            completion_id: inline_completion.id,
 6172            invalidation_range,
 6173        });
 6174
 6175        cx.notify();
 6176
 6177        Some(())
 6178    }
 6179
 6180    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6181        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6182    }
 6183
 6184    fn render_code_actions_indicator(
 6185        &self,
 6186        _style: &EditorStyle,
 6187        row: DisplayRow,
 6188        is_active: bool,
 6189        breakpoint: Option<&(Anchor, Breakpoint)>,
 6190        cx: &mut Context<Self>,
 6191    ) -> Option<IconButton> {
 6192        let color = Color::Muted;
 6193        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6194        let show_tooltip = !self.context_menu_visible();
 6195
 6196        if self.available_code_actions.is_some() {
 6197            Some(
 6198                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6199                    .shape(ui::IconButtonShape::Square)
 6200                    .icon_size(IconSize::XSmall)
 6201                    .icon_color(color)
 6202                    .toggle_state(is_active)
 6203                    .when(show_tooltip, |this| {
 6204                        this.tooltip({
 6205                            let focus_handle = self.focus_handle.clone();
 6206                            move |window, cx| {
 6207                                Tooltip::for_action_in(
 6208                                    "Toggle Code Actions",
 6209                                    &ToggleCodeActions {
 6210                                        deployed_from_indicator: None,
 6211                                    },
 6212                                    &focus_handle,
 6213                                    window,
 6214                                    cx,
 6215                                )
 6216                            }
 6217                        })
 6218                    })
 6219                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6220                        window.focus(&editor.focus_handle(cx));
 6221                        editor.toggle_code_actions(
 6222                            &ToggleCodeActions {
 6223                                deployed_from_indicator: Some(row),
 6224                            },
 6225                            window,
 6226                            cx,
 6227                        );
 6228                    }))
 6229                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6230                        editor.set_breakpoint_context_menu(
 6231                            row,
 6232                            position,
 6233                            event.down.position,
 6234                            window,
 6235                            cx,
 6236                        );
 6237                    })),
 6238            )
 6239        } else {
 6240            None
 6241        }
 6242    }
 6243
 6244    fn clear_tasks(&mut self) {
 6245        self.tasks.clear()
 6246    }
 6247
 6248    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6249        if self.tasks.insert(key, value).is_some() {
 6250            // This case should hopefully be rare, but just in case...
 6251            log::error!(
 6252                "multiple different run targets found on a single line, only the last target will be rendered"
 6253            )
 6254        }
 6255    }
 6256
 6257    /// Get all display points of breakpoints that will be rendered within editor
 6258    ///
 6259    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6260    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6261    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6262    fn active_breakpoints(
 6263        &self,
 6264        range: Range<DisplayRow>,
 6265        window: &mut Window,
 6266        cx: &mut Context<Self>,
 6267    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6268        let mut breakpoint_display_points = HashMap::default();
 6269
 6270        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6271            return breakpoint_display_points;
 6272        };
 6273
 6274        let snapshot = self.snapshot(window, cx);
 6275
 6276        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6277        let Some(project) = self.project.as_ref() else {
 6278            return breakpoint_display_points;
 6279        };
 6280
 6281        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6282            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6283
 6284        for (buffer_snapshot, range, excerpt_id) in
 6285            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6286        {
 6287            let Some(buffer) = project.read_with(cx, |this, cx| {
 6288                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6289            }) else {
 6290                continue;
 6291            };
 6292            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6293                &buffer,
 6294                Some(
 6295                    buffer_snapshot.anchor_before(range.start)
 6296                        ..buffer_snapshot.anchor_after(range.end),
 6297                ),
 6298                buffer_snapshot,
 6299                cx,
 6300            );
 6301            for (anchor, breakpoint) in breakpoints {
 6302                let multi_buffer_anchor =
 6303                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6304                let position = multi_buffer_anchor
 6305                    .to_point(&multi_buffer_snapshot)
 6306                    .to_display_point(&snapshot);
 6307
 6308                breakpoint_display_points
 6309                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6310            }
 6311        }
 6312
 6313        breakpoint_display_points
 6314    }
 6315
 6316    fn breakpoint_context_menu(
 6317        &self,
 6318        anchor: Anchor,
 6319        window: &mut Window,
 6320        cx: &mut Context<Self>,
 6321    ) -> Entity<ui::ContextMenu> {
 6322        let weak_editor = cx.weak_entity();
 6323        let focus_handle = self.focus_handle(cx);
 6324
 6325        let row = self
 6326            .buffer
 6327            .read(cx)
 6328            .snapshot(cx)
 6329            .summary_for_anchor::<Point>(&anchor)
 6330            .row;
 6331
 6332        let breakpoint = self
 6333            .breakpoint_at_row(row, window, cx)
 6334            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6335
 6336        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6337            "Edit Log Breakpoint"
 6338        } else {
 6339            "Set Log Breakpoint"
 6340        };
 6341
 6342        let condition_breakpoint_msg = if breakpoint
 6343            .as_ref()
 6344            .is_some_and(|bp| bp.1.condition.is_some())
 6345        {
 6346            "Edit Condition Breakpoint"
 6347        } else {
 6348            "Set Condition Breakpoint"
 6349        };
 6350
 6351        let hit_condition_breakpoint_msg = if breakpoint
 6352            .as_ref()
 6353            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6354        {
 6355            "Edit Hit Condition Breakpoint"
 6356        } else {
 6357            "Set Hit Condition Breakpoint"
 6358        };
 6359
 6360        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6361            "Unset Breakpoint"
 6362        } else {
 6363            "Set Breakpoint"
 6364        };
 6365
 6366        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6367            BreakpointState::Enabled => Some("Disable"),
 6368            BreakpointState::Disabled => Some("Enable"),
 6369        });
 6370
 6371        let (anchor, breakpoint) =
 6372            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6373
 6374        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6375            menu.on_blur_subscription(Subscription::new(|| {}))
 6376                .context(focus_handle)
 6377                .when_some(toggle_state_msg, |this, msg| {
 6378                    this.entry(msg, None, {
 6379                        let weak_editor = weak_editor.clone();
 6380                        let breakpoint = breakpoint.clone();
 6381                        move |_window, cx| {
 6382                            weak_editor
 6383                                .update(cx, |this, cx| {
 6384                                    this.edit_breakpoint_at_anchor(
 6385                                        anchor,
 6386                                        breakpoint.as_ref().clone(),
 6387                                        BreakpointEditAction::InvertState,
 6388                                        cx,
 6389                                    );
 6390                                })
 6391                                .log_err();
 6392                        }
 6393                    })
 6394                })
 6395                .entry(set_breakpoint_msg, None, {
 6396                    let weak_editor = weak_editor.clone();
 6397                    let breakpoint = breakpoint.clone();
 6398                    move |_window, cx| {
 6399                        weak_editor
 6400                            .update(cx, |this, cx| {
 6401                                this.edit_breakpoint_at_anchor(
 6402                                    anchor,
 6403                                    breakpoint.as_ref().clone(),
 6404                                    BreakpointEditAction::Toggle,
 6405                                    cx,
 6406                                );
 6407                            })
 6408                            .log_err();
 6409                    }
 6410                })
 6411                .entry(log_breakpoint_msg, None, {
 6412                    let breakpoint = breakpoint.clone();
 6413                    let weak_editor = weak_editor.clone();
 6414                    move |window, cx| {
 6415                        weak_editor
 6416                            .update(cx, |this, cx| {
 6417                                this.add_edit_breakpoint_block(
 6418                                    anchor,
 6419                                    breakpoint.as_ref(),
 6420                                    BreakpointPromptEditAction::Log,
 6421                                    window,
 6422                                    cx,
 6423                                );
 6424                            })
 6425                            .log_err();
 6426                    }
 6427                })
 6428                .entry(condition_breakpoint_msg, None, {
 6429                    let breakpoint = breakpoint.clone();
 6430                    let weak_editor = weak_editor.clone();
 6431                    move |window, cx| {
 6432                        weak_editor
 6433                            .update(cx, |this, cx| {
 6434                                this.add_edit_breakpoint_block(
 6435                                    anchor,
 6436                                    breakpoint.as_ref(),
 6437                                    BreakpointPromptEditAction::Condition,
 6438                                    window,
 6439                                    cx,
 6440                                );
 6441                            })
 6442                            .log_err();
 6443                    }
 6444                })
 6445                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6446                    weak_editor
 6447                        .update(cx, |this, cx| {
 6448                            this.add_edit_breakpoint_block(
 6449                                anchor,
 6450                                breakpoint.as_ref(),
 6451                                BreakpointPromptEditAction::HitCondition,
 6452                                window,
 6453                                cx,
 6454                            );
 6455                        })
 6456                        .log_err();
 6457                })
 6458        })
 6459    }
 6460
 6461    fn render_breakpoint(
 6462        &self,
 6463        position: Anchor,
 6464        row: DisplayRow,
 6465        breakpoint: &Breakpoint,
 6466        cx: &mut Context<Self>,
 6467    ) -> IconButton {
 6468        let (color, icon) = {
 6469            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6470                (false, false) => ui::IconName::DebugBreakpoint,
 6471                (true, false) => ui::IconName::DebugLogBreakpoint,
 6472                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6473                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6474            };
 6475
 6476            let color = if self
 6477                .gutter_breakpoint_indicator
 6478                .0
 6479                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6480            {
 6481                Color::Hint
 6482            } else {
 6483                Color::Debugger
 6484            };
 6485
 6486            (color, icon)
 6487        };
 6488
 6489        let breakpoint = Arc::from(breakpoint.clone());
 6490
 6491        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6492            .icon_size(IconSize::XSmall)
 6493            .size(ui::ButtonSize::None)
 6494            .icon_color(color)
 6495            .style(ButtonStyle::Transparent)
 6496            .on_click(cx.listener({
 6497                let breakpoint = breakpoint.clone();
 6498
 6499                move |editor, event: &ClickEvent, window, cx| {
 6500                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6501                        BreakpointEditAction::InvertState
 6502                    } else {
 6503                        BreakpointEditAction::Toggle
 6504                    };
 6505
 6506                    window.focus(&editor.focus_handle(cx));
 6507                    editor.edit_breakpoint_at_anchor(
 6508                        position,
 6509                        breakpoint.as_ref().clone(),
 6510                        edit_action,
 6511                        cx,
 6512                    );
 6513                }
 6514            }))
 6515            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6516                editor.set_breakpoint_context_menu(
 6517                    row,
 6518                    Some(position),
 6519                    event.down.position,
 6520                    window,
 6521                    cx,
 6522                );
 6523            }))
 6524    }
 6525
 6526    fn build_tasks_context(
 6527        project: &Entity<Project>,
 6528        buffer: &Entity<Buffer>,
 6529        buffer_row: u32,
 6530        tasks: &Arc<RunnableTasks>,
 6531        cx: &mut Context<Self>,
 6532    ) -> Task<Option<task::TaskContext>> {
 6533        let position = Point::new(buffer_row, tasks.column);
 6534        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6535        let location = Location {
 6536            buffer: buffer.clone(),
 6537            range: range_start..range_start,
 6538        };
 6539        // Fill in the environmental variables from the tree-sitter captures
 6540        let mut captured_task_variables = TaskVariables::default();
 6541        for (capture_name, value) in tasks.extra_variables.clone() {
 6542            captured_task_variables.insert(
 6543                task::VariableName::Custom(capture_name.into()),
 6544                value.clone(),
 6545            );
 6546        }
 6547        project.update(cx, |project, cx| {
 6548            project.task_store().update(cx, |task_store, cx| {
 6549                task_store.task_context_for_location(captured_task_variables, location, cx)
 6550            })
 6551        })
 6552    }
 6553
 6554    pub fn spawn_nearest_task(
 6555        &mut self,
 6556        action: &SpawnNearestTask,
 6557        window: &mut Window,
 6558        cx: &mut Context<Self>,
 6559    ) {
 6560        let Some((workspace, _)) = self.workspace.clone() else {
 6561            return;
 6562        };
 6563        let Some(project) = self.project.clone() else {
 6564            return;
 6565        };
 6566
 6567        // Try to find a closest, enclosing node using tree-sitter that has a
 6568        // task
 6569        let Some((buffer, buffer_row, tasks)) = self
 6570            .find_enclosing_node_task(cx)
 6571            // Or find the task that's closest in row-distance.
 6572            .or_else(|| self.find_closest_task(cx))
 6573        else {
 6574            return;
 6575        };
 6576
 6577        let reveal_strategy = action.reveal;
 6578        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6579        cx.spawn_in(window, async move |_, cx| {
 6580            let context = task_context.await?;
 6581            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6582
 6583            let resolved = resolved_task.resolved.as_mut()?;
 6584            resolved.reveal = reveal_strategy;
 6585
 6586            workspace
 6587                .update(cx, |workspace, cx| {
 6588                    workspace::tasks::schedule_resolved_task(
 6589                        workspace,
 6590                        task_source_kind,
 6591                        resolved_task,
 6592                        false,
 6593                        cx,
 6594                    );
 6595                })
 6596                .ok()
 6597        })
 6598        .detach();
 6599    }
 6600
 6601    fn find_closest_task(
 6602        &mut self,
 6603        cx: &mut Context<Self>,
 6604    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6605        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6606
 6607        let ((buffer_id, row), tasks) = self
 6608            .tasks
 6609            .iter()
 6610            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6611
 6612        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6613        let tasks = Arc::new(tasks.to_owned());
 6614        Some((buffer, *row, tasks))
 6615    }
 6616
 6617    fn find_enclosing_node_task(
 6618        &mut self,
 6619        cx: &mut Context<Self>,
 6620    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6621        let snapshot = self.buffer.read(cx).snapshot(cx);
 6622        let offset = self.selections.newest::<usize>(cx).head();
 6623        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6624        let buffer_id = excerpt.buffer().remote_id();
 6625
 6626        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6627        let mut cursor = layer.node().walk();
 6628
 6629        while cursor.goto_first_child_for_byte(offset).is_some() {
 6630            if cursor.node().end_byte() == offset {
 6631                cursor.goto_next_sibling();
 6632            }
 6633        }
 6634
 6635        // Ascend to the smallest ancestor that contains the range and has a task.
 6636        loop {
 6637            let node = cursor.node();
 6638            let node_range = node.byte_range();
 6639            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6640
 6641            // Check if this node contains our offset
 6642            if node_range.start <= offset && node_range.end >= offset {
 6643                // If it contains offset, check for task
 6644                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6645                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6646                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6647                }
 6648            }
 6649
 6650            if !cursor.goto_parent() {
 6651                break;
 6652            }
 6653        }
 6654        None
 6655    }
 6656
 6657    fn render_run_indicator(
 6658        &self,
 6659        _style: &EditorStyle,
 6660        is_active: bool,
 6661        row: DisplayRow,
 6662        breakpoint: Option<(Anchor, Breakpoint)>,
 6663        cx: &mut Context<Self>,
 6664    ) -> IconButton {
 6665        let color = Color::Muted;
 6666        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6667
 6668        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6669            .shape(ui::IconButtonShape::Square)
 6670            .icon_size(IconSize::XSmall)
 6671            .icon_color(color)
 6672            .toggle_state(is_active)
 6673            .on_click(cx.listener(move |editor, _e, window, cx| {
 6674                window.focus(&editor.focus_handle(cx));
 6675                editor.toggle_code_actions(
 6676                    &ToggleCodeActions {
 6677                        deployed_from_indicator: Some(row),
 6678                    },
 6679                    window,
 6680                    cx,
 6681                );
 6682            }))
 6683            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6684                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6685            }))
 6686    }
 6687
 6688    pub fn context_menu_visible(&self) -> bool {
 6689        !self.edit_prediction_preview_is_active()
 6690            && self
 6691                .context_menu
 6692                .borrow()
 6693                .as_ref()
 6694                .map_or(false, |menu| menu.visible())
 6695    }
 6696
 6697    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6698        self.context_menu
 6699            .borrow()
 6700            .as_ref()
 6701            .map(|menu| menu.origin())
 6702    }
 6703
 6704    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6705        self.context_menu_options = Some(options);
 6706    }
 6707
 6708    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6709    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6710
 6711    fn render_edit_prediction_popover(
 6712        &mut self,
 6713        text_bounds: &Bounds<Pixels>,
 6714        content_origin: gpui::Point<Pixels>,
 6715        editor_snapshot: &EditorSnapshot,
 6716        visible_row_range: Range<DisplayRow>,
 6717        scroll_top: f32,
 6718        scroll_bottom: f32,
 6719        line_layouts: &[LineWithInvisibles],
 6720        line_height: Pixels,
 6721        scroll_pixel_position: gpui::Point<Pixels>,
 6722        newest_selection_head: Option<DisplayPoint>,
 6723        editor_width: Pixels,
 6724        style: &EditorStyle,
 6725        window: &mut Window,
 6726        cx: &mut App,
 6727    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6728        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6729
 6730        if self.edit_prediction_visible_in_cursor_popover(true) {
 6731            return None;
 6732        }
 6733
 6734        match &active_inline_completion.completion {
 6735            InlineCompletion::Move { target, .. } => {
 6736                let target_display_point = target.to_display_point(editor_snapshot);
 6737
 6738                if self.edit_prediction_requires_modifier() {
 6739                    if !self.edit_prediction_preview_is_active() {
 6740                        return None;
 6741                    }
 6742
 6743                    self.render_edit_prediction_modifier_jump_popover(
 6744                        text_bounds,
 6745                        content_origin,
 6746                        visible_row_range,
 6747                        line_layouts,
 6748                        line_height,
 6749                        scroll_pixel_position,
 6750                        newest_selection_head,
 6751                        target_display_point,
 6752                        window,
 6753                        cx,
 6754                    )
 6755                } else {
 6756                    self.render_edit_prediction_eager_jump_popover(
 6757                        text_bounds,
 6758                        content_origin,
 6759                        editor_snapshot,
 6760                        visible_row_range,
 6761                        scroll_top,
 6762                        scroll_bottom,
 6763                        line_height,
 6764                        scroll_pixel_position,
 6765                        target_display_point,
 6766                        editor_width,
 6767                        window,
 6768                        cx,
 6769                    )
 6770                }
 6771            }
 6772            InlineCompletion::Edit {
 6773                display_mode: EditDisplayMode::Inline,
 6774                ..
 6775            } => None,
 6776            InlineCompletion::Edit {
 6777                display_mode: EditDisplayMode::TabAccept,
 6778                edits,
 6779                ..
 6780            } => {
 6781                let range = &edits.first()?.0;
 6782                let target_display_point = range.end.to_display_point(editor_snapshot);
 6783
 6784                self.render_edit_prediction_end_of_line_popover(
 6785                    "Accept",
 6786                    editor_snapshot,
 6787                    visible_row_range,
 6788                    target_display_point,
 6789                    line_height,
 6790                    scroll_pixel_position,
 6791                    content_origin,
 6792                    editor_width,
 6793                    window,
 6794                    cx,
 6795                )
 6796            }
 6797            InlineCompletion::Edit {
 6798                edits,
 6799                edit_preview,
 6800                display_mode: EditDisplayMode::DiffPopover,
 6801                snapshot,
 6802            } => self.render_edit_prediction_diff_popover(
 6803                text_bounds,
 6804                content_origin,
 6805                editor_snapshot,
 6806                visible_row_range,
 6807                line_layouts,
 6808                line_height,
 6809                scroll_pixel_position,
 6810                newest_selection_head,
 6811                editor_width,
 6812                style,
 6813                edits,
 6814                edit_preview,
 6815                snapshot,
 6816                window,
 6817                cx,
 6818            ),
 6819        }
 6820    }
 6821
 6822    fn render_edit_prediction_modifier_jump_popover(
 6823        &mut self,
 6824        text_bounds: &Bounds<Pixels>,
 6825        content_origin: gpui::Point<Pixels>,
 6826        visible_row_range: Range<DisplayRow>,
 6827        line_layouts: &[LineWithInvisibles],
 6828        line_height: Pixels,
 6829        scroll_pixel_position: gpui::Point<Pixels>,
 6830        newest_selection_head: Option<DisplayPoint>,
 6831        target_display_point: DisplayPoint,
 6832        window: &mut Window,
 6833        cx: &mut App,
 6834    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6835        let scrolled_content_origin =
 6836            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6837
 6838        const SCROLL_PADDING_Y: Pixels = px(12.);
 6839
 6840        if target_display_point.row() < visible_row_range.start {
 6841            return self.render_edit_prediction_scroll_popover(
 6842                |_| SCROLL_PADDING_Y,
 6843                IconName::ArrowUp,
 6844                visible_row_range,
 6845                line_layouts,
 6846                newest_selection_head,
 6847                scrolled_content_origin,
 6848                window,
 6849                cx,
 6850            );
 6851        } else if target_display_point.row() >= visible_row_range.end {
 6852            return self.render_edit_prediction_scroll_popover(
 6853                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6854                IconName::ArrowDown,
 6855                visible_row_range,
 6856                line_layouts,
 6857                newest_selection_head,
 6858                scrolled_content_origin,
 6859                window,
 6860                cx,
 6861            );
 6862        }
 6863
 6864        const POLE_WIDTH: Pixels = px(2.);
 6865
 6866        let line_layout =
 6867            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6868        let target_column = target_display_point.column() as usize;
 6869
 6870        let target_x = line_layout.x_for_index(target_column);
 6871        let target_y =
 6872            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6873
 6874        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6875
 6876        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6877        border_color.l += 0.001;
 6878
 6879        let mut element = v_flex()
 6880            .items_end()
 6881            .when(flag_on_right, |el| el.items_start())
 6882            .child(if flag_on_right {
 6883                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6884                    .rounded_bl(px(0.))
 6885                    .rounded_tl(px(0.))
 6886                    .border_l_2()
 6887                    .border_color(border_color)
 6888            } else {
 6889                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6890                    .rounded_br(px(0.))
 6891                    .rounded_tr(px(0.))
 6892                    .border_r_2()
 6893                    .border_color(border_color)
 6894            })
 6895            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6896            .into_any();
 6897
 6898        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6899
 6900        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6901            - point(
 6902                if flag_on_right {
 6903                    POLE_WIDTH
 6904                } else {
 6905                    size.width - POLE_WIDTH
 6906                },
 6907                size.height - line_height,
 6908            );
 6909
 6910        origin.x = origin.x.max(content_origin.x);
 6911
 6912        element.prepaint_at(origin, window, cx);
 6913
 6914        Some((element, origin))
 6915    }
 6916
 6917    fn render_edit_prediction_scroll_popover(
 6918        &mut self,
 6919        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6920        scroll_icon: IconName,
 6921        visible_row_range: Range<DisplayRow>,
 6922        line_layouts: &[LineWithInvisibles],
 6923        newest_selection_head: Option<DisplayPoint>,
 6924        scrolled_content_origin: gpui::Point<Pixels>,
 6925        window: &mut Window,
 6926        cx: &mut App,
 6927    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6928        let mut element = self
 6929            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6930            .into_any();
 6931
 6932        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6933
 6934        let cursor = newest_selection_head?;
 6935        let cursor_row_layout =
 6936            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6937        let cursor_column = cursor.column() as usize;
 6938
 6939        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6940
 6941        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6942
 6943        element.prepaint_at(origin, window, cx);
 6944        Some((element, origin))
 6945    }
 6946
 6947    fn render_edit_prediction_eager_jump_popover(
 6948        &mut self,
 6949        text_bounds: &Bounds<Pixels>,
 6950        content_origin: gpui::Point<Pixels>,
 6951        editor_snapshot: &EditorSnapshot,
 6952        visible_row_range: Range<DisplayRow>,
 6953        scroll_top: f32,
 6954        scroll_bottom: f32,
 6955        line_height: Pixels,
 6956        scroll_pixel_position: gpui::Point<Pixels>,
 6957        target_display_point: DisplayPoint,
 6958        editor_width: Pixels,
 6959        window: &mut Window,
 6960        cx: &mut App,
 6961    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6962        if target_display_point.row().as_f32() < scroll_top {
 6963            let mut element = self
 6964                .render_edit_prediction_line_popover(
 6965                    "Jump to Edit",
 6966                    Some(IconName::ArrowUp),
 6967                    window,
 6968                    cx,
 6969                )?
 6970                .into_any();
 6971
 6972            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6973            let offset = point(
 6974                (text_bounds.size.width - size.width) / 2.,
 6975                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6976            );
 6977
 6978            let origin = text_bounds.origin + offset;
 6979            element.prepaint_at(origin, window, cx);
 6980            Some((element, origin))
 6981        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6982            let mut element = self
 6983                .render_edit_prediction_line_popover(
 6984                    "Jump to Edit",
 6985                    Some(IconName::ArrowDown),
 6986                    window,
 6987                    cx,
 6988                )?
 6989                .into_any();
 6990
 6991            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6992            let offset = point(
 6993                (text_bounds.size.width - size.width) / 2.,
 6994                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6995            );
 6996
 6997            let origin = text_bounds.origin + offset;
 6998            element.prepaint_at(origin, window, cx);
 6999            Some((element, origin))
 7000        } else {
 7001            self.render_edit_prediction_end_of_line_popover(
 7002                "Jump to Edit",
 7003                editor_snapshot,
 7004                visible_row_range,
 7005                target_display_point,
 7006                line_height,
 7007                scroll_pixel_position,
 7008                content_origin,
 7009                editor_width,
 7010                window,
 7011                cx,
 7012            )
 7013        }
 7014    }
 7015
 7016    fn render_edit_prediction_end_of_line_popover(
 7017        self: &mut Editor,
 7018        label: &'static str,
 7019        editor_snapshot: &EditorSnapshot,
 7020        visible_row_range: Range<DisplayRow>,
 7021        target_display_point: DisplayPoint,
 7022        line_height: Pixels,
 7023        scroll_pixel_position: gpui::Point<Pixels>,
 7024        content_origin: gpui::Point<Pixels>,
 7025        editor_width: Pixels,
 7026        window: &mut Window,
 7027        cx: &mut App,
 7028    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7029        let target_line_end = DisplayPoint::new(
 7030            target_display_point.row(),
 7031            editor_snapshot.line_len(target_display_point.row()),
 7032        );
 7033
 7034        let mut element = self
 7035            .render_edit_prediction_line_popover(label, None, window, cx)?
 7036            .into_any();
 7037
 7038        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7039
 7040        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7041
 7042        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7043        let mut origin = start_point
 7044            + line_origin
 7045            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7046        origin.x = origin.x.max(content_origin.x);
 7047
 7048        let max_x = content_origin.x + editor_width - size.width;
 7049
 7050        if origin.x > max_x {
 7051            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7052
 7053            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7054                origin.y += offset;
 7055                IconName::ArrowUp
 7056            } else {
 7057                origin.y -= offset;
 7058                IconName::ArrowDown
 7059            };
 7060
 7061            element = self
 7062                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7063                .into_any();
 7064
 7065            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7066
 7067            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7068        }
 7069
 7070        element.prepaint_at(origin, window, cx);
 7071        Some((element, origin))
 7072    }
 7073
 7074    fn render_edit_prediction_diff_popover(
 7075        self: &Editor,
 7076        text_bounds: &Bounds<Pixels>,
 7077        content_origin: gpui::Point<Pixels>,
 7078        editor_snapshot: &EditorSnapshot,
 7079        visible_row_range: Range<DisplayRow>,
 7080        line_layouts: &[LineWithInvisibles],
 7081        line_height: Pixels,
 7082        scroll_pixel_position: gpui::Point<Pixels>,
 7083        newest_selection_head: Option<DisplayPoint>,
 7084        editor_width: Pixels,
 7085        style: &EditorStyle,
 7086        edits: &Vec<(Range<Anchor>, String)>,
 7087        edit_preview: &Option<language::EditPreview>,
 7088        snapshot: &language::BufferSnapshot,
 7089        window: &mut Window,
 7090        cx: &mut App,
 7091    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7092        let edit_start = edits
 7093            .first()
 7094            .unwrap()
 7095            .0
 7096            .start
 7097            .to_display_point(editor_snapshot);
 7098        let edit_end = edits
 7099            .last()
 7100            .unwrap()
 7101            .0
 7102            .end
 7103            .to_display_point(editor_snapshot);
 7104
 7105        let is_visible = visible_row_range.contains(&edit_start.row())
 7106            || visible_row_range.contains(&edit_end.row());
 7107        if !is_visible {
 7108            return None;
 7109        }
 7110
 7111        let highlighted_edits =
 7112            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7113
 7114        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7115        let line_count = highlighted_edits.text.lines().count();
 7116
 7117        const BORDER_WIDTH: Pixels = px(1.);
 7118
 7119        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7120        let has_keybind = keybind.is_some();
 7121
 7122        let mut element = h_flex()
 7123            .items_start()
 7124            .child(
 7125                h_flex()
 7126                    .bg(cx.theme().colors().editor_background)
 7127                    .border(BORDER_WIDTH)
 7128                    .shadow_sm()
 7129                    .border_color(cx.theme().colors().border)
 7130                    .rounded_l_lg()
 7131                    .when(line_count > 1, |el| el.rounded_br_lg())
 7132                    .pr_1()
 7133                    .child(styled_text),
 7134            )
 7135            .child(
 7136                h_flex()
 7137                    .h(line_height + BORDER_WIDTH * 2.)
 7138                    .px_1p5()
 7139                    .gap_1()
 7140                    // Workaround: For some reason, there's a gap if we don't do this
 7141                    .ml(-BORDER_WIDTH)
 7142                    .shadow(smallvec![gpui::BoxShadow {
 7143                        color: gpui::black().opacity(0.05),
 7144                        offset: point(px(1.), px(1.)),
 7145                        blur_radius: px(2.),
 7146                        spread_radius: px(0.),
 7147                    }])
 7148                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7149                    .border(BORDER_WIDTH)
 7150                    .border_color(cx.theme().colors().border)
 7151                    .rounded_r_lg()
 7152                    .id("edit_prediction_diff_popover_keybind")
 7153                    .when(!has_keybind, |el| {
 7154                        let status_colors = cx.theme().status();
 7155
 7156                        el.bg(status_colors.error_background)
 7157                            .border_color(status_colors.error.opacity(0.6))
 7158                            .child(Icon::new(IconName::Info).color(Color::Error))
 7159                            .cursor_default()
 7160                            .hoverable_tooltip(move |_window, cx| {
 7161                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7162                            })
 7163                    })
 7164                    .children(keybind),
 7165            )
 7166            .into_any();
 7167
 7168        let longest_row =
 7169            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7170        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7171            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7172        } else {
 7173            layout_line(
 7174                longest_row,
 7175                editor_snapshot,
 7176                style,
 7177                editor_width,
 7178                |_| false,
 7179                window,
 7180                cx,
 7181            )
 7182            .width
 7183        };
 7184
 7185        let viewport_bounds =
 7186            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7187                right: -EditorElement::SCROLLBAR_WIDTH,
 7188                ..Default::default()
 7189            });
 7190
 7191        let x_after_longest =
 7192            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7193                - scroll_pixel_position.x;
 7194
 7195        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7196
 7197        // Fully visible if it can be displayed within the window (allow overlapping other
 7198        // panes). However, this is only allowed if the popover starts within text_bounds.
 7199        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7200            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7201
 7202        let mut origin = if can_position_to_the_right {
 7203            point(
 7204                x_after_longest,
 7205                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7206                    - scroll_pixel_position.y,
 7207            )
 7208        } else {
 7209            let cursor_row = newest_selection_head.map(|head| head.row());
 7210            let above_edit = edit_start
 7211                .row()
 7212                .0
 7213                .checked_sub(line_count as u32)
 7214                .map(DisplayRow);
 7215            let below_edit = Some(edit_end.row() + 1);
 7216            let above_cursor =
 7217                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7218            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7219
 7220            // Place the edit popover adjacent to the edit if there is a location
 7221            // available that is onscreen and does not obscure the cursor. Otherwise,
 7222            // place it adjacent to the cursor.
 7223            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7224                .into_iter()
 7225                .flatten()
 7226                .find(|&start_row| {
 7227                    let end_row = start_row + line_count as u32;
 7228                    visible_row_range.contains(&start_row)
 7229                        && visible_row_range.contains(&end_row)
 7230                        && cursor_row.map_or(true, |cursor_row| {
 7231                            !((start_row..end_row).contains(&cursor_row))
 7232                        })
 7233                })?;
 7234
 7235            content_origin
 7236                + point(
 7237                    -scroll_pixel_position.x,
 7238                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7239                )
 7240        };
 7241
 7242        origin.x -= BORDER_WIDTH;
 7243
 7244        window.defer_draw(element, origin, 1);
 7245
 7246        // Do not return an element, since it will already be drawn due to defer_draw.
 7247        None
 7248    }
 7249
 7250    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7251        px(30.)
 7252    }
 7253
 7254    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7255        if self.read_only(cx) {
 7256            cx.theme().players().read_only()
 7257        } else {
 7258            self.style.as_ref().unwrap().local_player
 7259        }
 7260    }
 7261
 7262    fn render_edit_prediction_accept_keybind(
 7263        &self,
 7264        window: &mut Window,
 7265        cx: &App,
 7266    ) -> Option<AnyElement> {
 7267        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7268        let accept_keystroke = accept_binding.keystroke()?;
 7269
 7270        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7271
 7272        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7273            Color::Accent
 7274        } else {
 7275            Color::Muted
 7276        };
 7277
 7278        h_flex()
 7279            .px_0p5()
 7280            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7281            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7282            .text_size(TextSize::XSmall.rems(cx))
 7283            .child(h_flex().children(ui::render_modifiers(
 7284                &accept_keystroke.modifiers,
 7285                PlatformStyle::platform(),
 7286                Some(modifiers_color),
 7287                Some(IconSize::XSmall.rems().into()),
 7288                true,
 7289            )))
 7290            .when(is_platform_style_mac, |parent| {
 7291                parent.child(accept_keystroke.key.clone())
 7292            })
 7293            .when(!is_platform_style_mac, |parent| {
 7294                parent.child(
 7295                    Key::new(
 7296                        util::capitalize(&accept_keystroke.key),
 7297                        Some(Color::Default),
 7298                    )
 7299                    .size(Some(IconSize::XSmall.rems().into())),
 7300                )
 7301            })
 7302            .into_any()
 7303            .into()
 7304    }
 7305
 7306    fn render_edit_prediction_line_popover(
 7307        &self,
 7308        label: impl Into<SharedString>,
 7309        icon: Option<IconName>,
 7310        window: &mut Window,
 7311        cx: &App,
 7312    ) -> Option<Stateful<Div>> {
 7313        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7314
 7315        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7316        let has_keybind = keybind.is_some();
 7317
 7318        let result = h_flex()
 7319            .id("ep-line-popover")
 7320            .py_0p5()
 7321            .pl_1()
 7322            .pr(padding_right)
 7323            .gap_1()
 7324            .rounded_md()
 7325            .border_1()
 7326            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7327            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7328            .shadow_sm()
 7329            .when(!has_keybind, |el| {
 7330                let status_colors = cx.theme().status();
 7331
 7332                el.bg(status_colors.error_background)
 7333                    .border_color(status_colors.error.opacity(0.6))
 7334                    .pl_2()
 7335                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7336                    .cursor_default()
 7337                    .hoverable_tooltip(move |_window, cx| {
 7338                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7339                    })
 7340            })
 7341            .children(keybind)
 7342            .child(
 7343                Label::new(label)
 7344                    .size(LabelSize::Small)
 7345                    .when(!has_keybind, |el| {
 7346                        el.color(cx.theme().status().error.into()).strikethrough()
 7347                    }),
 7348            )
 7349            .when(!has_keybind, |el| {
 7350                el.child(
 7351                    h_flex().ml_1().child(
 7352                        Icon::new(IconName::Info)
 7353                            .size(IconSize::Small)
 7354                            .color(cx.theme().status().error.into()),
 7355                    ),
 7356                )
 7357            })
 7358            .when_some(icon, |element, icon| {
 7359                element.child(
 7360                    div()
 7361                        .mt(px(1.5))
 7362                        .child(Icon::new(icon).size(IconSize::Small)),
 7363                )
 7364            });
 7365
 7366        Some(result)
 7367    }
 7368
 7369    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7370        let accent_color = cx.theme().colors().text_accent;
 7371        let editor_bg_color = cx.theme().colors().editor_background;
 7372        editor_bg_color.blend(accent_color.opacity(0.1))
 7373    }
 7374
 7375    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7376        let accent_color = cx.theme().colors().text_accent;
 7377        let editor_bg_color = cx.theme().colors().editor_background;
 7378        editor_bg_color.blend(accent_color.opacity(0.6))
 7379    }
 7380
 7381    fn render_edit_prediction_cursor_popover(
 7382        &self,
 7383        min_width: Pixels,
 7384        max_width: Pixels,
 7385        cursor_point: Point,
 7386        style: &EditorStyle,
 7387        accept_keystroke: Option<&gpui::Keystroke>,
 7388        _window: &Window,
 7389        cx: &mut Context<Editor>,
 7390    ) -> Option<AnyElement> {
 7391        let provider = self.edit_prediction_provider.as_ref()?;
 7392
 7393        if provider.provider.needs_terms_acceptance(cx) {
 7394            return Some(
 7395                h_flex()
 7396                    .min_w(min_width)
 7397                    .flex_1()
 7398                    .px_2()
 7399                    .py_1()
 7400                    .gap_3()
 7401                    .elevation_2(cx)
 7402                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7403                    .id("accept-terms")
 7404                    .cursor_pointer()
 7405                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7406                    .on_click(cx.listener(|this, _event, window, cx| {
 7407                        cx.stop_propagation();
 7408                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7409                        window.dispatch_action(
 7410                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7411                            cx,
 7412                        );
 7413                    }))
 7414                    .child(
 7415                        h_flex()
 7416                            .flex_1()
 7417                            .gap_2()
 7418                            .child(Icon::new(IconName::ZedPredict))
 7419                            .child(Label::new("Accept Terms of Service"))
 7420                            .child(div().w_full())
 7421                            .child(
 7422                                Icon::new(IconName::ArrowUpRight)
 7423                                    .color(Color::Muted)
 7424                                    .size(IconSize::Small),
 7425                            )
 7426                            .into_any_element(),
 7427                    )
 7428                    .into_any(),
 7429            );
 7430        }
 7431
 7432        let is_refreshing = provider.provider.is_refreshing(cx);
 7433
 7434        fn pending_completion_container() -> Div {
 7435            h_flex()
 7436                .h_full()
 7437                .flex_1()
 7438                .gap_2()
 7439                .child(Icon::new(IconName::ZedPredict))
 7440        }
 7441
 7442        let completion = match &self.active_inline_completion {
 7443            Some(prediction) => {
 7444                if !self.has_visible_completions_menu() {
 7445                    const RADIUS: Pixels = px(6.);
 7446                    const BORDER_WIDTH: Pixels = px(1.);
 7447
 7448                    return Some(
 7449                        h_flex()
 7450                            .elevation_2(cx)
 7451                            .border(BORDER_WIDTH)
 7452                            .border_color(cx.theme().colors().border)
 7453                            .when(accept_keystroke.is_none(), |el| {
 7454                                el.border_color(cx.theme().status().error)
 7455                            })
 7456                            .rounded(RADIUS)
 7457                            .rounded_tl(px(0.))
 7458                            .overflow_hidden()
 7459                            .child(div().px_1p5().child(match &prediction.completion {
 7460                                InlineCompletion::Move { target, snapshot } => {
 7461                                    use text::ToPoint as _;
 7462                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7463                                    {
 7464                                        Icon::new(IconName::ZedPredictDown)
 7465                                    } else {
 7466                                        Icon::new(IconName::ZedPredictUp)
 7467                                    }
 7468                                }
 7469                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7470                            }))
 7471                            .child(
 7472                                h_flex()
 7473                                    .gap_1()
 7474                                    .py_1()
 7475                                    .px_2()
 7476                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7477                                    .border_l_1()
 7478                                    .border_color(cx.theme().colors().border)
 7479                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7480                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7481                                        el.child(
 7482                                            Label::new("Hold")
 7483                                                .size(LabelSize::Small)
 7484                                                .when(accept_keystroke.is_none(), |el| {
 7485                                                    el.strikethrough()
 7486                                                })
 7487                                                .line_height_style(LineHeightStyle::UiLabel),
 7488                                        )
 7489                                    })
 7490                                    .id("edit_prediction_cursor_popover_keybind")
 7491                                    .when(accept_keystroke.is_none(), |el| {
 7492                                        let status_colors = cx.theme().status();
 7493
 7494                                        el.bg(status_colors.error_background)
 7495                                            .border_color(status_colors.error.opacity(0.6))
 7496                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7497                                            .cursor_default()
 7498                                            .hoverable_tooltip(move |_window, cx| {
 7499                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7500                                                    .into()
 7501                                            })
 7502                                    })
 7503                                    .when_some(
 7504                                        accept_keystroke.as_ref(),
 7505                                        |el, accept_keystroke| {
 7506                                            el.child(h_flex().children(ui::render_modifiers(
 7507                                                &accept_keystroke.modifiers,
 7508                                                PlatformStyle::platform(),
 7509                                                Some(Color::Default),
 7510                                                Some(IconSize::XSmall.rems().into()),
 7511                                                false,
 7512                                            )))
 7513                                        },
 7514                                    ),
 7515                            )
 7516                            .into_any(),
 7517                    );
 7518                }
 7519
 7520                self.render_edit_prediction_cursor_popover_preview(
 7521                    prediction,
 7522                    cursor_point,
 7523                    style,
 7524                    cx,
 7525                )?
 7526            }
 7527
 7528            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7529                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7530                    stale_completion,
 7531                    cursor_point,
 7532                    style,
 7533                    cx,
 7534                )?,
 7535
 7536                None => {
 7537                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7538                }
 7539            },
 7540
 7541            None => pending_completion_container().child(Label::new("No Prediction")),
 7542        };
 7543
 7544        let completion = if is_refreshing {
 7545            completion
 7546                .with_animation(
 7547                    "loading-completion",
 7548                    Animation::new(Duration::from_secs(2))
 7549                        .repeat()
 7550                        .with_easing(pulsating_between(0.4, 0.8)),
 7551                    |label, delta| label.opacity(delta),
 7552                )
 7553                .into_any_element()
 7554        } else {
 7555            completion.into_any_element()
 7556        };
 7557
 7558        let has_completion = self.active_inline_completion.is_some();
 7559
 7560        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7561        Some(
 7562            h_flex()
 7563                .min_w(min_width)
 7564                .max_w(max_width)
 7565                .flex_1()
 7566                .elevation_2(cx)
 7567                .border_color(cx.theme().colors().border)
 7568                .child(
 7569                    div()
 7570                        .flex_1()
 7571                        .py_1()
 7572                        .px_2()
 7573                        .overflow_hidden()
 7574                        .child(completion),
 7575                )
 7576                .when_some(accept_keystroke, |el, accept_keystroke| {
 7577                    if !accept_keystroke.modifiers.modified() {
 7578                        return el;
 7579                    }
 7580
 7581                    el.child(
 7582                        h_flex()
 7583                            .h_full()
 7584                            .border_l_1()
 7585                            .rounded_r_lg()
 7586                            .border_color(cx.theme().colors().border)
 7587                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7588                            .gap_1()
 7589                            .py_1()
 7590                            .px_2()
 7591                            .child(
 7592                                h_flex()
 7593                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7594                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7595                                    .child(h_flex().children(ui::render_modifiers(
 7596                                        &accept_keystroke.modifiers,
 7597                                        PlatformStyle::platform(),
 7598                                        Some(if !has_completion {
 7599                                            Color::Muted
 7600                                        } else {
 7601                                            Color::Default
 7602                                        }),
 7603                                        None,
 7604                                        false,
 7605                                    ))),
 7606                            )
 7607                            .child(Label::new("Preview").into_any_element())
 7608                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7609                    )
 7610                })
 7611                .into_any(),
 7612        )
 7613    }
 7614
 7615    fn render_edit_prediction_cursor_popover_preview(
 7616        &self,
 7617        completion: &InlineCompletionState,
 7618        cursor_point: Point,
 7619        style: &EditorStyle,
 7620        cx: &mut Context<Editor>,
 7621    ) -> Option<Div> {
 7622        use text::ToPoint as _;
 7623
 7624        fn render_relative_row_jump(
 7625            prefix: impl Into<String>,
 7626            current_row: u32,
 7627            target_row: u32,
 7628        ) -> Div {
 7629            let (row_diff, arrow) = if target_row < current_row {
 7630                (current_row - target_row, IconName::ArrowUp)
 7631            } else {
 7632                (target_row - current_row, IconName::ArrowDown)
 7633            };
 7634
 7635            h_flex()
 7636                .child(
 7637                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7638                        .color(Color::Muted)
 7639                        .size(LabelSize::Small),
 7640                )
 7641                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7642        }
 7643
 7644        match &completion.completion {
 7645            InlineCompletion::Move {
 7646                target, snapshot, ..
 7647            } => Some(
 7648                h_flex()
 7649                    .px_2()
 7650                    .gap_2()
 7651                    .flex_1()
 7652                    .child(
 7653                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7654                            Icon::new(IconName::ZedPredictDown)
 7655                        } else {
 7656                            Icon::new(IconName::ZedPredictUp)
 7657                        },
 7658                    )
 7659                    .child(Label::new("Jump to Edit")),
 7660            ),
 7661
 7662            InlineCompletion::Edit {
 7663                edits,
 7664                edit_preview,
 7665                snapshot,
 7666                display_mode: _,
 7667            } => {
 7668                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7669
 7670                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7671                    &snapshot,
 7672                    &edits,
 7673                    edit_preview.as_ref()?,
 7674                    true,
 7675                    cx,
 7676                )
 7677                .first_line_preview();
 7678
 7679                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7680                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7681
 7682                let preview = h_flex()
 7683                    .gap_1()
 7684                    .min_w_16()
 7685                    .child(styled_text)
 7686                    .when(has_more_lines, |parent| parent.child(""));
 7687
 7688                let left = if first_edit_row != cursor_point.row {
 7689                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7690                        .into_any_element()
 7691                } else {
 7692                    Icon::new(IconName::ZedPredict).into_any_element()
 7693                };
 7694
 7695                Some(
 7696                    h_flex()
 7697                        .h_full()
 7698                        .flex_1()
 7699                        .gap_2()
 7700                        .pr_1()
 7701                        .overflow_x_hidden()
 7702                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7703                        .child(left)
 7704                        .child(preview),
 7705                )
 7706            }
 7707        }
 7708    }
 7709
 7710    fn render_context_menu(
 7711        &self,
 7712        style: &EditorStyle,
 7713        max_height_in_lines: u32,
 7714        window: &mut Window,
 7715        cx: &mut Context<Editor>,
 7716    ) -> Option<AnyElement> {
 7717        let menu = self.context_menu.borrow();
 7718        let menu = menu.as_ref()?;
 7719        if !menu.visible() {
 7720            return None;
 7721        };
 7722        Some(menu.render(style, max_height_in_lines, window, cx))
 7723    }
 7724
 7725    fn render_context_menu_aside(
 7726        &mut self,
 7727        max_size: Size<Pixels>,
 7728        window: &mut Window,
 7729        cx: &mut Context<Editor>,
 7730    ) -> Option<AnyElement> {
 7731        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7732            if menu.visible() {
 7733                menu.render_aside(self, max_size, window, cx)
 7734            } else {
 7735                None
 7736            }
 7737        })
 7738    }
 7739
 7740    fn hide_context_menu(
 7741        &mut self,
 7742        window: &mut Window,
 7743        cx: &mut Context<Self>,
 7744    ) -> Option<CodeContextMenu> {
 7745        cx.notify();
 7746        self.completion_tasks.clear();
 7747        let context_menu = self.context_menu.borrow_mut().take();
 7748        self.stale_inline_completion_in_menu.take();
 7749        self.update_visible_inline_completion(window, cx);
 7750        context_menu
 7751    }
 7752
 7753    fn show_snippet_choices(
 7754        &mut self,
 7755        choices: &Vec<String>,
 7756        selection: Range<Anchor>,
 7757        cx: &mut Context<Self>,
 7758    ) {
 7759        if selection.start.buffer_id.is_none() {
 7760            return;
 7761        }
 7762        let buffer_id = selection.start.buffer_id.unwrap();
 7763        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7764        let id = post_inc(&mut self.next_completion_id);
 7765
 7766        if let Some(buffer) = buffer {
 7767            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7768                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7769            ));
 7770        }
 7771    }
 7772
 7773    pub fn insert_snippet(
 7774        &mut self,
 7775        insertion_ranges: &[Range<usize>],
 7776        snippet: Snippet,
 7777        window: &mut Window,
 7778        cx: &mut Context<Self>,
 7779    ) -> Result<()> {
 7780        struct Tabstop<T> {
 7781            is_end_tabstop: bool,
 7782            ranges: Vec<Range<T>>,
 7783            choices: Option<Vec<String>>,
 7784        }
 7785
 7786        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7787            let snippet_text: Arc<str> = snippet.text.clone().into();
 7788            let edits = insertion_ranges
 7789                .iter()
 7790                .cloned()
 7791                .map(|range| (range, snippet_text.clone()));
 7792            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 7793
 7794            let snapshot = &*buffer.read(cx);
 7795            let snippet = &snippet;
 7796            snippet
 7797                .tabstops
 7798                .iter()
 7799                .map(|tabstop| {
 7800                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7801                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7802                    });
 7803                    let mut tabstop_ranges = tabstop
 7804                        .ranges
 7805                        .iter()
 7806                        .flat_map(|tabstop_range| {
 7807                            let mut delta = 0_isize;
 7808                            insertion_ranges.iter().map(move |insertion_range| {
 7809                                let insertion_start = insertion_range.start as isize + delta;
 7810                                delta +=
 7811                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7812
 7813                                let start = ((insertion_start + tabstop_range.start) as usize)
 7814                                    .min(snapshot.len());
 7815                                let end = ((insertion_start + tabstop_range.end) as usize)
 7816                                    .min(snapshot.len());
 7817                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7818                            })
 7819                        })
 7820                        .collect::<Vec<_>>();
 7821                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7822
 7823                    Tabstop {
 7824                        is_end_tabstop,
 7825                        ranges: tabstop_ranges,
 7826                        choices: tabstop.choices.clone(),
 7827                    }
 7828                })
 7829                .collect::<Vec<_>>()
 7830        });
 7831        if let Some(tabstop) = tabstops.first() {
 7832            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7833                s.select_ranges(tabstop.ranges.iter().cloned());
 7834            });
 7835
 7836            if let Some(choices) = &tabstop.choices {
 7837                if let Some(selection) = tabstop.ranges.first() {
 7838                    self.show_snippet_choices(choices, selection.clone(), cx)
 7839                }
 7840            }
 7841
 7842            // If we're already at the last tabstop and it's at the end of the snippet,
 7843            // we're done, we don't need to keep the state around.
 7844            if !tabstop.is_end_tabstop {
 7845                let choices = tabstops
 7846                    .iter()
 7847                    .map(|tabstop| tabstop.choices.clone())
 7848                    .collect();
 7849
 7850                let ranges = tabstops
 7851                    .into_iter()
 7852                    .map(|tabstop| tabstop.ranges)
 7853                    .collect::<Vec<_>>();
 7854
 7855                self.snippet_stack.push(SnippetState {
 7856                    active_index: 0,
 7857                    ranges,
 7858                    choices,
 7859                });
 7860            }
 7861
 7862            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7863            if self.autoclose_regions.is_empty() {
 7864                let snapshot = self.buffer.read(cx).snapshot(cx);
 7865                for selection in &mut self.selections.all::<Point>(cx) {
 7866                    let selection_head = selection.head();
 7867                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7868                        continue;
 7869                    };
 7870
 7871                    let mut bracket_pair = None;
 7872                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7873                    let prev_chars = snapshot
 7874                        .reversed_chars_at(selection_head)
 7875                        .collect::<String>();
 7876                    for (pair, enabled) in scope.brackets() {
 7877                        if enabled
 7878                            && pair.close
 7879                            && prev_chars.starts_with(pair.start.as_str())
 7880                            && next_chars.starts_with(pair.end.as_str())
 7881                        {
 7882                            bracket_pair = Some(pair.clone());
 7883                            break;
 7884                        }
 7885                    }
 7886                    if let Some(pair) = bracket_pair {
 7887                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 7888                        let autoclose_enabled =
 7889                            self.use_autoclose && snapshot_settings.use_autoclose;
 7890                        if autoclose_enabled {
 7891                            let start = snapshot.anchor_after(selection_head);
 7892                            let end = snapshot.anchor_after(selection_head);
 7893                            self.autoclose_regions.push(AutocloseRegion {
 7894                                selection_id: selection.id,
 7895                                range: start..end,
 7896                                pair,
 7897                            });
 7898                        }
 7899                    }
 7900                }
 7901            }
 7902        }
 7903        Ok(())
 7904    }
 7905
 7906    pub fn move_to_next_snippet_tabstop(
 7907        &mut self,
 7908        window: &mut Window,
 7909        cx: &mut Context<Self>,
 7910    ) -> bool {
 7911        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7912    }
 7913
 7914    pub fn move_to_prev_snippet_tabstop(
 7915        &mut self,
 7916        window: &mut Window,
 7917        cx: &mut Context<Self>,
 7918    ) -> bool {
 7919        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7920    }
 7921
 7922    pub fn move_to_snippet_tabstop(
 7923        &mut self,
 7924        bias: Bias,
 7925        window: &mut Window,
 7926        cx: &mut Context<Self>,
 7927    ) -> bool {
 7928        if let Some(mut snippet) = self.snippet_stack.pop() {
 7929            match bias {
 7930                Bias::Left => {
 7931                    if snippet.active_index > 0 {
 7932                        snippet.active_index -= 1;
 7933                    } else {
 7934                        self.snippet_stack.push(snippet);
 7935                        return false;
 7936                    }
 7937                }
 7938                Bias::Right => {
 7939                    if snippet.active_index + 1 < snippet.ranges.len() {
 7940                        snippet.active_index += 1;
 7941                    } else {
 7942                        self.snippet_stack.push(snippet);
 7943                        return false;
 7944                    }
 7945                }
 7946            }
 7947            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7948                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7949                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7950                });
 7951
 7952                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7953                    if let Some(selection) = current_ranges.first() {
 7954                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7955                    }
 7956                }
 7957
 7958                // If snippet state is not at the last tabstop, push it back on the stack
 7959                if snippet.active_index + 1 < snippet.ranges.len() {
 7960                    self.snippet_stack.push(snippet);
 7961                }
 7962                return true;
 7963            }
 7964        }
 7965
 7966        false
 7967    }
 7968
 7969    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7970        self.transact(window, cx, |this, window, cx| {
 7971            this.select_all(&SelectAll, window, cx);
 7972            this.insert("", window, cx);
 7973        });
 7974    }
 7975
 7976    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7977        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 7978        self.transact(window, cx, |this, window, cx| {
 7979            this.select_autoclose_pair(window, cx);
 7980            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7981            if !this.linked_edit_ranges.is_empty() {
 7982                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7983                let snapshot = this.buffer.read(cx).snapshot(cx);
 7984
 7985                for selection in selections.iter() {
 7986                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7987                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7988                    if selection_start.buffer_id != selection_end.buffer_id {
 7989                        continue;
 7990                    }
 7991                    if let Some(ranges) =
 7992                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7993                    {
 7994                        for (buffer, entries) in ranges {
 7995                            linked_ranges.entry(buffer).or_default().extend(entries);
 7996                        }
 7997                    }
 7998                }
 7999            }
 8000
 8001            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8002            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8003            for selection in &mut selections {
 8004                if selection.is_empty() {
 8005                    let old_head = selection.head();
 8006                    let mut new_head =
 8007                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8008                            .to_point(&display_map);
 8009                    if let Some((buffer, line_buffer_range)) = display_map
 8010                        .buffer_snapshot
 8011                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8012                    {
 8013                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8014                        let indent_len = match indent_size.kind {
 8015                            IndentKind::Space => {
 8016                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8017                            }
 8018                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8019                        };
 8020                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8021                            let indent_len = indent_len.get();
 8022                            new_head = cmp::min(
 8023                                new_head,
 8024                                MultiBufferPoint::new(
 8025                                    old_head.row,
 8026                                    ((old_head.column - 1) / indent_len) * indent_len,
 8027                                ),
 8028                            );
 8029                        }
 8030                    }
 8031
 8032                    selection.set_head(new_head, SelectionGoal::None);
 8033                }
 8034            }
 8035
 8036            this.signature_help_state.set_backspace_pressed(true);
 8037            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8038                s.select(selections)
 8039            });
 8040            this.insert("", window, cx);
 8041            let empty_str: Arc<str> = Arc::from("");
 8042            for (buffer, edits) in linked_ranges {
 8043                let snapshot = buffer.read(cx).snapshot();
 8044                use text::ToPoint as TP;
 8045
 8046                let edits = edits
 8047                    .into_iter()
 8048                    .map(|range| {
 8049                        let end_point = TP::to_point(&range.end, &snapshot);
 8050                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8051
 8052                        if end_point == start_point {
 8053                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8054                                .saturating_sub(1);
 8055                            start_point =
 8056                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8057                        };
 8058
 8059                        (start_point..end_point, empty_str.clone())
 8060                    })
 8061                    .sorted_by_key(|(range, _)| range.start)
 8062                    .collect::<Vec<_>>();
 8063                buffer.update(cx, |this, cx| {
 8064                    this.edit(edits, None, cx);
 8065                })
 8066            }
 8067            this.refresh_inline_completion(true, false, window, cx);
 8068            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8069        });
 8070    }
 8071
 8072    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8073        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8074        self.transact(window, cx, |this, window, cx| {
 8075            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8076                s.move_with(|map, selection| {
 8077                    if selection.is_empty() {
 8078                        let cursor = movement::right(map, selection.head());
 8079                        selection.end = cursor;
 8080                        selection.reversed = true;
 8081                        selection.goal = SelectionGoal::None;
 8082                    }
 8083                })
 8084            });
 8085            this.insert("", window, cx);
 8086            this.refresh_inline_completion(true, false, window, cx);
 8087        });
 8088    }
 8089
 8090    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8091        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8092        if self.move_to_prev_snippet_tabstop(window, cx) {
 8093            return;
 8094        }
 8095        self.outdent(&Outdent, window, cx);
 8096    }
 8097
 8098    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8099        if self.move_to_next_snippet_tabstop(window, cx) {
 8100            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8101            return;
 8102        }
 8103        if self.read_only(cx) {
 8104            return;
 8105        }
 8106        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8107        let mut selections = self.selections.all_adjusted(cx);
 8108        let buffer = self.buffer.read(cx);
 8109        let snapshot = buffer.snapshot(cx);
 8110        let rows_iter = selections.iter().map(|s| s.head().row);
 8111        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8112
 8113        let mut edits = Vec::new();
 8114        let mut prev_edited_row = 0;
 8115        let mut row_delta = 0;
 8116        for selection in &mut selections {
 8117            if selection.start.row != prev_edited_row {
 8118                row_delta = 0;
 8119            }
 8120            prev_edited_row = selection.end.row;
 8121
 8122            // If the selection is non-empty, then increase the indentation of the selected lines.
 8123            if !selection.is_empty() {
 8124                row_delta =
 8125                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8126                continue;
 8127            }
 8128
 8129            // If the selection is empty and the cursor is in the leading whitespace before the
 8130            // suggested indentation, then auto-indent the line.
 8131            let cursor = selection.head();
 8132            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8133            if let Some(suggested_indent) =
 8134                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8135            {
 8136                if cursor.column < suggested_indent.len
 8137                    && cursor.column <= current_indent.len
 8138                    && current_indent.len <= suggested_indent.len
 8139                {
 8140                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8141                    selection.end = selection.start;
 8142                    if row_delta == 0 {
 8143                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8144                            cursor.row,
 8145                            current_indent,
 8146                            suggested_indent,
 8147                        ));
 8148                        row_delta = suggested_indent.len - current_indent.len;
 8149                    }
 8150                    continue;
 8151                }
 8152            }
 8153
 8154            // Otherwise, insert a hard or soft tab.
 8155            let settings = buffer.language_settings_at(cursor, cx);
 8156            let tab_size = if settings.hard_tabs {
 8157                IndentSize::tab()
 8158            } else {
 8159                let tab_size = settings.tab_size.get();
 8160                let char_column = snapshot
 8161                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8162                    .flat_map(str::chars)
 8163                    .count()
 8164                    + row_delta as usize;
 8165                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 8166                IndentSize::spaces(chars_to_next_tab_stop)
 8167            };
 8168            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8169            selection.end = selection.start;
 8170            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8171            row_delta += tab_size.len;
 8172        }
 8173
 8174        self.transact(window, cx, |this, window, cx| {
 8175            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8176            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8177                s.select(selections)
 8178            });
 8179            this.refresh_inline_completion(true, false, window, cx);
 8180        });
 8181    }
 8182
 8183    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8184        if self.read_only(cx) {
 8185            return;
 8186        }
 8187        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8188        let mut selections = self.selections.all::<Point>(cx);
 8189        let mut prev_edited_row = 0;
 8190        let mut row_delta = 0;
 8191        let mut edits = Vec::new();
 8192        let buffer = self.buffer.read(cx);
 8193        let snapshot = buffer.snapshot(cx);
 8194        for selection in &mut selections {
 8195            if selection.start.row != prev_edited_row {
 8196                row_delta = 0;
 8197            }
 8198            prev_edited_row = selection.end.row;
 8199
 8200            row_delta =
 8201                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8202        }
 8203
 8204        self.transact(window, cx, |this, window, cx| {
 8205            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8206            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8207                s.select(selections)
 8208            });
 8209        });
 8210    }
 8211
 8212    fn indent_selection(
 8213        buffer: &MultiBuffer,
 8214        snapshot: &MultiBufferSnapshot,
 8215        selection: &mut Selection<Point>,
 8216        edits: &mut Vec<(Range<Point>, String)>,
 8217        delta_for_start_row: u32,
 8218        cx: &App,
 8219    ) -> u32 {
 8220        let settings = buffer.language_settings_at(selection.start, cx);
 8221        let tab_size = settings.tab_size.get();
 8222        let indent_kind = if settings.hard_tabs {
 8223            IndentKind::Tab
 8224        } else {
 8225            IndentKind::Space
 8226        };
 8227        let mut start_row = selection.start.row;
 8228        let mut end_row = selection.end.row + 1;
 8229
 8230        // If a selection ends at the beginning of a line, don't indent
 8231        // that last line.
 8232        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8233            end_row -= 1;
 8234        }
 8235
 8236        // Avoid re-indenting a row that has already been indented by a
 8237        // previous selection, but still update this selection's column
 8238        // to reflect that indentation.
 8239        if delta_for_start_row > 0 {
 8240            start_row += 1;
 8241            selection.start.column += delta_for_start_row;
 8242            if selection.end.row == selection.start.row {
 8243                selection.end.column += delta_for_start_row;
 8244            }
 8245        }
 8246
 8247        let mut delta_for_end_row = 0;
 8248        let has_multiple_rows = start_row + 1 != end_row;
 8249        for row in start_row..end_row {
 8250            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8251            let indent_delta = match (current_indent.kind, indent_kind) {
 8252                (IndentKind::Space, IndentKind::Space) => {
 8253                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8254                    IndentSize::spaces(columns_to_next_tab_stop)
 8255                }
 8256                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8257                (_, IndentKind::Tab) => IndentSize::tab(),
 8258            };
 8259
 8260            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8261                0
 8262            } else {
 8263                selection.start.column
 8264            };
 8265            let row_start = Point::new(row, start);
 8266            edits.push((
 8267                row_start..row_start,
 8268                indent_delta.chars().collect::<String>(),
 8269            ));
 8270
 8271            // Update this selection's endpoints to reflect the indentation.
 8272            if row == selection.start.row {
 8273                selection.start.column += indent_delta.len;
 8274            }
 8275            if row == selection.end.row {
 8276                selection.end.column += indent_delta.len;
 8277                delta_for_end_row = indent_delta.len;
 8278            }
 8279        }
 8280
 8281        if selection.start.row == selection.end.row {
 8282            delta_for_start_row + delta_for_end_row
 8283        } else {
 8284            delta_for_end_row
 8285        }
 8286    }
 8287
 8288    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8289        if self.read_only(cx) {
 8290            return;
 8291        }
 8292        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8293        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8294        let selections = self.selections.all::<Point>(cx);
 8295        let mut deletion_ranges = Vec::new();
 8296        let mut last_outdent = None;
 8297        {
 8298            let buffer = self.buffer.read(cx);
 8299            let snapshot = buffer.snapshot(cx);
 8300            for selection in &selections {
 8301                let settings = buffer.language_settings_at(selection.start, cx);
 8302                let tab_size = settings.tab_size.get();
 8303                let mut rows = selection.spanned_rows(false, &display_map);
 8304
 8305                // Avoid re-outdenting a row that has already been outdented by a
 8306                // previous selection.
 8307                if let Some(last_row) = last_outdent {
 8308                    if last_row == rows.start {
 8309                        rows.start = rows.start.next_row();
 8310                    }
 8311                }
 8312                let has_multiple_rows = rows.len() > 1;
 8313                for row in rows.iter_rows() {
 8314                    let indent_size = snapshot.indent_size_for_line(row);
 8315                    if indent_size.len > 0 {
 8316                        let deletion_len = match indent_size.kind {
 8317                            IndentKind::Space => {
 8318                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8319                                if columns_to_prev_tab_stop == 0 {
 8320                                    tab_size
 8321                                } else {
 8322                                    columns_to_prev_tab_stop
 8323                                }
 8324                            }
 8325                            IndentKind::Tab => 1,
 8326                        };
 8327                        let start = if has_multiple_rows
 8328                            || deletion_len > selection.start.column
 8329                            || indent_size.len < selection.start.column
 8330                        {
 8331                            0
 8332                        } else {
 8333                            selection.start.column - deletion_len
 8334                        };
 8335                        deletion_ranges.push(
 8336                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8337                        );
 8338                        last_outdent = Some(row);
 8339                    }
 8340                }
 8341            }
 8342        }
 8343
 8344        self.transact(window, cx, |this, window, cx| {
 8345            this.buffer.update(cx, |buffer, cx| {
 8346                let empty_str: Arc<str> = Arc::default();
 8347                buffer.edit(
 8348                    deletion_ranges
 8349                        .into_iter()
 8350                        .map(|range| (range, empty_str.clone())),
 8351                    None,
 8352                    cx,
 8353                );
 8354            });
 8355            let selections = this.selections.all::<usize>(cx);
 8356            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8357                s.select(selections)
 8358            });
 8359        });
 8360    }
 8361
 8362    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8363        if self.read_only(cx) {
 8364            return;
 8365        }
 8366        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8367        let selections = self
 8368            .selections
 8369            .all::<usize>(cx)
 8370            .into_iter()
 8371            .map(|s| s.range());
 8372
 8373        self.transact(window, cx, |this, window, cx| {
 8374            this.buffer.update(cx, |buffer, cx| {
 8375                buffer.autoindent_ranges(selections, cx);
 8376            });
 8377            let selections = this.selections.all::<usize>(cx);
 8378            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8379                s.select(selections)
 8380            });
 8381        });
 8382    }
 8383
 8384    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8385        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8386        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8387        let selections = self.selections.all::<Point>(cx);
 8388
 8389        let mut new_cursors = Vec::new();
 8390        let mut edit_ranges = Vec::new();
 8391        let mut selections = selections.iter().peekable();
 8392        while let Some(selection) = selections.next() {
 8393            let mut rows = selection.spanned_rows(false, &display_map);
 8394            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8395
 8396            // Accumulate contiguous regions of rows that we want to delete.
 8397            while let Some(next_selection) = selections.peek() {
 8398                let next_rows = next_selection.spanned_rows(false, &display_map);
 8399                if next_rows.start <= rows.end {
 8400                    rows.end = next_rows.end;
 8401                    selections.next().unwrap();
 8402                } else {
 8403                    break;
 8404                }
 8405            }
 8406
 8407            let buffer = &display_map.buffer_snapshot;
 8408            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8409            let edit_end;
 8410            let cursor_buffer_row;
 8411            if buffer.max_point().row >= rows.end.0 {
 8412                // If there's a line after the range, delete the \n from the end of the row range
 8413                // and position the cursor on the next line.
 8414                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8415                cursor_buffer_row = rows.end;
 8416            } else {
 8417                // If there isn't a line after the range, delete the \n from the line before the
 8418                // start of the row range and position the cursor there.
 8419                edit_start = edit_start.saturating_sub(1);
 8420                edit_end = buffer.len();
 8421                cursor_buffer_row = rows.start.previous_row();
 8422            }
 8423
 8424            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8425            *cursor.column_mut() =
 8426                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8427
 8428            new_cursors.push((
 8429                selection.id,
 8430                buffer.anchor_after(cursor.to_point(&display_map)),
 8431            ));
 8432            edit_ranges.push(edit_start..edit_end);
 8433        }
 8434
 8435        self.transact(window, cx, |this, window, cx| {
 8436            let buffer = this.buffer.update(cx, |buffer, cx| {
 8437                let empty_str: Arc<str> = Arc::default();
 8438                buffer.edit(
 8439                    edit_ranges
 8440                        .into_iter()
 8441                        .map(|range| (range, empty_str.clone())),
 8442                    None,
 8443                    cx,
 8444                );
 8445                buffer.snapshot(cx)
 8446            });
 8447            let new_selections = new_cursors
 8448                .into_iter()
 8449                .map(|(id, cursor)| {
 8450                    let cursor = cursor.to_point(&buffer);
 8451                    Selection {
 8452                        id,
 8453                        start: cursor,
 8454                        end: cursor,
 8455                        reversed: false,
 8456                        goal: SelectionGoal::None,
 8457                    }
 8458                })
 8459                .collect();
 8460
 8461            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8462                s.select(new_selections);
 8463            });
 8464        });
 8465    }
 8466
 8467    pub fn join_lines_impl(
 8468        &mut self,
 8469        insert_whitespace: bool,
 8470        window: &mut Window,
 8471        cx: &mut Context<Self>,
 8472    ) {
 8473        if self.read_only(cx) {
 8474            return;
 8475        }
 8476        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8477        for selection in self.selections.all::<Point>(cx) {
 8478            let start = MultiBufferRow(selection.start.row);
 8479            // Treat single line selections as if they include the next line. Otherwise this action
 8480            // would do nothing for single line selections individual cursors.
 8481            let end = if selection.start.row == selection.end.row {
 8482                MultiBufferRow(selection.start.row + 1)
 8483            } else {
 8484                MultiBufferRow(selection.end.row)
 8485            };
 8486
 8487            if let Some(last_row_range) = row_ranges.last_mut() {
 8488                if start <= last_row_range.end {
 8489                    last_row_range.end = end;
 8490                    continue;
 8491                }
 8492            }
 8493            row_ranges.push(start..end);
 8494        }
 8495
 8496        let snapshot = self.buffer.read(cx).snapshot(cx);
 8497        let mut cursor_positions = Vec::new();
 8498        for row_range in &row_ranges {
 8499            let anchor = snapshot.anchor_before(Point::new(
 8500                row_range.end.previous_row().0,
 8501                snapshot.line_len(row_range.end.previous_row()),
 8502            ));
 8503            cursor_positions.push(anchor..anchor);
 8504        }
 8505
 8506        self.transact(window, cx, |this, window, cx| {
 8507            for row_range in row_ranges.into_iter().rev() {
 8508                for row in row_range.iter_rows().rev() {
 8509                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8510                    let next_line_row = row.next_row();
 8511                    let indent = snapshot.indent_size_for_line(next_line_row);
 8512                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8513
 8514                    let replace =
 8515                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8516                            " "
 8517                        } else {
 8518                            ""
 8519                        };
 8520
 8521                    this.buffer.update(cx, |buffer, cx| {
 8522                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8523                    });
 8524                }
 8525            }
 8526
 8527            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8528                s.select_anchor_ranges(cursor_positions)
 8529            });
 8530        });
 8531    }
 8532
 8533    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8534        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8535        self.join_lines_impl(true, window, cx);
 8536    }
 8537
 8538    pub fn sort_lines_case_sensitive(
 8539        &mut self,
 8540        _: &SortLinesCaseSensitive,
 8541        window: &mut Window,
 8542        cx: &mut Context<Self>,
 8543    ) {
 8544        self.manipulate_lines(window, cx, |lines| lines.sort())
 8545    }
 8546
 8547    pub fn sort_lines_case_insensitive(
 8548        &mut self,
 8549        _: &SortLinesCaseInsensitive,
 8550        window: &mut Window,
 8551        cx: &mut Context<Self>,
 8552    ) {
 8553        self.manipulate_lines(window, cx, |lines| {
 8554            lines.sort_by_key(|line| line.to_lowercase())
 8555        })
 8556    }
 8557
 8558    pub fn unique_lines_case_insensitive(
 8559        &mut self,
 8560        _: &UniqueLinesCaseInsensitive,
 8561        window: &mut Window,
 8562        cx: &mut Context<Self>,
 8563    ) {
 8564        self.manipulate_lines(window, cx, |lines| {
 8565            let mut seen = HashSet::default();
 8566            lines.retain(|line| seen.insert(line.to_lowercase()));
 8567        })
 8568    }
 8569
 8570    pub fn unique_lines_case_sensitive(
 8571        &mut self,
 8572        _: &UniqueLinesCaseSensitive,
 8573        window: &mut Window,
 8574        cx: &mut Context<Self>,
 8575    ) {
 8576        self.manipulate_lines(window, cx, |lines| {
 8577            let mut seen = HashSet::default();
 8578            lines.retain(|line| seen.insert(*line));
 8579        })
 8580    }
 8581
 8582    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8583        let Some(project) = self.project.clone() else {
 8584            return;
 8585        };
 8586        self.reload(project, window, cx)
 8587            .detach_and_notify_err(window, cx);
 8588    }
 8589
 8590    pub fn restore_file(
 8591        &mut self,
 8592        _: &::git::RestoreFile,
 8593        window: &mut Window,
 8594        cx: &mut Context<Self>,
 8595    ) {
 8596        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8597        let mut buffer_ids = HashSet::default();
 8598        let snapshot = self.buffer().read(cx).snapshot(cx);
 8599        for selection in self.selections.all::<usize>(cx) {
 8600            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8601        }
 8602
 8603        let buffer = self.buffer().read(cx);
 8604        let ranges = buffer_ids
 8605            .into_iter()
 8606            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8607            .collect::<Vec<_>>();
 8608
 8609        self.restore_hunks_in_ranges(ranges, window, cx);
 8610    }
 8611
 8612    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8613        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8614        let selections = self
 8615            .selections
 8616            .all(cx)
 8617            .into_iter()
 8618            .map(|s| s.range())
 8619            .collect();
 8620        self.restore_hunks_in_ranges(selections, window, cx);
 8621    }
 8622
 8623    pub fn restore_hunks_in_ranges(
 8624        &mut self,
 8625        ranges: Vec<Range<Point>>,
 8626        window: &mut Window,
 8627        cx: &mut Context<Editor>,
 8628    ) {
 8629        let mut revert_changes = HashMap::default();
 8630        let chunk_by = self
 8631            .snapshot(window, cx)
 8632            .hunks_for_ranges(ranges)
 8633            .into_iter()
 8634            .chunk_by(|hunk| hunk.buffer_id);
 8635        for (buffer_id, hunks) in &chunk_by {
 8636            let hunks = hunks.collect::<Vec<_>>();
 8637            for hunk in &hunks {
 8638                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8639            }
 8640            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8641        }
 8642        drop(chunk_by);
 8643        if !revert_changes.is_empty() {
 8644            self.transact(window, cx, |editor, window, cx| {
 8645                editor.restore(revert_changes, window, cx);
 8646            });
 8647        }
 8648    }
 8649
 8650    pub fn open_active_item_in_terminal(
 8651        &mut self,
 8652        _: &OpenInTerminal,
 8653        window: &mut Window,
 8654        cx: &mut Context<Self>,
 8655    ) {
 8656        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8657            let project_path = buffer.read(cx).project_path(cx)?;
 8658            let project = self.project.as_ref()?.read(cx);
 8659            let entry = project.entry_for_path(&project_path, cx)?;
 8660            let parent = match &entry.canonical_path {
 8661                Some(canonical_path) => canonical_path.to_path_buf(),
 8662                None => project.absolute_path(&project_path, cx)?,
 8663            }
 8664            .parent()?
 8665            .to_path_buf();
 8666            Some(parent)
 8667        }) {
 8668            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8669        }
 8670    }
 8671
 8672    fn set_breakpoint_context_menu(
 8673        &mut self,
 8674        display_row: DisplayRow,
 8675        position: Option<Anchor>,
 8676        clicked_point: gpui::Point<Pixels>,
 8677        window: &mut Window,
 8678        cx: &mut Context<Self>,
 8679    ) {
 8680        if !cx.has_flag::<Debugger>() {
 8681            return;
 8682        }
 8683        let source = self
 8684            .buffer
 8685            .read(cx)
 8686            .snapshot(cx)
 8687            .anchor_before(Point::new(display_row.0, 0u32));
 8688
 8689        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8690
 8691        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8692            self,
 8693            source,
 8694            clicked_point,
 8695            context_menu,
 8696            window,
 8697            cx,
 8698        );
 8699    }
 8700
 8701    fn add_edit_breakpoint_block(
 8702        &mut self,
 8703        anchor: Anchor,
 8704        breakpoint: &Breakpoint,
 8705        edit_action: BreakpointPromptEditAction,
 8706        window: &mut Window,
 8707        cx: &mut Context<Self>,
 8708    ) {
 8709        let weak_editor = cx.weak_entity();
 8710        let bp_prompt = cx.new(|cx| {
 8711            BreakpointPromptEditor::new(
 8712                weak_editor,
 8713                anchor,
 8714                breakpoint.clone(),
 8715                edit_action,
 8716                window,
 8717                cx,
 8718            )
 8719        });
 8720
 8721        let height = bp_prompt.update(cx, |this, cx| {
 8722            this.prompt
 8723                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8724        });
 8725        let cloned_prompt = bp_prompt.clone();
 8726        let blocks = vec![BlockProperties {
 8727            style: BlockStyle::Sticky,
 8728            placement: BlockPlacement::Above(anchor),
 8729            height: Some(height),
 8730            render: Arc::new(move |cx| {
 8731                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8732                cloned_prompt.clone().into_any_element()
 8733            }),
 8734            priority: 0,
 8735        }];
 8736
 8737        let focus_handle = bp_prompt.focus_handle(cx);
 8738        window.focus(&focus_handle);
 8739
 8740        let block_ids = self.insert_blocks(blocks, None, cx);
 8741        bp_prompt.update(cx, |prompt, _| {
 8742            prompt.add_block_ids(block_ids);
 8743        });
 8744    }
 8745
 8746    fn breakpoint_at_cursor_head(
 8747        &self,
 8748        window: &mut Window,
 8749        cx: &mut Context<Self>,
 8750    ) -> Option<(Anchor, Breakpoint)> {
 8751        let cursor_position: Point = self.selections.newest(cx).head();
 8752        self.breakpoint_at_row(cursor_position.row, window, cx)
 8753    }
 8754
 8755    pub(crate) fn breakpoint_at_row(
 8756        &self,
 8757        row: u32,
 8758        window: &mut Window,
 8759        cx: &mut Context<Self>,
 8760    ) -> Option<(Anchor, Breakpoint)> {
 8761        let snapshot = self.snapshot(window, cx);
 8762        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8763
 8764        let project = self.project.clone()?;
 8765
 8766        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 8767            snapshot
 8768                .buffer_snapshot
 8769                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 8770        })?;
 8771
 8772        let enclosing_excerpt = breakpoint_position.excerpt_id;
 8773        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8774        let buffer_snapshot = buffer.read(cx).snapshot();
 8775
 8776        let row = buffer_snapshot
 8777            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 8778            .row;
 8779
 8780        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 8781        let anchor_end = snapshot
 8782            .buffer_snapshot
 8783            .anchor_after(Point::new(row, line_len));
 8784
 8785        let bp = self
 8786            .breakpoint_store
 8787            .as_ref()?
 8788            .read_with(cx, |breakpoint_store, cx| {
 8789                breakpoint_store
 8790                    .breakpoints(
 8791                        &buffer,
 8792                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 8793                        &buffer_snapshot,
 8794                        cx,
 8795                    )
 8796                    .next()
 8797                    .and_then(|(anchor, bp)| {
 8798                        let breakpoint_row = buffer_snapshot
 8799                            .summary_for_anchor::<text::PointUtf16>(anchor)
 8800                            .row;
 8801
 8802                        if breakpoint_row == row {
 8803                            snapshot
 8804                                .buffer_snapshot
 8805                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 8806                                .map(|anchor| (anchor, bp.clone()))
 8807                        } else {
 8808                            None
 8809                        }
 8810                    })
 8811            });
 8812        bp
 8813    }
 8814
 8815    pub fn edit_log_breakpoint(
 8816        &mut self,
 8817        _: &EditLogBreakpoint,
 8818        window: &mut Window,
 8819        cx: &mut Context<Self>,
 8820    ) {
 8821        let (anchor, bp) = self
 8822            .breakpoint_at_cursor_head(window, cx)
 8823            .unwrap_or_else(|| {
 8824                let cursor_position: Point = self.selections.newest(cx).head();
 8825
 8826                let breakpoint_position = self
 8827                    .snapshot(window, cx)
 8828                    .display_snapshot
 8829                    .buffer_snapshot
 8830                    .anchor_after(Point::new(cursor_position.row, 0));
 8831
 8832                (
 8833                    breakpoint_position,
 8834                    Breakpoint {
 8835                        message: None,
 8836                        state: BreakpointState::Enabled,
 8837                        condition: None,
 8838                        hit_condition: None,
 8839                    },
 8840                )
 8841            });
 8842
 8843        self.add_edit_breakpoint_block(anchor, &bp, BreakpointPromptEditAction::Log, window, cx);
 8844    }
 8845
 8846    pub fn enable_breakpoint(
 8847        &mut self,
 8848        _: &crate::actions::EnableBreakpoint,
 8849        window: &mut Window,
 8850        cx: &mut Context<Self>,
 8851    ) {
 8852        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8853            if breakpoint.is_disabled() {
 8854                self.edit_breakpoint_at_anchor(
 8855                    anchor,
 8856                    breakpoint,
 8857                    BreakpointEditAction::InvertState,
 8858                    cx,
 8859                );
 8860            }
 8861        }
 8862    }
 8863
 8864    pub fn disable_breakpoint(
 8865        &mut self,
 8866        _: &crate::actions::DisableBreakpoint,
 8867        window: &mut Window,
 8868        cx: &mut Context<Self>,
 8869    ) {
 8870        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8871            if breakpoint.is_enabled() {
 8872                self.edit_breakpoint_at_anchor(
 8873                    anchor,
 8874                    breakpoint,
 8875                    BreakpointEditAction::InvertState,
 8876                    cx,
 8877                );
 8878            }
 8879        }
 8880    }
 8881
 8882    pub fn toggle_breakpoint(
 8883        &mut self,
 8884        _: &crate::actions::ToggleBreakpoint,
 8885        window: &mut Window,
 8886        cx: &mut Context<Self>,
 8887    ) {
 8888        let edit_action = BreakpointEditAction::Toggle;
 8889
 8890        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8891            self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
 8892        } else {
 8893            let cursor_position: Point = self.selections.newest(cx).head();
 8894
 8895            let breakpoint_position = self
 8896                .snapshot(window, cx)
 8897                .display_snapshot
 8898                .buffer_snapshot
 8899                .anchor_after(Point::new(cursor_position.row, 0));
 8900
 8901            self.edit_breakpoint_at_anchor(
 8902                breakpoint_position,
 8903                Breakpoint::new_standard(),
 8904                edit_action,
 8905                cx,
 8906            );
 8907        }
 8908    }
 8909
 8910    pub fn edit_breakpoint_at_anchor(
 8911        &mut self,
 8912        breakpoint_position: Anchor,
 8913        breakpoint: Breakpoint,
 8914        edit_action: BreakpointEditAction,
 8915        cx: &mut Context<Self>,
 8916    ) {
 8917        let Some(breakpoint_store) = &self.breakpoint_store else {
 8918            return;
 8919        };
 8920
 8921        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 8922            if breakpoint_position == Anchor::min() {
 8923                self.buffer()
 8924                    .read(cx)
 8925                    .excerpt_buffer_ids()
 8926                    .into_iter()
 8927                    .next()
 8928            } else {
 8929                None
 8930            }
 8931        }) else {
 8932            return;
 8933        };
 8934
 8935        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 8936            return;
 8937        };
 8938
 8939        breakpoint_store.update(cx, |breakpoint_store, cx| {
 8940            breakpoint_store.toggle_breakpoint(
 8941                buffer,
 8942                (breakpoint_position.text_anchor, breakpoint),
 8943                edit_action,
 8944                cx,
 8945            );
 8946        });
 8947
 8948        cx.notify();
 8949    }
 8950
 8951    #[cfg(any(test, feature = "test-support"))]
 8952    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 8953        self.breakpoint_store.clone()
 8954    }
 8955
 8956    pub fn prepare_restore_change(
 8957        &self,
 8958        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 8959        hunk: &MultiBufferDiffHunk,
 8960        cx: &mut App,
 8961    ) -> Option<()> {
 8962        if hunk.is_created_file() {
 8963            return None;
 8964        }
 8965        let buffer = self.buffer.read(cx);
 8966        let diff = buffer.diff_for(hunk.buffer_id)?;
 8967        let buffer = buffer.buffer(hunk.buffer_id)?;
 8968        let buffer = buffer.read(cx);
 8969        let original_text = diff
 8970            .read(cx)
 8971            .base_text()
 8972            .as_rope()
 8973            .slice(hunk.diff_base_byte_range.clone());
 8974        let buffer_snapshot = buffer.snapshot();
 8975        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 8976        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 8977            probe
 8978                .0
 8979                .start
 8980                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 8981                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 8982        }) {
 8983            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 8984            Some(())
 8985        } else {
 8986            None
 8987        }
 8988    }
 8989
 8990    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 8991        self.manipulate_lines(window, cx, |lines| lines.reverse())
 8992    }
 8993
 8994    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 8995        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 8996    }
 8997
 8998    fn manipulate_lines<Fn>(
 8999        &mut self,
 9000        window: &mut Window,
 9001        cx: &mut Context<Self>,
 9002        mut callback: Fn,
 9003    ) where
 9004        Fn: FnMut(&mut Vec<&str>),
 9005    {
 9006        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9007
 9008        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9009        let buffer = self.buffer.read(cx).snapshot(cx);
 9010
 9011        let mut edits = Vec::new();
 9012
 9013        let selections = self.selections.all::<Point>(cx);
 9014        let mut selections = selections.iter().peekable();
 9015        let mut contiguous_row_selections = Vec::new();
 9016        let mut new_selections = Vec::new();
 9017        let mut added_lines = 0;
 9018        let mut removed_lines = 0;
 9019
 9020        while let Some(selection) = selections.next() {
 9021            let (start_row, end_row) = consume_contiguous_rows(
 9022                &mut contiguous_row_selections,
 9023                selection,
 9024                &display_map,
 9025                &mut selections,
 9026            );
 9027
 9028            let start_point = Point::new(start_row.0, 0);
 9029            let end_point = Point::new(
 9030                end_row.previous_row().0,
 9031                buffer.line_len(end_row.previous_row()),
 9032            );
 9033            let text = buffer
 9034                .text_for_range(start_point..end_point)
 9035                .collect::<String>();
 9036
 9037            let mut lines = text.split('\n').collect_vec();
 9038
 9039            let lines_before = lines.len();
 9040            callback(&mut lines);
 9041            let lines_after = lines.len();
 9042
 9043            edits.push((start_point..end_point, lines.join("\n")));
 9044
 9045            // Selections must change based on added and removed line count
 9046            let start_row =
 9047                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9048            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9049            new_selections.push(Selection {
 9050                id: selection.id,
 9051                start: start_row,
 9052                end: end_row,
 9053                goal: SelectionGoal::None,
 9054                reversed: selection.reversed,
 9055            });
 9056
 9057            if lines_after > lines_before {
 9058                added_lines += lines_after - lines_before;
 9059            } else if lines_before > lines_after {
 9060                removed_lines += lines_before - lines_after;
 9061            }
 9062        }
 9063
 9064        self.transact(window, cx, |this, window, cx| {
 9065            let buffer = this.buffer.update(cx, |buffer, cx| {
 9066                buffer.edit(edits, None, cx);
 9067                buffer.snapshot(cx)
 9068            });
 9069
 9070            // Recalculate offsets on newly edited buffer
 9071            let new_selections = new_selections
 9072                .iter()
 9073                .map(|s| {
 9074                    let start_point = Point::new(s.start.0, 0);
 9075                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9076                    Selection {
 9077                        id: s.id,
 9078                        start: buffer.point_to_offset(start_point),
 9079                        end: buffer.point_to_offset(end_point),
 9080                        goal: s.goal,
 9081                        reversed: s.reversed,
 9082                    }
 9083                })
 9084                .collect();
 9085
 9086            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9087                s.select(new_selections);
 9088            });
 9089
 9090            this.request_autoscroll(Autoscroll::fit(), cx);
 9091        });
 9092    }
 9093
 9094    pub fn convert_to_upper_case(
 9095        &mut self,
 9096        _: &ConvertToUpperCase,
 9097        window: &mut Window,
 9098        cx: &mut Context<Self>,
 9099    ) {
 9100        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9101    }
 9102
 9103    pub fn convert_to_lower_case(
 9104        &mut self,
 9105        _: &ConvertToLowerCase,
 9106        window: &mut Window,
 9107        cx: &mut Context<Self>,
 9108    ) {
 9109        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9110    }
 9111
 9112    pub fn convert_to_title_case(
 9113        &mut self,
 9114        _: &ConvertToTitleCase,
 9115        window: &mut Window,
 9116        cx: &mut Context<Self>,
 9117    ) {
 9118        self.manipulate_text(window, cx, |text| {
 9119            text.split('\n')
 9120                .map(|line| line.to_case(Case::Title))
 9121                .join("\n")
 9122        })
 9123    }
 9124
 9125    pub fn convert_to_snake_case(
 9126        &mut self,
 9127        _: &ConvertToSnakeCase,
 9128        window: &mut Window,
 9129        cx: &mut Context<Self>,
 9130    ) {
 9131        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9132    }
 9133
 9134    pub fn convert_to_kebab_case(
 9135        &mut self,
 9136        _: &ConvertToKebabCase,
 9137        window: &mut Window,
 9138        cx: &mut Context<Self>,
 9139    ) {
 9140        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9141    }
 9142
 9143    pub fn convert_to_upper_camel_case(
 9144        &mut self,
 9145        _: &ConvertToUpperCamelCase,
 9146        window: &mut Window,
 9147        cx: &mut Context<Self>,
 9148    ) {
 9149        self.manipulate_text(window, cx, |text| {
 9150            text.split('\n')
 9151                .map(|line| line.to_case(Case::UpperCamel))
 9152                .join("\n")
 9153        })
 9154    }
 9155
 9156    pub fn convert_to_lower_camel_case(
 9157        &mut self,
 9158        _: &ConvertToLowerCamelCase,
 9159        window: &mut Window,
 9160        cx: &mut Context<Self>,
 9161    ) {
 9162        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9163    }
 9164
 9165    pub fn convert_to_opposite_case(
 9166        &mut self,
 9167        _: &ConvertToOppositeCase,
 9168        window: &mut Window,
 9169        cx: &mut Context<Self>,
 9170    ) {
 9171        self.manipulate_text(window, cx, |text| {
 9172            text.chars()
 9173                .fold(String::with_capacity(text.len()), |mut t, c| {
 9174                    if c.is_uppercase() {
 9175                        t.extend(c.to_lowercase());
 9176                    } else {
 9177                        t.extend(c.to_uppercase());
 9178                    }
 9179                    t
 9180                })
 9181        })
 9182    }
 9183
 9184    pub fn convert_to_rot13(
 9185        &mut self,
 9186        _: &ConvertToRot13,
 9187        window: &mut Window,
 9188        cx: &mut Context<Self>,
 9189    ) {
 9190        self.manipulate_text(window, cx, |text| {
 9191            text.chars()
 9192                .map(|c| match c {
 9193                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9194                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9195                    _ => c,
 9196                })
 9197                .collect()
 9198        })
 9199    }
 9200
 9201    pub fn convert_to_rot47(
 9202        &mut self,
 9203        _: &ConvertToRot47,
 9204        window: &mut Window,
 9205        cx: &mut Context<Self>,
 9206    ) {
 9207        self.manipulate_text(window, cx, |text| {
 9208            text.chars()
 9209                .map(|c| {
 9210                    let code_point = c as u32;
 9211                    if code_point >= 33 && code_point <= 126 {
 9212                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9213                    }
 9214                    c
 9215                })
 9216                .collect()
 9217        })
 9218    }
 9219
 9220    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9221    where
 9222        Fn: FnMut(&str) -> String,
 9223    {
 9224        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9225        let buffer = self.buffer.read(cx).snapshot(cx);
 9226
 9227        let mut new_selections = Vec::new();
 9228        let mut edits = Vec::new();
 9229        let mut selection_adjustment = 0i32;
 9230
 9231        for selection in self.selections.all::<usize>(cx) {
 9232            let selection_is_empty = selection.is_empty();
 9233
 9234            let (start, end) = if selection_is_empty {
 9235                let word_range = movement::surrounding_word(
 9236                    &display_map,
 9237                    selection.start.to_display_point(&display_map),
 9238                );
 9239                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9240                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9241                (start, end)
 9242            } else {
 9243                (selection.start, selection.end)
 9244            };
 9245
 9246            let text = buffer.text_for_range(start..end).collect::<String>();
 9247            let old_length = text.len() as i32;
 9248            let text = callback(&text);
 9249
 9250            new_selections.push(Selection {
 9251                start: (start as i32 - selection_adjustment) as usize,
 9252                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9253                goal: SelectionGoal::None,
 9254                ..selection
 9255            });
 9256
 9257            selection_adjustment += old_length - text.len() as i32;
 9258
 9259            edits.push((start..end, text));
 9260        }
 9261
 9262        self.transact(window, cx, |this, window, cx| {
 9263            this.buffer.update(cx, |buffer, cx| {
 9264                buffer.edit(edits, None, cx);
 9265            });
 9266
 9267            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9268                s.select(new_selections);
 9269            });
 9270
 9271            this.request_autoscroll(Autoscroll::fit(), cx);
 9272        });
 9273    }
 9274
 9275    pub fn duplicate(
 9276        &mut self,
 9277        upwards: bool,
 9278        whole_lines: bool,
 9279        window: &mut Window,
 9280        cx: &mut Context<Self>,
 9281    ) {
 9282        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9283
 9284        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9285        let buffer = &display_map.buffer_snapshot;
 9286        let selections = self.selections.all::<Point>(cx);
 9287
 9288        let mut edits = Vec::new();
 9289        let mut selections_iter = selections.iter().peekable();
 9290        while let Some(selection) = selections_iter.next() {
 9291            let mut rows = selection.spanned_rows(false, &display_map);
 9292            // duplicate line-wise
 9293            if whole_lines || selection.start == selection.end {
 9294                // Avoid duplicating the same lines twice.
 9295                while let Some(next_selection) = selections_iter.peek() {
 9296                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9297                    if next_rows.start < rows.end {
 9298                        rows.end = next_rows.end;
 9299                        selections_iter.next().unwrap();
 9300                    } else {
 9301                        break;
 9302                    }
 9303                }
 9304
 9305                // Copy the text from the selected row region and splice it either at the start
 9306                // or end of the region.
 9307                let start = Point::new(rows.start.0, 0);
 9308                let end = Point::new(
 9309                    rows.end.previous_row().0,
 9310                    buffer.line_len(rows.end.previous_row()),
 9311                );
 9312                let text = buffer
 9313                    .text_for_range(start..end)
 9314                    .chain(Some("\n"))
 9315                    .collect::<String>();
 9316                let insert_location = if upwards {
 9317                    Point::new(rows.end.0, 0)
 9318                } else {
 9319                    start
 9320                };
 9321                edits.push((insert_location..insert_location, text));
 9322            } else {
 9323                // duplicate character-wise
 9324                let start = selection.start;
 9325                let end = selection.end;
 9326                let text = buffer.text_for_range(start..end).collect::<String>();
 9327                edits.push((selection.end..selection.end, text));
 9328            }
 9329        }
 9330
 9331        self.transact(window, cx, |this, _, cx| {
 9332            this.buffer.update(cx, |buffer, cx| {
 9333                buffer.edit(edits, None, cx);
 9334            });
 9335
 9336            this.request_autoscroll(Autoscroll::fit(), cx);
 9337        });
 9338    }
 9339
 9340    pub fn duplicate_line_up(
 9341        &mut self,
 9342        _: &DuplicateLineUp,
 9343        window: &mut Window,
 9344        cx: &mut Context<Self>,
 9345    ) {
 9346        self.duplicate(true, true, window, cx);
 9347    }
 9348
 9349    pub fn duplicate_line_down(
 9350        &mut self,
 9351        _: &DuplicateLineDown,
 9352        window: &mut Window,
 9353        cx: &mut Context<Self>,
 9354    ) {
 9355        self.duplicate(false, true, window, cx);
 9356    }
 9357
 9358    pub fn duplicate_selection(
 9359        &mut self,
 9360        _: &DuplicateSelection,
 9361        window: &mut Window,
 9362        cx: &mut Context<Self>,
 9363    ) {
 9364        self.duplicate(false, false, window, cx);
 9365    }
 9366
 9367    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9368        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9369
 9370        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9371        let buffer = self.buffer.read(cx).snapshot(cx);
 9372
 9373        let mut edits = Vec::new();
 9374        let mut unfold_ranges = Vec::new();
 9375        let mut refold_creases = Vec::new();
 9376
 9377        let selections = self.selections.all::<Point>(cx);
 9378        let mut selections = selections.iter().peekable();
 9379        let mut contiguous_row_selections = Vec::new();
 9380        let mut new_selections = Vec::new();
 9381
 9382        while let Some(selection) = selections.next() {
 9383            // Find all the selections that span a contiguous row range
 9384            let (start_row, end_row) = consume_contiguous_rows(
 9385                &mut contiguous_row_selections,
 9386                selection,
 9387                &display_map,
 9388                &mut selections,
 9389            );
 9390
 9391            // Move the text spanned by the row range to be before the line preceding the row range
 9392            if start_row.0 > 0 {
 9393                let range_to_move = Point::new(
 9394                    start_row.previous_row().0,
 9395                    buffer.line_len(start_row.previous_row()),
 9396                )
 9397                    ..Point::new(
 9398                        end_row.previous_row().0,
 9399                        buffer.line_len(end_row.previous_row()),
 9400                    );
 9401                let insertion_point = display_map
 9402                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9403                    .0;
 9404
 9405                // Don't move lines across excerpts
 9406                if buffer
 9407                    .excerpt_containing(insertion_point..range_to_move.end)
 9408                    .is_some()
 9409                {
 9410                    let text = buffer
 9411                        .text_for_range(range_to_move.clone())
 9412                        .flat_map(|s| s.chars())
 9413                        .skip(1)
 9414                        .chain(['\n'])
 9415                        .collect::<String>();
 9416
 9417                    edits.push((
 9418                        buffer.anchor_after(range_to_move.start)
 9419                            ..buffer.anchor_before(range_to_move.end),
 9420                        String::new(),
 9421                    ));
 9422                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9423                    edits.push((insertion_anchor..insertion_anchor, text));
 9424
 9425                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9426
 9427                    // Move selections up
 9428                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9429                        |mut selection| {
 9430                            selection.start.row -= row_delta;
 9431                            selection.end.row -= row_delta;
 9432                            selection
 9433                        },
 9434                    ));
 9435
 9436                    // Move folds up
 9437                    unfold_ranges.push(range_to_move.clone());
 9438                    for fold in display_map.folds_in_range(
 9439                        buffer.anchor_before(range_to_move.start)
 9440                            ..buffer.anchor_after(range_to_move.end),
 9441                    ) {
 9442                        let mut start = fold.range.start.to_point(&buffer);
 9443                        let mut end = fold.range.end.to_point(&buffer);
 9444                        start.row -= row_delta;
 9445                        end.row -= row_delta;
 9446                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9447                    }
 9448                }
 9449            }
 9450
 9451            // If we didn't move line(s), preserve the existing selections
 9452            new_selections.append(&mut contiguous_row_selections);
 9453        }
 9454
 9455        self.transact(window, cx, |this, window, cx| {
 9456            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9457            this.buffer.update(cx, |buffer, cx| {
 9458                for (range, text) in edits {
 9459                    buffer.edit([(range, text)], None, cx);
 9460                }
 9461            });
 9462            this.fold_creases(refold_creases, true, window, cx);
 9463            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9464                s.select(new_selections);
 9465            })
 9466        });
 9467    }
 9468
 9469    pub fn move_line_down(
 9470        &mut self,
 9471        _: &MoveLineDown,
 9472        window: &mut Window,
 9473        cx: &mut Context<Self>,
 9474    ) {
 9475        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9476
 9477        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9478        let buffer = self.buffer.read(cx).snapshot(cx);
 9479
 9480        let mut edits = Vec::new();
 9481        let mut unfold_ranges = Vec::new();
 9482        let mut refold_creases = Vec::new();
 9483
 9484        let selections = self.selections.all::<Point>(cx);
 9485        let mut selections = selections.iter().peekable();
 9486        let mut contiguous_row_selections = Vec::new();
 9487        let mut new_selections = Vec::new();
 9488
 9489        while let Some(selection) = selections.next() {
 9490            // Find all the selections that span a contiguous row range
 9491            let (start_row, end_row) = consume_contiguous_rows(
 9492                &mut contiguous_row_selections,
 9493                selection,
 9494                &display_map,
 9495                &mut selections,
 9496            );
 9497
 9498            // Move the text spanned by the row range to be after the last line of the row range
 9499            if end_row.0 <= buffer.max_point().row {
 9500                let range_to_move =
 9501                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9502                let insertion_point = display_map
 9503                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9504                    .0;
 9505
 9506                // Don't move lines across excerpt boundaries
 9507                if buffer
 9508                    .excerpt_containing(range_to_move.start..insertion_point)
 9509                    .is_some()
 9510                {
 9511                    let mut text = String::from("\n");
 9512                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9513                    text.pop(); // Drop trailing newline
 9514                    edits.push((
 9515                        buffer.anchor_after(range_to_move.start)
 9516                            ..buffer.anchor_before(range_to_move.end),
 9517                        String::new(),
 9518                    ));
 9519                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9520                    edits.push((insertion_anchor..insertion_anchor, text));
 9521
 9522                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9523
 9524                    // Move selections down
 9525                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9526                        |mut selection| {
 9527                            selection.start.row += row_delta;
 9528                            selection.end.row += row_delta;
 9529                            selection
 9530                        },
 9531                    ));
 9532
 9533                    // Move folds down
 9534                    unfold_ranges.push(range_to_move.clone());
 9535                    for fold in display_map.folds_in_range(
 9536                        buffer.anchor_before(range_to_move.start)
 9537                            ..buffer.anchor_after(range_to_move.end),
 9538                    ) {
 9539                        let mut start = fold.range.start.to_point(&buffer);
 9540                        let mut end = fold.range.end.to_point(&buffer);
 9541                        start.row += row_delta;
 9542                        end.row += row_delta;
 9543                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9544                    }
 9545                }
 9546            }
 9547
 9548            // If we didn't move line(s), preserve the existing selections
 9549            new_selections.append(&mut contiguous_row_selections);
 9550        }
 9551
 9552        self.transact(window, cx, |this, window, cx| {
 9553            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9554            this.buffer.update(cx, |buffer, cx| {
 9555                for (range, text) in edits {
 9556                    buffer.edit([(range, text)], None, cx);
 9557                }
 9558            });
 9559            this.fold_creases(refold_creases, true, window, cx);
 9560            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9561                s.select(new_selections)
 9562            });
 9563        });
 9564    }
 9565
 9566    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9567        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9568        let text_layout_details = &self.text_layout_details(window);
 9569        self.transact(window, cx, |this, window, cx| {
 9570            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9571                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9572                s.move_with(|display_map, selection| {
 9573                    if !selection.is_empty() {
 9574                        return;
 9575                    }
 9576
 9577                    let mut head = selection.head();
 9578                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9579                    if head.column() == display_map.line_len(head.row()) {
 9580                        transpose_offset = display_map
 9581                            .buffer_snapshot
 9582                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9583                    }
 9584
 9585                    if transpose_offset == 0 {
 9586                        return;
 9587                    }
 9588
 9589                    *head.column_mut() += 1;
 9590                    head = display_map.clip_point(head, Bias::Right);
 9591                    let goal = SelectionGoal::HorizontalPosition(
 9592                        display_map
 9593                            .x_for_display_point(head, text_layout_details)
 9594                            .into(),
 9595                    );
 9596                    selection.collapse_to(head, goal);
 9597
 9598                    let transpose_start = display_map
 9599                        .buffer_snapshot
 9600                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9601                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9602                        let transpose_end = display_map
 9603                            .buffer_snapshot
 9604                            .clip_offset(transpose_offset + 1, Bias::Right);
 9605                        if let Some(ch) =
 9606                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9607                        {
 9608                            edits.push((transpose_start..transpose_offset, String::new()));
 9609                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9610                        }
 9611                    }
 9612                });
 9613                edits
 9614            });
 9615            this.buffer
 9616                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9617            let selections = this.selections.all::<usize>(cx);
 9618            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9619                s.select(selections);
 9620            });
 9621        });
 9622    }
 9623
 9624    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9625        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9626        self.rewrap_impl(RewrapOptions::default(), cx)
 9627    }
 9628
 9629    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9630        let buffer = self.buffer.read(cx).snapshot(cx);
 9631        let selections = self.selections.all::<Point>(cx);
 9632        let mut selections = selections.iter().peekable();
 9633
 9634        let mut edits = Vec::new();
 9635        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9636
 9637        while let Some(selection) = selections.next() {
 9638            let mut start_row = selection.start.row;
 9639            let mut end_row = selection.end.row;
 9640
 9641            // Skip selections that overlap with a range that has already been rewrapped.
 9642            let selection_range = start_row..end_row;
 9643            if rewrapped_row_ranges
 9644                .iter()
 9645                .any(|range| range.overlaps(&selection_range))
 9646            {
 9647                continue;
 9648            }
 9649
 9650            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9651
 9652            // Since not all lines in the selection may be at the same indent
 9653            // level, choose the indent size that is the most common between all
 9654            // of the lines.
 9655            //
 9656            // If there is a tie, we use the deepest indent.
 9657            let (indent_size, indent_end) = {
 9658                let mut indent_size_occurrences = HashMap::default();
 9659                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9660
 9661                for row in start_row..=end_row {
 9662                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9663                    rows_by_indent_size.entry(indent).or_default().push(row);
 9664                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9665                }
 9666
 9667                let indent_size = indent_size_occurrences
 9668                    .into_iter()
 9669                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9670                    .map(|(indent, _)| indent)
 9671                    .unwrap_or_default();
 9672                let row = rows_by_indent_size[&indent_size][0];
 9673                let indent_end = Point::new(row, indent_size.len);
 9674
 9675                (indent_size, indent_end)
 9676            };
 9677
 9678            let mut line_prefix = indent_size.chars().collect::<String>();
 9679
 9680            let mut inside_comment = false;
 9681            if let Some(comment_prefix) =
 9682                buffer
 9683                    .language_scope_at(selection.head())
 9684                    .and_then(|language| {
 9685                        language
 9686                            .line_comment_prefixes()
 9687                            .iter()
 9688                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9689                            .cloned()
 9690                    })
 9691            {
 9692                line_prefix.push_str(&comment_prefix);
 9693                inside_comment = true;
 9694            }
 9695
 9696            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9697            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9698                RewrapBehavior::InComments => inside_comment,
 9699                RewrapBehavior::InSelections => !selection.is_empty(),
 9700                RewrapBehavior::Anywhere => true,
 9701            };
 9702
 9703            let should_rewrap = options.override_language_settings
 9704                || allow_rewrap_based_on_language
 9705                || self.hard_wrap.is_some();
 9706            if !should_rewrap {
 9707                continue;
 9708            }
 9709
 9710            if selection.is_empty() {
 9711                'expand_upwards: while start_row > 0 {
 9712                    let prev_row = start_row - 1;
 9713                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9714                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9715                    {
 9716                        start_row = prev_row;
 9717                    } else {
 9718                        break 'expand_upwards;
 9719                    }
 9720                }
 9721
 9722                'expand_downwards: while end_row < buffer.max_point().row {
 9723                    let next_row = end_row + 1;
 9724                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9725                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9726                    {
 9727                        end_row = next_row;
 9728                    } else {
 9729                        break 'expand_downwards;
 9730                    }
 9731                }
 9732            }
 9733
 9734            let start = Point::new(start_row, 0);
 9735            let start_offset = start.to_offset(&buffer);
 9736            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9737            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9738            let Some(lines_without_prefixes) = selection_text
 9739                .lines()
 9740                .map(|line| {
 9741                    line.strip_prefix(&line_prefix)
 9742                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9743                        .ok_or_else(|| {
 9744                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9745                        })
 9746                })
 9747                .collect::<Result<Vec<_>, _>>()
 9748                .log_err()
 9749            else {
 9750                continue;
 9751            };
 9752
 9753            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9754                buffer
 9755                    .language_settings_at(Point::new(start_row, 0), cx)
 9756                    .preferred_line_length as usize
 9757            });
 9758            let wrapped_text = wrap_with_prefix(
 9759                line_prefix,
 9760                lines_without_prefixes.join("\n"),
 9761                wrap_column,
 9762                tab_size,
 9763                options.preserve_existing_whitespace,
 9764            );
 9765
 9766            // TODO: should always use char-based diff while still supporting cursor behavior that
 9767            // matches vim.
 9768            let mut diff_options = DiffOptions::default();
 9769            if options.override_language_settings {
 9770                diff_options.max_word_diff_len = 0;
 9771                diff_options.max_word_diff_line_count = 0;
 9772            } else {
 9773                diff_options.max_word_diff_len = usize::MAX;
 9774                diff_options.max_word_diff_line_count = usize::MAX;
 9775            }
 9776
 9777            for (old_range, new_text) in
 9778                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 9779            {
 9780                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 9781                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 9782                edits.push((edit_start..edit_end, new_text));
 9783            }
 9784
 9785            rewrapped_row_ranges.push(start_row..=end_row);
 9786        }
 9787
 9788        self.buffer
 9789            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9790    }
 9791
 9792    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 9793        let mut text = String::new();
 9794        let buffer = self.buffer.read(cx).snapshot(cx);
 9795        let mut selections = self.selections.all::<Point>(cx);
 9796        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9797        {
 9798            let max_point = buffer.max_point();
 9799            let mut is_first = true;
 9800            for selection in &mut selections {
 9801                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9802                if is_entire_line {
 9803                    selection.start = Point::new(selection.start.row, 0);
 9804                    if !selection.is_empty() && selection.end.column == 0 {
 9805                        selection.end = cmp::min(max_point, selection.end);
 9806                    } else {
 9807                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 9808                    }
 9809                    selection.goal = SelectionGoal::None;
 9810                }
 9811                if is_first {
 9812                    is_first = false;
 9813                } else {
 9814                    text += "\n";
 9815                }
 9816                let mut len = 0;
 9817                for chunk in buffer.text_for_range(selection.start..selection.end) {
 9818                    text.push_str(chunk);
 9819                    len += chunk.len();
 9820                }
 9821                clipboard_selections.push(ClipboardSelection {
 9822                    len,
 9823                    is_entire_line,
 9824                    first_line_indent: buffer
 9825                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 9826                        .len,
 9827                });
 9828            }
 9829        }
 9830
 9831        self.transact(window, cx, |this, window, cx| {
 9832            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9833                s.select(selections);
 9834            });
 9835            this.insert("", window, cx);
 9836        });
 9837        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 9838    }
 9839
 9840    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 9841        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9842        let item = self.cut_common(window, cx);
 9843        cx.write_to_clipboard(item);
 9844    }
 9845
 9846    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 9847        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9848        self.change_selections(None, window, cx, |s| {
 9849            s.move_with(|snapshot, sel| {
 9850                if sel.is_empty() {
 9851                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 9852                }
 9853            });
 9854        });
 9855        let item = self.cut_common(window, cx);
 9856        cx.set_global(KillRing(item))
 9857    }
 9858
 9859    pub fn kill_ring_yank(
 9860        &mut self,
 9861        _: &KillRingYank,
 9862        window: &mut Window,
 9863        cx: &mut Context<Self>,
 9864    ) {
 9865        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9866        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 9867            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 9868                (kill_ring.text().to_string(), kill_ring.metadata_json())
 9869            } else {
 9870                return;
 9871            }
 9872        } else {
 9873            return;
 9874        };
 9875        self.do_paste(&text, metadata, false, window, cx);
 9876    }
 9877
 9878    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
 9879        self.do_copy(true, cx);
 9880    }
 9881
 9882    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 9883        self.do_copy(false, cx);
 9884    }
 9885
 9886    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
 9887        let selections = self.selections.all::<Point>(cx);
 9888        let buffer = self.buffer.read(cx).read(cx);
 9889        let mut text = String::new();
 9890
 9891        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9892        {
 9893            let max_point = buffer.max_point();
 9894            let mut is_first = true;
 9895            for selection in &selections {
 9896                let mut start = selection.start;
 9897                let mut end = selection.end;
 9898                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9899                if is_entire_line {
 9900                    start = Point::new(start.row, 0);
 9901                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 9902                }
 9903
 9904                let mut trimmed_selections = Vec::new();
 9905                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
 9906                    let row = MultiBufferRow(start.row);
 9907                    let first_indent = buffer.indent_size_for_line(row);
 9908                    if first_indent.len == 0 || start.column > first_indent.len {
 9909                        trimmed_selections.push(start..end);
 9910                    } else {
 9911                        trimmed_selections.push(
 9912                            Point::new(row.0, first_indent.len)
 9913                                ..Point::new(row.0, buffer.line_len(row)),
 9914                        );
 9915                        for row in start.row + 1..=end.row {
 9916                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
 9917                            if row_indent_size.len >= first_indent.len {
 9918                                trimmed_selections.push(
 9919                                    Point::new(row, first_indent.len)
 9920                                        ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
 9921                                );
 9922                            } else {
 9923                                trimmed_selections.clear();
 9924                                trimmed_selections.push(start..end);
 9925                                break;
 9926                            }
 9927                        }
 9928                    }
 9929                } else {
 9930                    trimmed_selections.push(start..end);
 9931                }
 9932
 9933                for trimmed_range in trimmed_selections {
 9934                    if is_first {
 9935                        is_first = false;
 9936                    } else {
 9937                        text += "\n";
 9938                    }
 9939                    let mut len = 0;
 9940                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
 9941                        text.push_str(chunk);
 9942                        len += chunk.len();
 9943                    }
 9944                    clipboard_selections.push(ClipboardSelection {
 9945                        len,
 9946                        is_entire_line,
 9947                        first_line_indent: buffer
 9948                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
 9949                            .len,
 9950                    });
 9951                }
 9952            }
 9953        }
 9954
 9955        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 9956            text,
 9957            clipboard_selections,
 9958        ));
 9959    }
 9960
 9961    pub fn do_paste(
 9962        &mut self,
 9963        text: &String,
 9964        clipboard_selections: Option<Vec<ClipboardSelection>>,
 9965        handle_entire_lines: bool,
 9966        window: &mut Window,
 9967        cx: &mut Context<Self>,
 9968    ) {
 9969        if self.read_only(cx) {
 9970            return;
 9971        }
 9972
 9973        let clipboard_text = Cow::Borrowed(text);
 9974
 9975        self.transact(window, cx, |this, window, cx| {
 9976            if let Some(mut clipboard_selections) = clipboard_selections {
 9977                let old_selections = this.selections.all::<usize>(cx);
 9978                let all_selections_were_entire_line =
 9979                    clipboard_selections.iter().all(|s| s.is_entire_line);
 9980                let first_selection_indent_column =
 9981                    clipboard_selections.first().map(|s| s.first_line_indent);
 9982                if clipboard_selections.len() != old_selections.len() {
 9983                    clipboard_selections.drain(..);
 9984                }
 9985                let cursor_offset = this.selections.last::<usize>(cx).head();
 9986                let mut auto_indent_on_paste = true;
 9987
 9988                this.buffer.update(cx, |buffer, cx| {
 9989                    let snapshot = buffer.read(cx);
 9990                    auto_indent_on_paste = snapshot
 9991                        .language_settings_at(cursor_offset, cx)
 9992                        .auto_indent_on_paste;
 9993
 9994                    let mut start_offset = 0;
 9995                    let mut edits = Vec::new();
 9996                    let mut original_indent_columns = Vec::new();
 9997                    for (ix, selection) in old_selections.iter().enumerate() {
 9998                        let to_insert;
 9999                        let entire_line;
10000                        let original_indent_column;
10001                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10002                            let end_offset = start_offset + clipboard_selection.len;
10003                            to_insert = &clipboard_text[start_offset..end_offset];
10004                            entire_line = clipboard_selection.is_entire_line;
10005                            start_offset = end_offset + 1;
10006                            original_indent_column = Some(clipboard_selection.first_line_indent);
10007                        } else {
10008                            to_insert = clipboard_text.as_str();
10009                            entire_line = all_selections_were_entire_line;
10010                            original_indent_column = first_selection_indent_column
10011                        }
10012
10013                        // If the corresponding selection was empty when this slice of the
10014                        // clipboard text was written, then the entire line containing the
10015                        // selection was copied. If this selection is also currently empty,
10016                        // then paste the line before the current line of the buffer.
10017                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10018                            let column = selection.start.to_point(&snapshot).column as usize;
10019                            let line_start = selection.start - column;
10020                            line_start..line_start
10021                        } else {
10022                            selection.range()
10023                        };
10024
10025                        edits.push((range, to_insert));
10026                        original_indent_columns.push(original_indent_column);
10027                    }
10028                    drop(snapshot);
10029
10030                    buffer.edit(
10031                        edits,
10032                        if auto_indent_on_paste {
10033                            Some(AutoindentMode::Block {
10034                                original_indent_columns,
10035                            })
10036                        } else {
10037                            None
10038                        },
10039                        cx,
10040                    );
10041                });
10042
10043                let selections = this.selections.all::<usize>(cx);
10044                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10045                    s.select(selections)
10046                });
10047            } else {
10048                this.insert(&clipboard_text, window, cx);
10049            }
10050        });
10051    }
10052
10053    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10054        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10055        if let Some(item) = cx.read_from_clipboard() {
10056            let entries = item.entries();
10057
10058            match entries.first() {
10059                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10060                // of all the pasted entries.
10061                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10062                    .do_paste(
10063                        clipboard_string.text(),
10064                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10065                        true,
10066                        window,
10067                        cx,
10068                    ),
10069                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10070            }
10071        }
10072    }
10073
10074    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10075        if self.read_only(cx) {
10076            return;
10077        }
10078
10079        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10080
10081        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10082            if let Some((selections, _)) =
10083                self.selection_history.transaction(transaction_id).cloned()
10084            {
10085                self.change_selections(None, window, cx, |s| {
10086                    s.select_anchors(selections.to_vec());
10087                });
10088            } else {
10089                log::error!(
10090                    "No entry in selection_history found for undo. \
10091                     This may correspond to a bug where undo does not update the selection. \
10092                     If this is occurring, please add details to \
10093                     https://github.com/zed-industries/zed/issues/22692"
10094                );
10095            }
10096            self.request_autoscroll(Autoscroll::fit(), cx);
10097            self.unmark_text(window, cx);
10098            self.refresh_inline_completion(true, false, window, cx);
10099            cx.emit(EditorEvent::Edited { transaction_id });
10100            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10101        }
10102    }
10103
10104    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10105        if self.read_only(cx) {
10106            return;
10107        }
10108
10109        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10110
10111        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10112            if let Some((_, Some(selections))) =
10113                self.selection_history.transaction(transaction_id).cloned()
10114            {
10115                self.change_selections(None, window, cx, |s| {
10116                    s.select_anchors(selections.to_vec());
10117                });
10118            } else {
10119                log::error!(
10120                    "No entry in selection_history found for redo. \
10121                     This may correspond to a bug where undo does not update the selection. \
10122                     If this is occurring, please add details to \
10123                     https://github.com/zed-industries/zed/issues/22692"
10124                );
10125            }
10126            self.request_autoscroll(Autoscroll::fit(), cx);
10127            self.unmark_text(window, cx);
10128            self.refresh_inline_completion(true, false, window, cx);
10129            cx.emit(EditorEvent::Edited { transaction_id });
10130        }
10131    }
10132
10133    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10134        self.buffer
10135            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10136    }
10137
10138    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10139        self.buffer
10140            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10141    }
10142
10143    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10144        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10145        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10146            s.move_with(|map, selection| {
10147                let cursor = if selection.is_empty() {
10148                    movement::left(map, selection.start)
10149                } else {
10150                    selection.start
10151                };
10152                selection.collapse_to(cursor, SelectionGoal::None);
10153            });
10154        })
10155    }
10156
10157    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10158        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10159        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10160            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10161        })
10162    }
10163
10164    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10165        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10166        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10167            s.move_with(|map, selection| {
10168                let cursor = if selection.is_empty() {
10169                    movement::right(map, selection.end)
10170                } else {
10171                    selection.end
10172                };
10173                selection.collapse_to(cursor, SelectionGoal::None)
10174            });
10175        })
10176    }
10177
10178    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10179        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10180        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10181            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10182        })
10183    }
10184
10185    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10186        if self.take_rename(true, window, cx).is_some() {
10187            return;
10188        }
10189
10190        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10191            cx.propagate();
10192            return;
10193        }
10194
10195        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10196
10197        let text_layout_details = &self.text_layout_details(window);
10198        let selection_count = self.selections.count();
10199        let first_selection = self.selections.first_anchor();
10200
10201        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10202            s.move_with(|map, selection| {
10203                if !selection.is_empty() {
10204                    selection.goal = SelectionGoal::None;
10205                }
10206                let (cursor, goal) = movement::up(
10207                    map,
10208                    selection.start,
10209                    selection.goal,
10210                    false,
10211                    text_layout_details,
10212                );
10213                selection.collapse_to(cursor, goal);
10214            });
10215        });
10216
10217        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10218        {
10219            cx.propagate();
10220        }
10221    }
10222
10223    pub fn move_up_by_lines(
10224        &mut self,
10225        action: &MoveUpByLines,
10226        window: &mut Window,
10227        cx: &mut Context<Self>,
10228    ) {
10229        if self.take_rename(true, window, cx).is_some() {
10230            return;
10231        }
10232
10233        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10234            cx.propagate();
10235            return;
10236        }
10237
10238        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10239
10240        let text_layout_details = &self.text_layout_details(window);
10241
10242        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10243            s.move_with(|map, selection| {
10244                if !selection.is_empty() {
10245                    selection.goal = SelectionGoal::None;
10246                }
10247                let (cursor, goal) = movement::up_by_rows(
10248                    map,
10249                    selection.start,
10250                    action.lines,
10251                    selection.goal,
10252                    false,
10253                    text_layout_details,
10254                );
10255                selection.collapse_to(cursor, goal);
10256            });
10257        })
10258    }
10259
10260    pub fn move_down_by_lines(
10261        &mut self,
10262        action: &MoveDownByLines,
10263        window: &mut Window,
10264        cx: &mut Context<Self>,
10265    ) {
10266        if self.take_rename(true, window, cx).is_some() {
10267            return;
10268        }
10269
10270        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10271            cx.propagate();
10272            return;
10273        }
10274
10275        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10276
10277        let text_layout_details = &self.text_layout_details(window);
10278
10279        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10280            s.move_with(|map, selection| {
10281                if !selection.is_empty() {
10282                    selection.goal = SelectionGoal::None;
10283                }
10284                let (cursor, goal) = movement::down_by_rows(
10285                    map,
10286                    selection.start,
10287                    action.lines,
10288                    selection.goal,
10289                    false,
10290                    text_layout_details,
10291                );
10292                selection.collapse_to(cursor, goal);
10293            });
10294        })
10295    }
10296
10297    pub fn select_down_by_lines(
10298        &mut self,
10299        action: &SelectDownByLines,
10300        window: &mut Window,
10301        cx: &mut Context<Self>,
10302    ) {
10303        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10304        let text_layout_details = &self.text_layout_details(window);
10305        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10306            s.move_heads_with(|map, head, goal| {
10307                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10308            })
10309        })
10310    }
10311
10312    pub fn select_up_by_lines(
10313        &mut self,
10314        action: &SelectUpByLines,
10315        window: &mut Window,
10316        cx: &mut Context<Self>,
10317    ) {
10318        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10319        let text_layout_details = &self.text_layout_details(window);
10320        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10321            s.move_heads_with(|map, head, goal| {
10322                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10323            })
10324        })
10325    }
10326
10327    pub fn select_page_up(
10328        &mut self,
10329        _: &SelectPageUp,
10330        window: &mut Window,
10331        cx: &mut Context<Self>,
10332    ) {
10333        let Some(row_count) = self.visible_row_count() else {
10334            return;
10335        };
10336
10337        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10338
10339        let text_layout_details = &self.text_layout_details(window);
10340
10341        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10342            s.move_heads_with(|map, head, goal| {
10343                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10344            })
10345        })
10346    }
10347
10348    pub fn move_page_up(
10349        &mut self,
10350        action: &MovePageUp,
10351        window: &mut Window,
10352        cx: &mut Context<Self>,
10353    ) {
10354        if self.take_rename(true, window, cx).is_some() {
10355            return;
10356        }
10357
10358        if self
10359            .context_menu
10360            .borrow_mut()
10361            .as_mut()
10362            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10363            .unwrap_or(false)
10364        {
10365            return;
10366        }
10367
10368        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10369            cx.propagate();
10370            return;
10371        }
10372
10373        let Some(row_count) = self.visible_row_count() else {
10374            return;
10375        };
10376
10377        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10378
10379        let autoscroll = if action.center_cursor {
10380            Autoscroll::center()
10381        } else {
10382            Autoscroll::fit()
10383        };
10384
10385        let text_layout_details = &self.text_layout_details(window);
10386
10387        self.change_selections(Some(autoscroll), window, cx, |s| {
10388            s.move_with(|map, selection| {
10389                if !selection.is_empty() {
10390                    selection.goal = SelectionGoal::None;
10391                }
10392                let (cursor, goal) = movement::up_by_rows(
10393                    map,
10394                    selection.end,
10395                    row_count,
10396                    selection.goal,
10397                    false,
10398                    text_layout_details,
10399                );
10400                selection.collapse_to(cursor, goal);
10401            });
10402        });
10403    }
10404
10405    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10406        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10407        let text_layout_details = &self.text_layout_details(window);
10408        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10409            s.move_heads_with(|map, head, goal| {
10410                movement::up(map, head, goal, false, text_layout_details)
10411            })
10412        })
10413    }
10414
10415    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10416        self.take_rename(true, window, cx);
10417
10418        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10419            cx.propagate();
10420            return;
10421        }
10422
10423        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10424
10425        let text_layout_details = &self.text_layout_details(window);
10426        let selection_count = self.selections.count();
10427        let first_selection = self.selections.first_anchor();
10428
10429        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10430            s.move_with(|map, selection| {
10431                if !selection.is_empty() {
10432                    selection.goal = SelectionGoal::None;
10433                }
10434                let (cursor, goal) = movement::down(
10435                    map,
10436                    selection.end,
10437                    selection.goal,
10438                    false,
10439                    text_layout_details,
10440                );
10441                selection.collapse_to(cursor, goal);
10442            });
10443        });
10444
10445        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10446        {
10447            cx.propagate();
10448        }
10449    }
10450
10451    pub fn select_page_down(
10452        &mut self,
10453        _: &SelectPageDown,
10454        window: &mut Window,
10455        cx: &mut Context<Self>,
10456    ) {
10457        let Some(row_count) = self.visible_row_count() else {
10458            return;
10459        };
10460
10461        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10462
10463        let text_layout_details = &self.text_layout_details(window);
10464
10465        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10466            s.move_heads_with(|map, head, goal| {
10467                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10468            })
10469        })
10470    }
10471
10472    pub fn move_page_down(
10473        &mut self,
10474        action: &MovePageDown,
10475        window: &mut Window,
10476        cx: &mut Context<Self>,
10477    ) {
10478        if self.take_rename(true, window, cx).is_some() {
10479            return;
10480        }
10481
10482        if self
10483            .context_menu
10484            .borrow_mut()
10485            .as_mut()
10486            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10487            .unwrap_or(false)
10488        {
10489            return;
10490        }
10491
10492        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10493            cx.propagate();
10494            return;
10495        }
10496
10497        let Some(row_count) = self.visible_row_count() else {
10498            return;
10499        };
10500
10501        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10502
10503        let autoscroll = if action.center_cursor {
10504            Autoscroll::center()
10505        } else {
10506            Autoscroll::fit()
10507        };
10508
10509        let text_layout_details = &self.text_layout_details(window);
10510        self.change_selections(Some(autoscroll), window, cx, |s| {
10511            s.move_with(|map, selection| {
10512                if !selection.is_empty() {
10513                    selection.goal = SelectionGoal::None;
10514                }
10515                let (cursor, goal) = movement::down_by_rows(
10516                    map,
10517                    selection.end,
10518                    row_count,
10519                    selection.goal,
10520                    false,
10521                    text_layout_details,
10522                );
10523                selection.collapse_to(cursor, goal);
10524            });
10525        });
10526    }
10527
10528    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10529        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10530        let text_layout_details = &self.text_layout_details(window);
10531        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10532            s.move_heads_with(|map, head, goal| {
10533                movement::down(map, head, goal, false, text_layout_details)
10534            })
10535        });
10536    }
10537
10538    pub fn context_menu_first(
10539        &mut self,
10540        _: &ContextMenuFirst,
10541        _window: &mut Window,
10542        cx: &mut Context<Self>,
10543    ) {
10544        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10545            context_menu.select_first(self.completion_provider.as_deref(), cx);
10546        }
10547    }
10548
10549    pub fn context_menu_prev(
10550        &mut self,
10551        _: &ContextMenuPrevious,
10552        _window: &mut Window,
10553        cx: &mut Context<Self>,
10554    ) {
10555        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10556            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10557        }
10558    }
10559
10560    pub fn context_menu_next(
10561        &mut self,
10562        _: &ContextMenuNext,
10563        _window: &mut Window,
10564        cx: &mut Context<Self>,
10565    ) {
10566        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10567            context_menu.select_next(self.completion_provider.as_deref(), cx);
10568        }
10569    }
10570
10571    pub fn context_menu_last(
10572        &mut self,
10573        _: &ContextMenuLast,
10574        _window: &mut Window,
10575        cx: &mut Context<Self>,
10576    ) {
10577        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10578            context_menu.select_last(self.completion_provider.as_deref(), cx);
10579        }
10580    }
10581
10582    pub fn move_to_previous_word_start(
10583        &mut self,
10584        _: &MoveToPreviousWordStart,
10585        window: &mut Window,
10586        cx: &mut Context<Self>,
10587    ) {
10588        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10589        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10590            s.move_cursors_with(|map, head, _| {
10591                (
10592                    movement::previous_word_start(map, head),
10593                    SelectionGoal::None,
10594                )
10595            });
10596        })
10597    }
10598
10599    pub fn move_to_previous_subword_start(
10600        &mut self,
10601        _: &MoveToPreviousSubwordStart,
10602        window: &mut Window,
10603        cx: &mut Context<Self>,
10604    ) {
10605        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10606        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10607            s.move_cursors_with(|map, head, _| {
10608                (
10609                    movement::previous_subword_start(map, head),
10610                    SelectionGoal::None,
10611                )
10612            });
10613        })
10614    }
10615
10616    pub fn select_to_previous_word_start(
10617        &mut self,
10618        _: &SelectToPreviousWordStart,
10619        window: &mut Window,
10620        cx: &mut Context<Self>,
10621    ) {
10622        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10623        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10624            s.move_heads_with(|map, head, _| {
10625                (
10626                    movement::previous_word_start(map, head),
10627                    SelectionGoal::None,
10628                )
10629            });
10630        })
10631    }
10632
10633    pub fn select_to_previous_subword_start(
10634        &mut self,
10635        _: &SelectToPreviousSubwordStart,
10636        window: &mut Window,
10637        cx: &mut Context<Self>,
10638    ) {
10639        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10640        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10641            s.move_heads_with(|map, head, _| {
10642                (
10643                    movement::previous_subword_start(map, head),
10644                    SelectionGoal::None,
10645                )
10646            });
10647        })
10648    }
10649
10650    pub fn delete_to_previous_word_start(
10651        &mut self,
10652        action: &DeleteToPreviousWordStart,
10653        window: &mut Window,
10654        cx: &mut Context<Self>,
10655    ) {
10656        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10657        self.transact(window, cx, |this, window, cx| {
10658            this.select_autoclose_pair(window, cx);
10659            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10660                s.move_with(|map, selection| {
10661                    if selection.is_empty() {
10662                        let cursor = if action.ignore_newlines {
10663                            movement::previous_word_start(map, selection.head())
10664                        } else {
10665                            movement::previous_word_start_or_newline(map, selection.head())
10666                        };
10667                        selection.set_head(cursor, SelectionGoal::None);
10668                    }
10669                });
10670            });
10671            this.insert("", window, cx);
10672        });
10673    }
10674
10675    pub fn delete_to_previous_subword_start(
10676        &mut self,
10677        _: &DeleteToPreviousSubwordStart,
10678        window: &mut Window,
10679        cx: &mut Context<Self>,
10680    ) {
10681        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10682        self.transact(window, cx, |this, window, cx| {
10683            this.select_autoclose_pair(window, cx);
10684            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10685                s.move_with(|map, selection| {
10686                    if selection.is_empty() {
10687                        let cursor = movement::previous_subword_start(map, selection.head());
10688                        selection.set_head(cursor, SelectionGoal::None);
10689                    }
10690                });
10691            });
10692            this.insert("", window, cx);
10693        });
10694    }
10695
10696    pub fn move_to_next_word_end(
10697        &mut self,
10698        _: &MoveToNextWordEnd,
10699        window: &mut Window,
10700        cx: &mut Context<Self>,
10701    ) {
10702        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10703        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10704            s.move_cursors_with(|map, head, _| {
10705                (movement::next_word_end(map, head), SelectionGoal::None)
10706            });
10707        })
10708    }
10709
10710    pub fn move_to_next_subword_end(
10711        &mut self,
10712        _: &MoveToNextSubwordEnd,
10713        window: &mut Window,
10714        cx: &mut Context<Self>,
10715    ) {
10716        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10717        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10718            s.move_cursors_with(|map, head, _| {
10719                (movement::next_subword_end(map, head), SelectionGoal::None)
10720            });
10721        })
10722    }
10723
10724    pub fn select_to_next_word_end(
10725        &mut self,
10726        _: &SelectToNextWordEnd,
10727        window: &mut Window,
10728        cx: &mut Context<Self>,
10729    ) {
10730        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10731        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10732            s.move_heads_with(|map, head, _| {
10733                (movement::next_word_end(map, head), SelectionGoal::None)
10734            });
10735        })
10736    }
10737
10738    pub fn select_to_next_subword_end(
10739        &mut self,
10740        _: &SelectToNextSubwordEnd,
10741        window: &mut Window,
10742        cx: &mut Context<Self>,
10743    ) {
10744        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10745        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10746            s.move_heads_with(|map, head, _| {
10747                (movement::next_subword_end(map, head), SelectionGoal::None)
10748            });
10749        })
10750    }
10751
10752    pub fn delete_to_next_word_end(
10753        &mut self,
10754        action: &DeleteToNextWordEnd,
10755        window: &mut Window,
10756        cx: &mut Context<Self>,
10757    ) {
10758        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10759        self.transact(window, cx, |this, window, cx| {
10760            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10761                s.move_with(|map, selection| {
10762                    if selection.is_empty() {
10763                        let cursor = if action.ignore_newlines {
10764                            movement::next_word_end(map, selection.head())
10765                        } else {
10766                            movement::next_word_end_or_newline(map, selection.head())
10767                        };
10768                        selection.set_head(cursor, SelectionGoal::None);
10769                    }
10770                });
10771            });
10772            this.insert("", window, cx);
10773        });
10774    }
10775
10776    pub fn delete_to_next_subword_end(
10777        &mut self,
10778        _: &DeleteToNextSubwordEnd,
10779        window: &mut Window,
10780        cx: &mut Context<Self>,
10781    ) {
10782        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10783        self.transact(window, cx, |this, window, cx| {
10784            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10785                s.move_with(|map, selection| {
10786                    if selection.is_empty() {
10787                        let cursor = movement::next_subword_end(map, selection.head());
10788                        selection.set_head(cursor, SelectionGoal::None);
10789                    }
10790                });
10791            });
10792            this.insert("", window, cx);
10793        });
10794    }
10795
10796    pub fn move_to_beginning_of_line(
10797        &mut self,
10798        action: &MoveToBeginningOfLine,
10799        window: &mut Window,
10800        cx: &mut Context<Self>,
10801    ) {
10802        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10803        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10804            s.move_cursors_with(|map, head, _| {
10805                (
10806                    movement::indented_line_beginning(
10807                        map,
10808                        head,
10809                        action.stop_at_soft_wraps,
10810                        action.stop_at_indent,
10811                    ),
10812                    SelectionGoal::None,
10813                )
10814            });
10815        })
10816    }
10817
10818    pub fn select_to_beginning_of_line(
10819        &mut self,
10820        action: &SelectToBeginningOfLine,
10821        window: &mut Window,
10822        cx: &mut Context<Self>,
10823    ) {
10824        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10825        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10826            s.move_heads_with(|map, head, _| {
10827                (
10828                    movement::indented_line_beginning(
10829                        map,
10830                        head,
10831                        action.stop_at_soft_wraps,
10832                        action.stop_at_indent,
10833                    ),
10834                    SelectionGoal::None,
10835                )
10836            });
10837        });
10838    }
10839
10840    pub fn delete_to_beginning_of_line(
10841        &mut self,
10842        action: &DeleteToBeginningOfLine,
10843        window: &mut Window,
10844        cx: &mut Context<Self>,
10845    ) {
10846        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10847        self.transact(window, cx, |this, window, cx| {
10848            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10849                s.move_with(|_, selection| {
10850                    selection.reversed = true;
10851                });
10852            });
10853
10854            this.select_to_beginning_of_line(
10855                &SelectToBeginningOfLine {
10856                    stop_at_soft_wraps: false,
10857                    stop_at_indent: action.stop_at_indent,
10858                },
10859                window,
10860                cx,
10861            );
10862            this.backspace(&Backspace, window, cx);
10863        });
10864    }
10865
10866    pub fn move_to_end_of_line(
10867        &mut self,
10868        action: &MoveToEndOfLine,
10869        window: &mut Window,
10870        cx: &mut Context<Self>,
10871    ) {
10872        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10873        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10874            s.move_cursors_with(|map, head, _| {
10875                (
10876                    movement::line_end(map, head, action.stop_at_soft_wraps),
10877                    SelectionGoal::None,
10878                )
10879            });
10880        })
10881    }
10882
10883    pub fn select_to_end_of_line(
10884        &mut self,
10885        action: &SelectToEndOfLine,
10886        window: &mut Window,
10887        cx: &mut Context<Self>,
10888    ) {
10889        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10890        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10891            s.move_heads_with(|map, head, _| {
10892                (
10893                    movement::line_end(map, head, action.stop_at_soft_wraps),
10894                    SelectionGoal::None,
10895                )
10896            });
10897        })
10898    }
10899
10900    pub fn delete_to_end_of_line(
10901        &mut self,
10902        _: &DeleteToEndOfLine,
10903        window: &mut Window,
10904        cx: &mut Context<Self>,
10905    ) {
10906        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10907        self.transact(window, cx, |this, window, cx| {
10908            this.select_to_end_of_line(
10909                &SelectToEndOfLine {
10910                    stop_at_soft_wraps: false,
10911                },
10912                window,
10913                cx,
10914            );
10915            this.delete(&Delete, window, cx);
10916        });
10917    }
10918
10919    pub fn cut_to_end_of_line(
10920        &mut self,
10921        _: &CutToEndOfLine,
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.select_to_end_of_line(
10928                &SelectToEndOfLine {
10929                    stop_at_soft_wraps: false,
10930                },
10931                window,
10932                cx,
10933            );
10934            this.cut(&Cut, window, cx);
10935        });
10936    }
10937
10938    pub fn move_to_start_of_paragraph(
10939        &mut self,
10940        _: &MoveToStartOfParagraph,
10941        window: &mut Window,
10942        cx: &mut Context<Self>,
10943    ) {
10944        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10945            cx.propagate();
10946            return;
10947        }
10948        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10949        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10950            s.move_with(|map, selection| {
10951                selection.collapse_to(
10952                    movement::start_of_paragraph(map, selection.head(), 1),
10953                    SelectionGoal::None,
10954                )
10955            });
10956        })
10957    }
10958
10959    pub fn move_to_end_of_paragraph(
10960        &mut self,
10961        _: &MoveToEndOfParagraph,
10962        window: &mut Window,
10963        cx: &mut Context<Self>,
10964    ) {
10965        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10966            cx.propagate();
10967            return;
10968        }
10969        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10970        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10971            s.move_with(|map, selection| {
10972                selection.collapse_to(
10973                    movement::end_of_paragraph(map, selection.head(), 1),
10974                    SelectionGoal::None,
10975                )
10976            });
10977        })
10978    }
10979
10980    pub fn select_to_start_of_paragraph(
10981        &mut self,
10982        _: &SelectToStartOfParagraph,
10983        window: &mut Window,
10984        cx: &mut Context<Self>,
10985    ) {
10986        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10987            cx.propagate();
10988            return;
10989        }
10990        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10991        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10992            s.move_heads_with(|map, head, _| {
10993                (
10994                    movement::start_of_paragraph(map, head, 1),
10995                    SelectionGoal::None,
10996                )
10997            });
10998        })
10999    }
11000
11001    pub fn select_to_end_of_paragraph(
11002        &mut self,
11003        _: &SelectToEndOfParagraph,
11004        window: &mut Window,
11005        cx: &mut Context<Self>,
11006    ) {
11007        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11008            cx.propagate();
11009            return;
11010        }
11011        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11012        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11013            s.move_heads_with(|map, head, _| {
11014                (
11015                    movement::end_of_paragraph(map, head, 1),
11016                    SelectionGoal::None,
11017                )
11018            });
11019        })
11020    }
11021
11022    pub fn move_to_start_of_excerpt(
11023        &mut self,
11024        _: &MoveToStartOfExcerpt,
11025        window: &mut Window,
11026        cx: &mut Context<Self>,
11027    ) {
11028        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11029            cx.propagate();
11030            return;
11031        }
11032        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11033        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11034            s.move_with(|map, selection| {
11035                selection.collapse_to(
11036                    movement::start_of_excerpt(
11037                        map,
11038                        selection.head(),
11039                        workspace::searchable::Direction::Prev,
11040                    ),
11041                    SelectionGoal::None,
11042                )
11043            });
11044        })
11045    }
11046
11047    pub fn move_to_start_of_next_excerpt(
11048        &mut self,
11049        _: &MoveToStartOfNextExcerpt,
11050        window: &mut Window,
11051        cx: &mut Context<Self>,
11052    ) {
11053        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11054            cx.propagate();
11055            return;
11056        }
11057
11058        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11059            s.move_with(|map, selection| {
11060                selection.collapse_to(
11061                    movement::start_of_excerpt(
11062                        map,
11063                        selection.head(),
11064                        workspace::searchable::Direction::Next,
11065                    ),
11066                    SelectionGoal::None,
11067                )
11068            });
11069        })
11070    }
11071
11072    pub fn move_to_end_of_excerpt(
11073        &mut self,
11074        _: &MoveToEndOfExcerpt,
11075        window: &mut Window,
11076        cx: &mut Context<Self>,
11077    ) {
11078        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11079            cx.propagate();
11080            return;
11081        }
11082        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11083        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11084            s.move_with(|map, selection| {
11085                selection.collapse_to(
11086                    movement::end_of_excerpt(
11087                        map,
11088                        selection.head(),
11089                        workspace::searchable::Direction::Next,
11090                    ),
11091                    SelectionGoal::None,
11092                )
11093            });
11094        })
11095    }
11096
11097    pub fn move_to_end_of_previous_excerpt(
11098        &mut self,
11099        _: &MoveToEndOfPreviousExcerpt,
11100        window: &mut Window,
11101        cx: &mut Context<Self>,
11102    ) {
11103        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11104            cx.propagate();
11105            return;
11106        }
11107        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11108        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11109            s.move_with(|map, selection| {
11110                selection.collapse_to(
11111                    movement::end_of_excerpt(
11112                        map,
11113                        selection.head(),
11114                        workspace::searchable::Direction::Prev,
11115                    ),
11116                    SelectionGoal::None,
11117                )
11118            });
11119        })
11120    }
11121
11122    pub fn select_to_start_of_excerpt(
11123        &mut self,
11124        _: &SelectToStartOfExcerpt,
11125        window: &mut Window,
11126        cx: &mut Context<Self>,
11127    ) {
11128        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11129            cx.propagate();
11130            return;
11131        }
11132        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11133        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11134            s.move_heads_with(|map, head, _| {
11135                (
11136                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11137                    SelectionGoal::None,
11138                )
11139            });
11140        })
11141    }
11142
11143    pub fn select_to_start_of_next_excerpt(
11144        &mut self,
11145        _: &SelectToStartOfNextExcerpt,
11146        window: &mut Window,
11147        cx: &mut Context<Self>,
11148    ) {
11149        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11150            cx.propagate();
11151            return;
11152        }
11153        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11154        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11155            s.move_heads_with(|map, head, _| {
11156                (
11157                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11158                    SelectionGoal::None,
11159                )
11160            });
11161        })
11162    }
11163
11164    pub fn select_to_end_of_excerpt(
11165        &mut self,
11166        _: &SelectToEndOfExcerpt,
11167        window: &mut Window,
11168        cx: &mut Context<Self>,
11169    ) {
11170        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11171            cx.propagate();
11172            return;
11173        }
11174        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11175        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11176            s.move_heads_with(|map, head, _| {
11177                (
11178                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11179                    SelectionGoal::None,
11180                )
11181            });
11182        })
11183    }
11184
11185    pub fn select_to_end_of_previous_excerpt(
11186        &mut self,
11187        _: &SelectToEndOfPreviousExcerpt,
11188        window: &mut Window,
11189        cx: &mut Context<Self>,
11190    ) {
11191        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11192            cx.propagate();
11193            return;
11194        }
11195        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11196        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11197            s.move_heads_with(|map, head, _| {
11198                (
11199                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11200                    SelectionGoal::None,
11201                )
11202            });
11203        })
11204    }
11205
11206    pub fn move_to_beginning(
11207        &mut self,
11208        _: &MoveToBeginning,
11209        window: &mut Window,
11210        cx: &mut Context<Self>,
11211    ) {
11212        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11213            cx.propagate();
11214            return;
11215        }
11216        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11217        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11218            s.select_ranges(vec![0..0]);
11219        });
11220    }
11221
11222    pub fn select_to_beginning(
11223        &mut self,
11224        _: &SelectToBeginning,
11225        window: &mut Window,
11226        cx: &mut Context<Self>,
11227    ) {
11228        let mut selection = self.selections.last::<Point>(cx);
11229        selection.set_head(Point::zero(), SelectionGoal::None);
11230        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11231        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11232            s.select(vec![selection]);
11233        });
11234    }
11235
11236    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11237        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11238            cx.propagate();
11239            return;
11240        }
11241        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11242        let cursor = self.buffer.read(cx).read(cx).len();
11243        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11244            s.select_ranges(vec![cursor..cursor])
11245        });
11246    }
11247
11248    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11249        self.nav_history = nav_history;
11250    }
11251
11252    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11253        self.nav_history.as_ref()
11254    }
11255
11256    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11257        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11258    }
11259
11260    fn push_to_nav_history(
11261        &mut self,
11262        cursor_anchor: Anchor,
11263        new_position: Option<Point>,
11264        is_deactivate: bool,
11265        cx: &mut Context<Self>,
11266    ) {
11267        if let Some(nav_history) = self.nav_history.as_mut() {
11268            let buffer = self.buffer.read(cx).read(cx);
11269            let cursor_position = cursor_anchor.to_point(&buffer);
11270            let scroll_state = self.scroll_manager.anchor();
11271            let scroll_top_row = scroll_state.top_row(&buffer);
11272            drop(buffer);
11273
11274            if let Some(new_position) = new_position {
11275                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11276                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11277                    return;
11278                }
11279            }
11280
11281            nav_history.push(
11282                Some(NavigationData {
11283                    cursor_anchor,
11284                    cursor_position,
11285                    scroll_anchor: scroll_state,
11286                    scroll_top_row,
11287                }),
11288                cx,
11289            );
11290            cx.emit(EditorEvent::PushedToNavHistory {
11291                anchor: cursor_anchor,
11292                is_deactivate,
11293            })
11294        }
11295    }
11296
11297    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11298        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11299        let buffer = self.buffer.read(cx).snapshot(cx);
11300        let mut selection = self.selections.first::<usize>(cx);
11301        selection.set_head(buffer.len(), SelectionGoal::None);
11302        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11303            s.select(vec![selection]);
11304        });
11305    }
11306
11307    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11308        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11309        let end = self.buffer.read(cx).read(cx).len();
11310        self.change_selections(None, window, cx, |s| {
11311            s.select_ranges(vec![0..end]);
11312        });
11313    }
11314
11315    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11316        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11317        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11318        let mut selections = self.selections.all::<Point>(cx);
11319        let max_point = display_map.buffer_snapshot.max_point();
11320        for selection in &mut selections {
11321            let rows = selection.spanned_rows(true, &display_map);
11322            selection.start = Point::new(rows.start.0, 0);
11323            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11324            selection.reversed = false;
11325        }
11326        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11327            s.select(selections);
11328        });
11329    }
11330
11331    pub fn split_selection_into_lines(
11332        &mut self,
11333        _: &SplitSelectionIntoLines,
11334        window: &mut Window,
11335        cx: &mut Context<Self>,
11336    ) {
11337        let selections = self
11338            .selections
11339            .all::<Point>(cx)
11340            .into_iter()
11341            .map(|selection| selection.start..selection.end)
11342            .collect::<Vec<_>>();
11343        self.unfold_ranges(&selections, true, true, cx);
11344
11345        let mut new_selection_ranges = Vec::new();
11346        {
11347            let buffer = self.buffer.read(cx).read(cx);
11348            for selection in selections {
11349                for row in selection.start.row..selection.end.row {
11350                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11351                    new_selection_ranges.push(cursor..cursor);
11352                }
11353
11354                let is_multiline_selection = selection.start.row != selection.end.row;
11355                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11356                // so this action feels more ergonomic when paired with other selection operations
11357                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11358                if !should_skip_last {
11359                    new_selection_ranges.push(selection.end..selection.end);
11360                }
11361            }
11362        }
11363        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11364            s.select_ranges(new_selection_ranges);
11365        });
11366    }
11367
11368    pub fn add_selection_above(
11369        &mut self,
11370        _: &AddSelectionAbove,
11371        window: &mut Window,
11372        cx: &mut Context<Self>,
11373    ) {
11374        self.add_selection(true, window, cx);
11375    }
11376
11377    pub fn add_selection_below(
11378        &mut self,
11379        _: &AddSelectionBelow,
11380        window: &mut Window,
11381        cx: &mut Context<Self>,
11382    ) {
11383        self.add_selection(false, window, cx);
11384    }
11385
11386    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11387        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11388
11389        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11390        let mut selections = self.selections.all::<Point>(cx);
11391        let text_layout_details = self.text_layout_details(window);
11392        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11393            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11394            let range = oldest_selection.display_range(&display_map).sorted();
11395
11396            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11397            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11398            let positions = start_x.min(end_x)..start_x.max(end_x);
11399
11400            selections.clear();
11401            let mut stack = Vec::new();
11402            for row in range.start.row().0..=range.end.row().0 {
11403                if let Some(selection) = self.selections.build_columnar_selection(
11404                    &display_map,
11405                    DisplayRow(row),
11406                    &positions,
11407                    oldest_selection.reversed,
11408                    &text_layout_details,
11409                ) {
11410                    stack.push(selection.id);
11411                    selections.push(selection);
11412                }
11413            }
11414
11415            if above {
11416                stack.reverse();
11417            }
11418
11419            AddSelectionsState { above, stack }
11420        });
11421
11422        let last_added_selection = *state.stack.last().unwrap();
11423        let mut new_selections = Vec::new();
11424        if above == state.above {
11425            let end_row = if above {
11426                DisplayRow(0)
11427            } else {
11428                display_map.max_point().row()
11429            };
11430
11431            'outer: for selection in selections {
11432                if selection.id == last_added_selection {
11433                    let range = selection.display_range(&display_map).sorted();
11434                    debug_assert_eq!(range.start.row(), range.end.row());
11435                    let mut row = range.start.row();
11436                    let positions =
11437                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11438                            px(start)..px(end)
11439                        } else {
11440                            let start_x =
11441                                display_map.x_for_display_point(range.start, &text_layout_details);
11442                            let end_x =
11443                                display_map.x_for_display_point(range.end, &text_layout_details);
11444                            start_x.min(end_x)..start_x.max(end_x)
11445                        };
11446
11447                    while row != end_row {
11448                        if above {
11449                            row.0 -= 1;
11450                        } else {
11451                            row.0 += 1;
11452                        }
11453
11454                        if let Some(new_selection) = self.selections.build_columnar_selection(
11455                            &display_map,
11456                            row,
11457                            &positions,
11458                            selection.reversed,
11459                            &text_layout_details,
11460                        ) {
11461                            state.stack.push(new_selection.id);
11462                            if above {
11463                                new_selections.push(new_selection);
11464                                new_selections.push(selection);
11465                            } else {
11466                                new_selections.push(selection);
11467                                new_selections.push(new_selection);
11468                            }
11469
11470                            continue 'outer;
11471                        }
11472                    }
11473                }
11474
11475                new_selections.push(selection);
11476            }
11477        } else {
11478            new_selections = selections;
11479            new_selections.retain(|s| s.id != last_added_selection);
11480            state.stack.pop();
11481        }
11482
11483        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11484            s.select(new_selections);
11485        });
11486        if state.stack.len() > 1 {
11487            self.add_selections_state = Some(state);
11488        }
11489    }
11490
11491    pub fn select_next_match_internal(
11492        &mut self,
11493        display_map: &DisplaySnapshot,
11494        replace_newest: bool,
11495        autoscroll: Option<Autoscroll>,
11496        window: &mut Window,
11497        cx: &mut Context<Self>,
11498    ) -> Result<()> {
11499        fn select_next_match_ranges(
11500            this: &mut Editor,
11501            range: Range<usize>,
11502            replace_newest: bool,
11503            auto_scroll: Option<Autoscroll>,
11504            window: &mut Window,
11505            cx: &mut Context<Editor>,
11506        ) {
11507            this.unfold_ranges(&[range.clone()], false, true, cx);
11508            this.change_selections(auto_scroll, window, cx, |s| {
11509                if replace_newest {
11510                    s.delete(s.newest_anchor().id);
11511                }
11512                s.insert_range(range.clone());
11513            });
11514        }
11515
11516        let buffer = &display_map.buffer_snapshot;
11517        let mut selections = self.selections.all::<usize>(cx);
11518        if let Some(mut select_next_state) = self.select_next_state.take() {
11519            let query = &select_next_state.query;
11520            if !select_next_state.done {
11521                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11522                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11523                let mut next_selected_range = None;
11524
11525                let bytes_after_last_selection =
11526                    buffer.bytes_in_range(last_selection.end..buffer.len());
11527                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11528                let query_matches = query
11529                    .stream_find_iter(bytes_after_last_selection)
11530                    .map(|result| (last_selection.end, result))
11531                    .chain(
11532                        query
11533                            .stream_find_iter(bytes_before_first_selection)
11534                            .map(|result| (0, result)),
11535                    );
11536
11537                for (start_offset, query_match) in query_matches {
11538                    let query_match = query_match.unwrap(); // can only fail due to I/O
11539                    let offset_range =
11540                        start_offset + query_match.start()..start_offset + query_match.end();
11541                    let display_range = offset_range.start.to_display_point(display_map)
11542                        ..offset_range.end.to_display_point(display_map);
11543
11544                    if !select_next_state.wordwise
11545                        || (!movement::is_inside_word(display_map, display_range.start)
11546                            && !movement::is_inside_word(display_map, display_range.end))
11547                    {
11548                        // TODO: This is n^2, because we might check all the selections
11549                        if !selections
11550                            .iter()
11551                            .any(|selection| selection.range().overlaps(&offset_range))
11552                        {
11553                            next_selected_range = Some(offset_range);
11554                            break;
11555                        }
11556                    }
11557                }
11558
11559                if let Some(next_selected_range) = next_selected_range {
11560                    select_next_match_ranges(
11561                        self,
11562                        next_selected_range,
11563                        replace_newest,
11564                        autoscroll,
11565                        window,
11566                        cx,
11567                    );
11568                } else {
11569                    select_next_state.done = true;
11570                }
11571            }
11572
11573            self.select_next_state = Some(select_next_state);
11574        } else {
11575            let mut only_carets = true;
11576            let mut same_text_selected = true;
11577            let mut selected_text = None;
11578
11579            let mut selections_iter = selections.iter().peekable();
11580            while let Some(selection) = selections_iter.next() {
11581                if selection.start != selection.end {
11582                    only_carets = false;
11583                }
11584
11585                if same_text_selected {
11586                    if selected_text.is_none() {
11587                        selected_text =
11588                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11589                    }
11590
11591                    if let Some(next_selection) = selections_iter.peek() {
11592                        if next_selection.range().len() == selection.range().len() {
11593                            let next_selected_text = buffer
11594                                .text_for_range(next_selection.range())
11595                                .collect::<String>();
11596                            if Some(next_selected_text) != selected_text {
11597                                same_text_selected = false;
11598                                selected_text = None;
11599                            }
11600                        } else {
11601                            same_text_selected = false;
11602                            selected_text = None;
11603                        }
11604                    }
11605                }
11606            }
11607
11608            if only_carets {
11609                for selection in &mut selections {
11610                    let word_range = movement::surrounding_word(
11611                        display_map,
11612                        selection.start.to_display_point(display_map),
11613                    );
11614                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11615                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11616                    selection.goal = SelectionGoal::None;
11617                    selection.reversed = false;
11618                    select_next_match_ranges(
11619                        self,
11620                        selection.start..selection.end,
11621                        replace_newest,
11622                        autoscroll,
11623                        window,
11624                        cx,
11625                    );
11626                }
11627
11628                if selections.len() == 1 {
11629                    let selection = selections
11630                        .last()
11631                        .expect("ensured that there's only one selection");
11632                    let query = buffer
11633                        .text_for_range(selection.start..selection.end)
11634                        .collect::<String>();
11635                    let is_empty = query.is_empty();
11636                    let select_state = SelectNextState {
11637                        query: AhoCorasick::new(&[query])?,
11638                        wordwise: true,
11639                        done: is_empty,
11640                    };
11641                    self.select_next_state = Some(select_state);
11642                } else {
11643                    self.select_next_state = None;
11644                }
11645            } else if let Some(selected_text) = selected_text {
11646                self.select_next_state = Some(SelectNextState {
11647                    query: AhoCorasick::new(&[selected_text])?,
11648                    wordwise: false,
11649                    done: false,
11650                });
11651                self.select_next_match_internal(
11652                    display_map,
11653                    replace_newest,
11654                    autoscroll,
11655                    window,
11656                    cx,
11657                )?;
11658            }
11659        }
11660        Ok(())
11661    }
11662
11663    pub fn select_all_matches(
11664        &mut self,
11665        _action: &SelectAllMatches,
11666        window: &mut Window,
11667        cx: &mut Context<Self>,
11668    ) -> Result<()> {
11669        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11670
11671        self.push_to_selection_history();
11672        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11673
11674        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11675        let Some(select_next_state) = self.select_next_state.as_mut() else {
11676            return Ok(());
11677        };
11678        if select_next_state.done {
11679            return Ok(());
11680        }
11681
11682        let mut new_selections = self.selections.all::<usize>(cx);
11683
11684        let buffer = &display_map.buffer_snapshot;
11685        let query_matches = select_next_state
11686            .query
11687            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11688
11689        for query_match in query_matches {
11690            let query_match = query_match.unwrap(); // can only fail due to I/O
11691            let offset_range = query_match.start()..query_match.end();
11692            let display_range = offset_range.start.to_display_point(&display_map)
11693                ..offset_range.end.to_display_point(&display_map);
11694
11695            if !select_next_state.wordwise
11696                || (!movement::is_inside_word(&display_map, display_range.start)
11697                    && !movement::is_inside_word(&display_map, display_range.end))
11698            {
11699                self.selections.change_with(cx, |selections| {
11700                    new_selections.push(Selection {
11701                        id: selections.new_selection_id(),
11702                        start: offset_range.start,
11703                        end: offset_range.end,
11704                        reversed: false,
11705                        goal: SelectionGoal::None,
11706                    });
11707                });
11708            }
11709        }
11710
11711        new_selections.sort_by_key(|selection| selection.start);
11712        let mut ix = 0;
11713        while ix + 1 < new_selections.len() {
11714            let current_selection = &new_selections[ix];
11715            let next_selection = &new_selections[ix + 1];
11716            if current_selection.range().overlaps(&next_selection.range()) {
11717                if current_selection.id < next_selection.id {
11718                    new_selections.remove(ix + 1);
11719                } else {
11720                    new_selections.remove(ix);
11721                }
11722            } else {
11723                ix += 1;
11724            }
11725        }
11726
11727        let reversed = self.selections.oldest::<usize>(cx).reversed;
11728
11729        for selection in new_selections.iter_mut() {
11730            selection.reversed = reversed;
11731        }
11732
11733        select_next_state.done = true;
11734        self.unfold_ranges(
11735            &new_selections
11736                .iter()
11737                .map(|selection| selection.range())
11738                .collect::<Vec<_>>(),
11739            false,
11740            false,
11741            cx,
11742        );
11743        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11744            selections.select(new_selections)
11745        });
11746
11747        Ok(())
11748    }
11749
11750    pub fn select_next(
11751        &mut self,
11752        action: &SelectNext,
11753        window: &mut Window,
11754        cx: &mut Context<Self>,
11755    ) -> Result<()> {
11756        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11757        self.push_to_selection_history();
11758        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11759        self.select_next_match_internal(
11760            &display_map,
11761            action.replace_newest,
11762            Some(Autoscroll::newest()),
11763            window,
11764            cx,
11765        )?;
11766        Ok(())
11767    }
11768
11769    pub fn select_previous(
11770        &mut self,
11771        action: &SelectPrevious,
11772        window: &mut Window,
11773        cx: &mut Context<Self>,
11774    ) -> Result<()> {
11775        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11776        self.push_to_selection_history();
11777        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11778        let buffer = &display_map.buffer_snapshot;
11779        let mut selections = self.selections.all::<usize>(cx);
11780        if let Some(mut select_prev_state) = self.select_prev_state.take() {
11781            let query = &select_prev_state.query;
11782            if !select_prev_state.done {
11783                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11784                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11785                let mut next_selected_range = None;
11786                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11787                let bytes_before_last_selection =
11788                    buffer.reversed_bytes_in_range(0..last_selection.start);
11789                let bytes_after_first_selection =
11790                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11791                let query_matches = query
11792                    .stream_find_iter(bytes_before_last_selection)
11793                    .map(|result| (last_selection.start, result))
11794                    .chain(
11795                        query
11796                            .stream_find_iter(bytes_after_first_selection)
11797                            .map(|result| (buffer.len(), result)),
11798                    );
11799                for (end_offset, query_match) in query_matches {
11800                    let query_match = query_match.unwrap(); // can only fail due to I/O
11801                    let offset_range =
11802                        end_offset - query_match.end()..end_offset - query_match.start();
11803                    let display_range = offset_range.start.to_display_point(&display_map)
11804                        ..offset_range.end.to_display_point(&display_map);
11805
11806                    if !select_prev_state.wordwise
11807                        || (!movement::is_inside_word(&display_map, display_range.start)
11808                            && !movement::is_inside_word(&display_map, display_range.end))
11809                    {
11810                        next_selected_range = Some(offset_range);
11811                        break;
11812                    }
11813                }
11814
11815                if let Some(next_selected_range) = next_selected_range {
11816                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11817                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11818                        if action.replace_newest {
11819                            s.delete(s.newest_anchor().id);
11820                        }
11821                        s.insert_range(next_selected_range);
11822                    });
11823                } else {
11824                    select_prev_state.done = true;
11825                }
11826            }
11827
11828            self.select_prev_state = Some(select_prev_state);
11829        } else {
11830            let mut only_carets = true;
11831            let mut same_text_selected = true;
11832            let mut selected_text = None;
11833
11834            let mut selections_iter = selections.iter().peekable();
11835            while let Some(selection) = selections_iter.next() {
11836                if selection.start != selection.end {
11837                    only_carets = false;
11838                }
11839
11840                if same_text_selected {
11841                    if selected_text.is_none() {
11842                        selected_text =
11843                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11844                    }
11845
11846                    if let Some(next_selection) = selections_iter.peek() {
11847                        if next_selection.range().len() == selection.range().len() {
11848                            let next_selected_text = buffer
11849                                .text_for_range(next_selection.range())
11850                                .collect::<String>();
11851                            if Some(next_selected_text) != selected_text {
11852                                same_text_selected = false;
11853                                selected_text = None;
11854                            }
11855                        } else {
11856                            same_text_selected = false;
11857                            selected_text = None;
11858                        }
11859                    }
11860                }
11861            }
11862
11863            if only_carets {
11864                for selection in &mut selections {
11865                    let word_range = movement::surrounding_word(
11866                        &display_map,
11867                        selection.start.to_display_point(&display_map),
11868                    );
11869                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11870                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11871                    selection.goal = SelectionGoal::None;
11872                    selection.reversed = false;
11873                }
11874                if selections.len() == 1 {
11875                    let selection = selections
11876                        .last()
11877                        .expect("ensured that there's only one selection");
11878                    let query = buffer
11879                        .text_for_range(selection.start..selection.end)
11880                        .collect::<String>();
11881                    let is_empty = query.is_empty();
11882                    let select_state = SelectNextState {
11883                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11884                        wordwise: true,
11885                        done: is_empty,
11886                    };
11887                    self.select_prev_state = Some(select_state);
11888                } else {
11889                    self.select_prev_state = None;
11890                }
11891
11892                self.unfold_ranges(
11893                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11894                    false,
11895                    true,
11896                    cx,
11897                );
11898                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11899                    s.select(selections);
11900                });
11901            } else if let Some(selected_text) = selected_text {
11902                self.select_prev_state = Some(SelectNextState {
11903                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11904                    wordwise: false,
11905                    done: false,
11906                });
11907                self.select_previous(action, window, cx)?;
11908            }
11909        }
11910        Ok(())
11911    }
11912
11913    pub fn toggle_comments(
11914        &mut self,
11915        action: &ToggleComments,
11916        window: &mut Window,
11917        cx: &mut Context<Self>,
11918    ) {
11919        if self.read_only(cx) {
11920            return;
11921        }
11922        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11923        let text_layout_details = &self.text_layout_details(window);
11924        self.transact(window, cx, |this, window, cx| {
11925            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11926            let mut edits = Vec::new();
11927            let mut selection_edit_ranges = Vec::new();
11928            let mut last_toggled_row = None;
11929            let snapshot = this.buffer.read(cx).read(cx);
11930            let empty_str: Arc<str> = Arc::default();
11931            let mut suffixes_inserted = Vec::new();
11932            let ignore_indent = action.ignore_indent;
11933
11934            fn comment_prefix_range(
11935                snapshot: &MultiBufferSnapshot,
11936                row: MultiBufferRow,
11937                comment_prefix: &str,
11938                comment_prefix_whitespace: &str,
11939                ignore_indent: bool,
11940            ) -> Range<Point> {
11941                let indent_size = if ignore_indent {
11942                    0
11943                } else {
11944                    snapshot.indent_size_for_line(row).len
11945                };
11946
11947                let start = Point::new(row.0, indent_size);
11948
11949                let mut line_bytes = snapshot
11950                    .bytes_in_range(start..snapshot.max_point())
11951                    .flatten()
11952                    .copied();
11953
11954                // If this line currently begins with the line comment prefix, then record
11955                // the range containing the prefix.
11956                if line_bytes
11957                    .by_ref()
11958                    .take(comment_prefix.len())
11959                    .eq(comment_prefix.bytes())
11960                {
11961                    // Include any whitespace that matches the comment prefix.
11962                    let matching_whitespace_len = line_bytes
11963                        .zip(comment_prefix_whitespace.bytes())
11964                        .take_while(|(a, b)| a == b)
11965                        .count() as u32;
11966                    let end = Point::new(
11967                        start.row,
11968                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11969                    );
11970                    start..end
11971                } else {
11972                    start..start
11973                }
11974            }
11975
11976            fn comment_suffix_range(
11977                snapshot: &MultiBufferSnapshot,
11978                row: MultiBufferRow,
11979                comment_suffix: &str,
11980                comment_suffix_has_leading_space: bool,
11981            ) -> Range<Point> {
11982                let end = Point::new(row.0, snapshot.line_len(row));
11983                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11984
11985                let mut line_end_bytes = snapshot
11986                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11987                    .flatten()
11988                    .copied();
11989
11990                let leading_space_len = if suffix_start_column > 0
11991                    && line_end_bytes.next() == Some(b' ')
11992                    && comment_suffix_has_leading_space
11993                {
11994                    1
11995                } else {
11996                    0
11997                };
11998
11999                // If this line currently begins with the line comment prefix, then record
12000                // the range containing the prefix.
12001                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12002                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12003                    start..end
12004                } else {
12005                    end..end
12006                }
12007            }
12008
12009            // TODO: Handle selections that cross excerpts
12010            for selection in &mut selections {
12011                let start_column = snapshot
12012                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12013                    .len;
12014                let language = if let Some(language) =
12015                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12016                {
12017                    language
12018                } else {
12019                    continue;
12020                };
12021
12022                selection_edit_ranges.clear();
12023
12024                // If multiple selections contain a given row, avoid processing that
12025                // row more than once.
12026                let mut start_row = MultiBufferRow(selection.start.row);
12027                if last_toggled_row == Some(start_row) {
12028                    start_row = start_row.next_row();
12029                }
12030                let end_row =
12031                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12032                        MultiBufferRow(selection.end.row - 1)
12033                    } else {
12034                        MultiBufferRow(selection.end.row)
12035                    };
12036                last_toggled_row = Some(end_row);
12037
12038                if start_row > end_row {
12039                    continue;
12040                }
12041
12042                // If the language has line comments, toggle those.
12043                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12044
12045                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12046                if ignore_indent {
12047                    full_comment_prefixes = full_comment_prefixes
12048                        .into_iter()
12049                        .map(|s| Arc::from(s.trim_end()))
12050                        .collect();
12051                }
12052
12053                if !full_comment_prefixes.is_empty() {
12054                    let first_prefix = full_comment_prefixes
12055                        .first()
12056                        .expect("prefixes is non-empty");
12057                    let prefix_trimmed_lengths = full_comment_prefixes
12058                        .iter()
12059                        .map(|p| p.trim_end_matches(' ').len())
12060                        .collect::<SmallVec<[usize; 4]>>();
12061
12062                    let mut all_selection_lines_are_comments = true;
12063
12064                    for row in start_row.0..=end_row.0 {
12065                        let row = MultiBufferRow(row);
12066                        if start_row < end_row && snapshot.is_line_blank(row) {
12067                            continue;
12068                        }
12069
12070                        let prefix_range = full_comment_prefixes
12071                            .iter()
12072                            .zip(prefix_trimmed_lengths.iter().copied())
12073                            .map(|(prefix, trimmed_prefix_len)| {
12074                                comment_prefix_range(
12075                                    snapshot.deref(),
12076                                    row,
12077                                    &prefix[..trimmed_prefix_len],
12078                                    &prefix[trimmed_prefix_len..],
12079                                    ignore_indent,
12080                                )
12081                            })
12082                            .max_by_key(|range| range.end.column - range.start.column)
12083                            .expect("prefixes is non-empty");
12084
12085                        if prefix_range.is_empty() {
12086                            all_selection_lines_are_comments = false;
12087                        }
12088
12089                        selection_edit_ranges.push(prefix_range);
12090                    }
12091
12092                    if all_selection_lines_are_comments {
12093                        edits.extend(
12094                            selection_edit_ranges
12095                                .iter()
12096                                .cloned()
12097                                .map(|range| (range, empty_str.clone())),
12098                        );
12099                    } else {
12100                        let min_column = selection_edit_ranges
12101                            .iter()
12102                            .map(|range| range.start.column)
12103                            .min()
12104                            .unwrap_or(0);
12105                        edits.extend(selection_edit_ranges.iter().map(|range| {
12106                            let position = Point::new(range.start.row, min_column);
12107                            (position..position, first_prefix.clone())
12108                        }));
12109                    }
12110                } else if let Some((full_comment_prefix, comment_suffix)) =
12111                    language.block_comment_delimiters()
12112                {
12113                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12114                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12115                    let prefix_range = comment_prefix_range(
12116                        snapshot.deref(),
12117                        start_row,
12118                        comment_prefix,
12119                        comment_prefix_whitespace,
12120                        ignore_indent,
12121                    );
12122                    let suffix_range = comment_suffix_range(
12123                        snapshot.deref(),
12124                        end_row,
12125                        comment_suffix.trim_start_matches(' '),
12126                        comment_suffix.starts_with(' '),
12127                    );
12128
12129                    if prefix_range.is_empty() || suffix_range.is_empty() {
12130                        edits.push((
12131                            prefix_range.start..prefix_range.start,
12132                            full_comment_prefix.clone(),
12133                        ));
12134                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12135                        suffixes_inserted.push((end_row, comment_suffix.len()));
12136                    } else {
12137                        edits.push((prefix_range, empty_str.clone()));
12138                        edits.push((suffix_range, empty_str.clone()));
12139                    }
12140                } else {
12141                    continue;
12142                }
12143            }
12144
12145            drop(snapshot);
12146            this.buffer.update(cx, |buffer, cx| {
12147                buffer.edit(edits, None, cx);
12148            });
12149
12150            // Adjust selections so that they end before any comment suffixes that
12151            // were inserted.
12152            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12153            let mut selections = this.selections.all::<Point>(cx);
12154            let snapshot = this.buffer.read(cx).read(cx);
12155            for selection in &mut selections {
12156                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12157                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12158                        Ordering::Less => {
12159                            suffixes_inserted.next();
12160                            continue;
12161                        }
12162                        Ordering::Greater => break,
12163                        Ordering::Equal => {
12164                            if selection.end.column == snapshot.line_len(row) {
12165                                if selection.is_empty() {
12166                                    selection.start.column -= suffix_len as u32;
12167                                }
12168                                selection.end.column -= suffix_len as u32;
12169                            }
12170                            break;
12171                        }
12172                    }
12173                }
12174            }
12175
12176            drop(snapshot);
12177            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12178                s.select(selections)
12179            });
12180
12181            let selections = this.selections.all::<Point>(cx);
12182            let selections_on_single_row = selections.windows(2).all(|selections| {
12183                selections[0].start.row == selections[1].start.row
12184                    && selections[0].end.row == selections[1].end.row
12185                    && selections[0].start.row == selections[0].end.row
12186            });
12187            let selections_selecting = selections
12188                .iter()
12189                .any(|selection| selection.start != selection.end);
12190            let advance_downwards = action.advance_downwards
12191                && selections_on_single_row
12192                && !selections_selecting
12193                && !matches!(this.mode, EditorMode::SingleLine { .. });
12194
12195            if advance_downwards {
12196                let snapshot = this.buffer.read(cx).snapshot(cx);
12197
12198                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12199                    s.move_cursors_with(|display_snapshot, display_point, _| {
12200                        let mut point = display_point.to_point(display_snapshot);
12201                        point.row += 1;
12202                        point = snapshot.clip_point(point, Bias::Left);
12203                        let display_point = point.to_display_point(display_snapshot);
12204                        let goal = SelectionGoal::HorizontalPosition(
12205                            display_snapshot
12206                                .x_for_display_point(display_point, text_layout_details)
12207                                .into(),
12208                        );
12209                        (display_point, goal)
12210                    })
12211                });
12212            }
12213        });
12214    }
12215
12216    pub fn select_enclosing_symbol(
12217        &mut self,
12218        _: &SelectEnclosingSymbol,
12219        window: &mut Window,
12220        cx: &mut Context<Self>,
12221    ) {
12222        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12223
12224        let buffer = self.buffer.read(cx).snapshot(cx);
12225        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12226
12227        fn update_selection(
12228            selection: &Selection<usize>,
12229            buffer_snap: &MultiBufferSnapshot,
12230        ) -> Option<Selection<usize>> {
12231            let cursor = selection.head();
12232            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12233            for symbol in symbols.iter().rev() {
12234                let start = symbol.range.start.to_offset(buffer_snap);
12235                let end = symbol.range.end.to_offset(buffer_snap);
12236                let new_range = start..end;
12237                if start < selection.start || end > selection.end {
12238                    return Some(Selection {
12239                        id: selection.id,
12240                        start: new_range.start,
12241                        end: new_range.end,
12242                        goal: SelectionGoal::None,
12243                        reversed: selection.reversed,
12244                    });
12245                }
12246            }
12247            None
12248        }
12249
12250        let mut selected_larger_symbol = false;
12251        let new_selections = old_selections
12252            .iter()
12253            .map(|selection| match update_selection(selection, &buffer) {
12254                Some(new_selection) => {
12255                    if new_selection.range() != selection.range() {
12256                        selected_larger_symbol = true;
12257                    }
12258                    new_selection
12259                }
12260                None => selection.clone(),
12261            })
12262            .collect::<Vec<_>>();
12263
12264        if selected_larger_symbol {
12265            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12266                s.select(new_selections);
12267            });
12268        }
12269    }
12270
12271    pub fn select_larger_syntax_node(
12272        &mut self,
12273        _: &SelectLargerSyntaxNode,
12274        window: &mut Window,
12275        cx: &mut Context<Self>,
12276    ) {
12277        let Some(visible_row_count) = self.visible_row_count() else {
12278            return;
12279        };
12280        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12281        if old_selections.is_empty() {
12282            return;
12283        }
12284
12285        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12286
12287        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12288        let buffer = self.buffer.read(cx).snapshot(cx);
12289
12290        let mut selected_larger_node = false;
12291        let mut new_selections = old_selections
12292            .iter()
12293            .map(|selection| {
12294                let old_range = selection.start..selection.end;
12295                let mut new_range = old_range.clone();
12296                let mut new_node = None;
12297                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12298                {
12299                    new_node = Some(node);
12300                    new_range = match containing_range {
12301                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12302                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12303                    };
12304                    if !display_map.intersects_fold(new_range.start)
12305                        && !display_map.intersects_fold(new_range.end)
12306                    {
12307                        break;
12308                    }
12309                }
12310
12311                if let Some(node) = new_node {
12312                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12313                    // nodes. Parent and grandparent are also logged because this operation will not
12314                    // visit nodes that have the same range as their parent.
12315                    log::info!("Node: {node:?}");
12316                    let parent = node.parent();
12317                    log::info!("Parent: {parent:?}");
12318                    let grandparent = parent.and_then(|x| x.parent());
12319                    log::info!("Grandparent: {grandparent:?}");
12320                }
12321
12322                selected_larger_node |= new_range != old_range;
12323                Selection {
12324                    id: selection.id,
12325                    start: new_range.start,
12326                    end: new_range.end,
12327                    goal: SelectionGoal::None,
12328                    reversed: selection.reversed,
12329                }
12330            })
12331            .collect::<Vec<_>>();
12332
12333        if !selected_larger_node {
12334            return; // don't put this call in the history
12335        }
12336
12337        // scroll based on transformation done to the last selection created by the user
12338        let (last_old, last_new) = old_selections
12339            .last()
12340            .zip(new_selections.last().cloned())
12341            .expect("old_selections isn't empty");
12342
12343        // revert selection
12344        let is_selection_reversed = {
12345            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12346            new_selections.last_mut().expect("checked above").reversed =
12347                should_newest_selection_be_reversed;
12348            should_newest_selection_be_reversed
12349        };
12350
12351        if selected_larger_node {
12352            self.select_syntax_node_history.disable_clearing = true;
12353            self.change_selections(None, window, cx, |s| {
12354                s.select(new_selections.clone());
12355            });
12356            self.select_syntax_node_history.disable_clearing = false;
12357        }
12358
12359        let start_row = last_new.start.to_display_point(&display_map).row().0;
12360        let end_row = last_new.end.to_display_point(&display_map).row().0;
12361        let selection_height = end_row - start_row + 1;
12362        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12363
12364        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12365        let scroll_behavior = if fits_on_the_screen {
12366            self.request_autoscroll(Autoscroll::fit(), cx);
12367            SelectSyntaxNodeScrollBehavior::FitSelection
12368        } else if is_selection_reversed {
12369            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12370            SelectSyntaxNodeScrollBehavior::CursorTop
12371        } else {
12372            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12373            SelectSyntaxNodeScrollBehavior::CursorBottom
12374        };
12375
12376        self.select_syntax_node_history.push((
12377            old_selections,
12378            scroll_behavior,
12379            is_selection_reversed,
12380        ));
12381    }
12382
12383    pub fn select_smaller_syntax_node(
12384        &mut self,
12385        _: &SelectSmallerSyntaxNode,
12386        window: &mut Window,
12387        cx: &mut Context<Self>,
12388    ) {
12389        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12390
12391        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12392            self.select_syntax_node_history.pop()
12393        {
12394            if let Some(selection) = selections.last_mut() {
12395                selection.reversed = is_selection_reversed;
12396            }
12397
12398            self.select_syntax_node_history.disable_clearing = true;
12399            self.change_selections(None, window, cx, |s| {
12400                s.select(selections.to_vec());
12401            });
12402            self.select_syntax_node_history.disable_clearing = false;
12403
12404            match scroll_behavior {
12405                SelectSyntaxNodeScrollBehavior::CursorTop => {
12406                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12407                }
12408                SelectSyntaxNodeScrollBehavior::FitSelection => {
12409                    self.request_autoscroll(Autoscroll::fit(), cx);
12410                }
12411                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12412                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12413                }
12414            }
12415        }
12416    }
12417
12418    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12419        if !EditorSettings::get_global(cx).gutter.runnables {
12420            self.clear_tasks();
12421            return Task::ready(());
12422        }
12423        let project = self.project.as_ref().map(Entity::downgrade);
12424        cx.spawn_in(window, async move |this, cx| {
12425            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12426            let Some(project) = project.and_then(|p| p.upgrade()) else {
12427                return;
12428            };
12429            let Ok(display_snapshot) = this.update(cx, |this, cx| {
12430                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12431            }) else {
12432                return;
12433            };
12434
12435            let hide_runnables = project
12436                .update(cx, |project, cx| {
12437                    // Do not display any test indicators in non-dev server remote projects.
12438                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12439                })
12440                .unwrap_or(true);
12441            if hide_runnables {
12442                return;
12443            }
12444            let new_rows =
12445                cx.background_spawn({
12446                    let snapshot = display_snapshot.clone();
12447                    async move {
12448                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12449                    }
12450                })
12451                    .await;
12452
12453            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12454            this.update(cx, |this, _| {
12455                this.clear_tasks();
12456                for (key, value) in rows {
12457                    this.insert_tasks(key, value);
12458                }
12459            })
12460            .ok();
12461        })
12462    }
12463    fn fetch_runnable_ranges(
12464        snapshot: &DisplaySnapshot,
12465        range: Range<Anchor>,
12466    ) -> Vec<language::RunnableRange> {
12467        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12468    }
12469
12470    fn runnable_rows(
12471        project: Entity<Project>,
12472        snapshot: DisplaySnapshot,
12473        runnable_ranges: Vec<RunnableRange>,
12474        mut cx: AsyncWindowContext,
12475    ) -> Vec<((BufferId, u32), RunnableTasks)> {
12476        runnable_ranges
12477            .into_iter()
12478            .filter_map(|mut runnable| {
12479                let tasks = cx
12480                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12481                    .ok()?;
12482                if tasks.is_empty() {
12483                    return None;
12484                }
12485
12486                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12487
12488                let row = snapshot
12489                    .buffer_snapshot
12490                    .buffer_line_for_row(MultiBufferRow(point.row))?
12491                    .1
12492                    .start
12493                    .row;
12494
12495                let context_range =
12496                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12497                Some((
12498                    (runnable.buffer_id, row),
12499                    RunnableTasks {
12500                        templates: tasks,
12501                        offset: snapshot
12502                            .buffer_snapshot
12503                            .anchor_before(runnable.run_range.start),
12504                        context_range,
12505                        column: point.column,
12506                        extra_variables: runnable.extra_captures,
12507                    },
12508                ))
12509            })
12510            .collect()
12511    }
12512
12513    fn templates_with_tags(
12514        project: &Entity<Project>,
12515        runnable: &mut Runnable,
12516        cx: &mut App,
12517    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12518        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12519            let (worktree_id, file) = project
12520                .buffer_for_id(runnable.buffer, cx)
12521                .and_then(|buffer| buffer.read(cx).file())
12522                .map(|file| (file.worktree_id(cx), file.clone()))
12523                .unzip();
12524
12525            (
12526                project.task_store().read(cx).task_inventory().cloned(),
12527                worktree_id,
12528                file,
12529            )
12530        });
12531
12532        let tags = mem::take(&mut runnable.tags);
12533        let mut tags: Vec<_> = tags
12534            .into_iter()
12535            .flat_map(|tag| {
12536                let tag = tag.0.clone();
12537                inventory
12538                    .as_ref()
12539                    .into_iter()
12540                    .flat_map(|inventory| {
12541                        inventory.read(cx).list_tasks(
12542                            file.clone(),
12543                            Some(runnable.language.clone()),
12544                            worktree_id,
12545                            cx,
12546                        )
12547                    })
12548                    .filter(move |(_, template)| {
12549                        template.tags.iter().any(|source_tag| source_tag == &tag)
12550                    })
12551            })
12552            .sorted_by_key(|(kind, _)| kind.to_owned())
12553            .collect();
12554        if let Some((leading_tag_source, _)) = tags.first() {
12555            // Strongest source wins; if we have worktree tag binding, prefer that to
12556            // global and language bindings;
12557            // if we have a global binding, prefer that to language binding.
12558            let first_mismatch = tags
12559                .iter()
12560                .position(|(tag_source, _)| tag_source != leading_tag_source);
12561            if let Some(index) = first_mismatch {
12562                tags.truncate(index);
12563            }
12564        }
12565
12566        tags
12567    }
12568
12569    pub fn move_to_enclosing_bracket(
12570        &mut self,
12571        _: &MoveToEnclosingBracket,
12572        window: &mut Window,
12573        cx: &mut Context<Self>,
12574    ) {
12575        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12576        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12577            s.move_offsets_with(|snapshot, selection| {
12578                let Some(enclosing_bracket_ranges) =
12579                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12580                else {
12581                    return;
12582                };
12583
12584                let mut best_length = usize::MAX;
12585                let mut best_inside = false;
12586                let mut best_in_bracket_range = false;
12587                let mut best_destination = None;
12588                for (open, close) in enclosing_bracket_ranges {
12589                    let close = close.to_inclusive();
12590                    let length = close.end() - open.start;
12591                    let inside = selection.start >= open.end && selection.end <= *close.start();
12592                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12593                        || close.contains(&selection.head());
12594
12595                    // If best is next to a bracket and current isn't, skip
12596                    if !in_bracket_range && best_in_bracket_range {
12597                        continue;
12598                    }
12599
12600                    // Prefer smaller lengths unless best is inside and current isn't
12601                    if length > best_length && (best_inside || !inside) {
12602                        continue;
12603                    }
12604
12605                    best_length = length;
12606                    best_inside = inside;
12607                    best_in_bracket_range = in_bracket_range;
12608                    best_destination = Some(
12609                        if close.contains(&selection.start) && close.contains(&selection.end) {
12610                            if inside { open.end } else { open.start }
12611                        } else if inside {
12612                            *close.start()
12613                        } else {
12614                            *close.end()
12615                        },
12616                    );
12617                }
12618
12619                if let Some(destination) = best_destination {
12620                    selection.collapse_to(destination, SelectionGoal::None);
12621                }
12622            })
12623        });
12624    }
12625
12626    pub fn undo_selection(
12627        &mut self,
12628        _: &UndoSelection,
12629        window: &mut Window,
12630        cx: &mut Context<Self>,
12631    ) {
12632        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12633        self.end_selection(window, cx);
12634        self.selection_history.mode = SelectionHistoryMode::Undoing;
12635        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12636            self.change_selections(None, window, cx, |s| {
12637                s.select_anchors(entry.selections.to_vec())
12638            });
12639            self.select_next_state = entry.select_next_state;
12640            self.select_prev_state = entry.select_prev_state;
12641            self.add_selections_state = entry.add_selections_state;
12642            self.request_autoscroll(Autoscroll::newest(), cx);
12643        }
12644        self.selection_history.mode = SelectionHistoryMode::Normal;
12645    }
12646
12647    pub fn redo_selection(
12648        &mut self,
12649        _: &RedoSelection,
12650        window: &mut Window,
12651        cx: &mut Context<Self>,
12652    ) {
12653        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12654        self.end_selection(window, cx);
12655        self.selection_history.mode = SelectionHistoryMode::Redoing;
12656        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12657            self.change_selections(None, window, cx, |s| {
12658                s.select_anchors(entry.selections.to_vec())
12659            });
12660            self.select_next_state = entry.select_next_state;
12661            self.select_prev_state = entry.select_prev_state;
12662            self.add_selections_state = entry.add_selections_state;
12663            self.request_autoscroll(Autoscroll::newest(), cx);
12664        }
12665        self.selection_history.mode = SelectionHistoryMode::Normal;
12666    }
12667
12668    pub fn expand_excerpts(
12669        &mut self,
12670        action: &ExpandExcerpts,
12671        _: &mut Window,
12672        cx: &mut Context<Self>,
12673    ) {
12674        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12675    }
12676
12677    pub fn expand_excerpts_down(
12678        &mut self,
12679        action: &ExpandExcerptsDown,
12680        _: &mut Window,
12681        cx: &mut Context<Self>,
12682    ) {
12683        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12684    }
12685
12686    pub fn expand_excerpts_up(
12687        &mut self,
12688        action: &ExpandExcerptsUp,
12689        _: &mut Window,
12690        cx: &mut Context<Self>,
12691    ) {
12692        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12693    }
12694
12695    pub fn expand_excerpts_for_direction(
12696        &mut self,
12697        lines: u32,
12698        direction: ExpandExcerptDirection,
12699
12700        cx: &mut Context<Self>,
12701    ) {
12702        let selections = self.selections.disjoint_anchors();
12703
12704        let lines = if lines == 0 {
12705            EditorSettings::get_global(cx).expand_excerpt_lines
12706        } else {
12707            lines
12708        };
12709
12710        self.buffer.update(cx, |buffer, cx| {
12711            let snapshot = buffer.snapshot(cx);
12712            let mut excerpt_ids = selections
12713                .iter()
12714                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12715                .collect::<Vec<_>>();
12716            excerpt_ids.sort();
12717            excerpt_ids.dedup();
12718            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12719        })
12720    }
12721
12722    pub fn expand_excerpt(
12723        &mut self,
12724        excerpt: ExcerptId,
12725        direction: ExpandExcerptDirection,
12726        window: &mut Window,
12727        cx: &mut Context<Self>,
12728    ) {
12729        let current_scroll_position = self.scroll_position(cx);
12730        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
12731        let mut should_scroll_up = false;
12732
12733        if direction == ExpandExcerptDirection::Down {
12734            let multi_buffer = self.buffer.read(cx);
12735            let snapshot = multi_buffer.snapshot(cx);
12736            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
12737                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12738                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
12739                        let buffer_snapshot = buffer.read(cx).snapshot();
12740                        let excerpt_end_row =
12741                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
12742                        let last_row = buffer_snapshot.max_point().row;
12743                        let lines_below = last_row.saturating_sub(excerpt_end_row);
12744                        should_scroll_up = lines_below >= lines_to_expand;
12745                    }
12746                }
12747            }
12748        }
12749
12750        self.buffer.update(cx, |buffer, cx| {
12751            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
12752        });
12753
12754        if should_scroll_up {
12755            let new_scroll_position =
12756                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
12757            self.set_scroll_position(new_scroll_position, window, cx);
12758        }
12759    }
12760
12761    pub fn go_to_singleton_buffer_point(
12762        &mut self,
12763        point: Point,
12764        window: &mut Window,
12765        cx: &mut Context<Self>,
12766    ) {
12767        self.go_to_singleton_buffer_range(point..point, window, cx);
12768    }
12769
12770    pub fn go_to_singleton_buffer_range(
12771        &mut self,
12772        range: Range<Point>,
12773        window: &mut Window,
12774        cx: &mut Context<Self>,
12775    ) {
12776        let multibuffer = self.buffer().read(cx);
12777        let Some(buffer) = multibuffer.as_singleton() else {
12778            return;
12779        };
12780        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12781            return;
12782        };
12783        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12784            return;
12785        };
12786        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12787            s.select_anchor_ranges([start..end])
12788        });
12789    }
12790
12791    fn go_to_diagnostic(
12792        &mut self,
12793        _: &GoToDiagnostic,
12794        window: &mut Window,
12795        cx: &mut Context<Self>,
12796    ) {
12797        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12798        self.go_to_diagnostic_impl(Direction::Next, window, cx)
12799    }
12800
12801    fn go_to_prev_diagnostic(
12802        &mut self,
12803        _: &GoToPreviousDiagnostic,
12804        window: &mut Window,
12805        cx: &mut Context<Self>,
12806    ) {
12807        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12808        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12809    }
12810
12811    pub fn go_to_diagnostic_impl(
12812        &mut self,
12813        direction: Direction,
12814        window: &mut Window,
12815        cx: &mut Context<Self>,
12816    ) {
12817        let buffer = self.buffer.read(cx).snapshot(cx);
12818        let selection = self.selections.newest::<usize>(cx);
12819        // If there is an active Diagnostic Popover jump to its diagnostic instead.
12820        if direction == Direction::Next {
12821            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12822                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12823                    return;
12824                };
12825                self.activate_diagnostics(
12826                    buffer_id,
12827                    popover.local_diagnostic.diagnostic.group_id,
12828                    window,
12829                    cx,
12830                );
12831                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12832                    let primary_range_start = active_diagnostics.primary_range.start;
12833                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12834                        let mut new_selection = s.newest_anchor().clone();
12835                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12836                        s.select_anchors(vec![new_selection.clone()]);
12837                    });
12838                    self.refresh_inline_completion(false, true, window, cx);
12839                }
12840                return;
12841            }
12842        }
12843
12844        let active_group_id = self
12845            .active_diagnostics
12846            .as_ref()
12847            .map(|active_group| active_group.group_id);
12848        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12849            active_diagnostics
12850                .primary_range
12851                .to_offset(&buffer)
12852                .to_inclusive()
12853        });
12854        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12855            if active_primary_range.contains(&selection.head()) {
12856                *active_primary_range.start()
12857            } else {
12858                selection.head()
12859            }
12860        } else {
12861            selection.head()
12862        };
12863
12864        let snapshot = self.snapshot(window, cx);
12865        let primary_diagnostics_before = buffer
12866            .diagnostics_in_range::<usize>(0..search_start)
12867            .filter(|entry| entry.diagnostic.is_primary)
12868            .filter(|entry| entry.range.start != entry.range.end)
12869            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12870            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12871            .collect::<Vec<_>>();
12872        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12873            primary_diagnostics_before
12874                .iter()
12875                .position(|entry| entry.diagnostic.group_id == active_group_id)
12876        });
12877
12878        let primary_diagnostics_after = buffer
12879            .diagnostics_in_range::<usize>(search_start..buffer.len())
12880            .filter(|entry| entry.diagnostic.is_primary)
12881            .filter(|entry| entry.range.start != entry.range.end)
12882            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12883            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12884            .collect::<Vec<_>>();
12885        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12886            primary_diagnostics_after
12887                .iter()
12888                .enumerate()
12889                .rev()
12890                .find_map(|(i, entry)| {
12891                    if entry.diagnostic.group_id == active_group_id {
12892                        Some(i)
12893                    } else {
12894                        None
12895                    }
12896                })
12897        });
12898
12899        let next_primary_diagnostic = match direction {
12900            Direction::Prev => primary_diagnostics_before
12901                .iter()
12902                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12903                .rev()
12904                .next(),
12905            Direction::Next => primary_diagnostics_after
12906                .iter()
12907                .skip(
12908                    last_same_group_diagnostic_after
12909                        .map(|index| index + 1)
12910                        .unwrap_or(0),
12911                )
12912                .next(),
12913        };
12914
12915        // Cycle around to the start of the buffer, potentially moving back to the start of
12916        // the currently active diagnostic.
12917        let cycle_around = || match direction {
12918            Direction::Prev => primary_diagnostics_after
12919                .iter()
12920                .rev()
12921                .chain(primary_diagnostics_before.iter().rev())
12922                .next(),
12923            Direction::Next => primary_diagnostics_before
12924                .iter()
12925                .chain(primary_diagnostics_after.iter())
12926                .next(),
12927        };
12928
12929        if let Some((primary_range, group_id)) = next_primary_diagnostic
12930            .or_else(cycle_around)
12931            .map(|entry| (&entry.range, entry.diagnostic.group_id))
12932        {
12933            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12934                return;
12935            };
12936            self.activate_diagnostics(buffer_id, group_id, window, cx);
12937            if self.active_diagnostics.is_some() {
12938                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12939                    s.select(vec![Selection {
12940                        id: selection.id,
12941                        start: primary_range.start,
12942                        end: primary_range.start,
12943                        reversed: false,
12944                        goal: SelectionGoal::None,
12945                    }]);
12946                });
12947                self.refresh_inline_completion(false, true, window, cx);
12948            }
12949        }
12950    }
12951
12952    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12953        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12954        let snapshot = self.snapshot(window, cx);
12955        let selection = self.selections.newest::<Point>(cx);
12956        self.go_to_hunk_before_or_after_position(
12957            &snapshot,
12958            selection.head(),
12959            Direction::Next,
12960            window,
12961            cx,
12962        );
12963    }
12964
12965    pub fn go_to_hunk_before_or_after_position(
12966        &mut self,
12967        snapshot: &EditorSnapshot,
12968        position: Point,
12969        direction: Direction,
12970        window: &mut Window,
12971        cx: &mut Context<Editor>,
12972    ) {
12973        let row = if direction == Direction::Next {
12974            self.hunk_after_position(snapshot, position)
12975                .map(|hunk| hunk.row_range.start)
12976        } else {
12977            self.hunk_before_position(snapshot, position)
12978        };
12979
12980        if let Some(row) = row {
12981            let destination = Point::new(row.0, 0);
12982            let autoscroll = Autoscroll::center();
12983
12984            self.unfold_ranges(&[destination..destination], false, false, cx);
12985            self.change_selections(Some(autoscroll), window, cx, |s| {
12986                s.select_ranges([destination..destination]);
12987            });
12988        }
12989    }
12990
12991    fn hunk_after_position(
12992        &mut self,
12993        snapshot: &EditorSnapshot,
12994        position: Point,
12995    ) -> Option<MultiBufferDiffHunk> {
12996        snapshot
12997            .buffer_snapshot
12998            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12999            .find(|hunk| hunk.row_range.start.0 > position.row)
13000            .or_else(|| {
13001                snapshot
13002                    .buffer_snapshot
13003                    .diff_hunks_in_range(Point::zero()..position)
13004                    .find(|hunk| hunk.row_range.end.0 < position.row)
13005            })
13006    }
13007
13008    fn go_to_prev_hunk(
13009        &mut self,
13010        _: &GoToPreviousHunk,
13011        window: &mut Window,
13012        cx: &mut Context<Self>,
13013    ) {
13014        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13015        let snapshot = self.snapshot(window, cx);
13016        let selection = self.selections.newest::<Point>(cx);
13017        self.go_to_hunk_before_or_after_position(
13018            &snapshot,
13019            selection.head(),
13020            Direction::Prev,
13021            window,
13022            cx,
13023        );
13024    }
13025
13026    fn hunk_before_position(
13027        &mut self,
13028        snapshot: &EditorSnapshot,
13029        position: Point,
13030    ) -> Option<MultiBufferRow> {
13031        snapshot
13032            .buffer_snapshot
13033            .diff_hunk_before(position)
13034            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13035    }
13036
13037    fn go_to_line<T: 'static>(
13038        &mut self,
13039        position: Anchor,
13040        highlight_color: Option<Hsla>,
13041        window: &mut Window,
13042        cx: &mut Context<Self>,
13043    ) {
13044        let snapshot = self.snapshot(window, cx).display_snapshot;
13045        let position = position.to_point(&snapshot.buffer_snapshot);
13046        let start = snapshot
13047            .buffer_snapshot
13048            .clip_point(Point::new(position.row, 0), Bias::Left);
13049        let end = start + Point::new(1, 0);
13050        let start = snapshot.buffer_snapshot.anchor_before(start);
13051        let end = snapshot.buffer_snapshot.anchor_before(end);
13052
13053        self.highlight_rows::<T>(
13054            start..end,
13055            highlight_color
13056                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13057            false,
13058            cx,
13059        );
13060        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13061    }
13062
13063    pub fn go_to_definition(
13064        &mut self,
13065        _: &GoToDefinition,
13066        window: &mut Window,
13067        cx: &mut Context<Self>,
13068    ) -> Task<Result<Navigated>> {
13069        let definition =
13070            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13071        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13072        cx.spawn_in(window, async move |editor, cx| {
13073            if definition.await? == Navigated::Yes {
13074                return Ok(Navigated::Yes);
13075            }
13076            match fallback_strategy {
13077                GoToDefinitionFallback::None => Ok(Navigated::No),
13078                GoToDefinitionFallback::FindAllReferences => {
13079                    match editor.update_in(cx, |editor, window, cx| {
13080                        editor.find_all_references(&FindAllReferences, window, cx)
13081                    })? {
13082                        Some(references) => references.await,
13083                        None => Ok(Navigated::No),
13084                    }
13085                }
13086            }
13087        })
13088    }
13089
13090    pub fn go_to_declaration(
13091        &mut self,
13092        _: &GoToDeclaration,
13093        window: &mut Window,
13094        cx: &mut Context<Self>,
13095    ) -> Task<Result<Navigated>> {
13096        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13097    }
13098
13099    pub fn go_to_declaration_split(
13100        &mut self,
13101        _: &GoToDeclaration,
13102        window: &mut Window,
13103        cx: &mut Context<Self>,
13104    ) -> Task<Result<Navigated>> {
13105        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13106    }
13107
13108    pub fn go_to_implementation(
13109        &mut self,
13110        _: &GoToImplementation,
13111        window: &mut Window,
13112        cx: &mut Context<Self>,
13113    ) -> Task<Result<Navigated>> {
13114        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13115    }
13116
13117    pub fn go_to_implementation_split(
13118        &mut self,
13119        _: &GoToImplementationSplit,
13120        window: &mut Window,
13121        cx: &mut Context<Self>,
13122    ) -> Task<Result<Navigated>> {
13123        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13124    }
13125
13126    pub fn go_to_type_definition(
13127        &mut self,
13128        _: &GoToTypeDefinition,
13129        window: &mut Window,
13130        cx: &mut Context<Self>,
13131    ) -> Task<Result<Navigated>> {
13132        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13133    }
13134
13135    pub fn go_to_definition_split(
13136        &mut self,
13137        _: &GoToDefinitionSplit,
13138        window: &mut Window,
13139        cx: &mut Context<Self>,
13140    ) -> Task<Result<Navigated>> {
13141        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13142    }
13143
13144    pub fn go_to_type_definition_split(
13145        &mut self,
13146        _: &GoToTypeDefinitionSplit,
13147        window: &mut Window,
13148        cx: &mut Context<Self>,
13149    ) -> Task<Result<Navigated>> {
13150        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13151    }
13152
13153    fn go_to_definition_of_kind(
13154        &mut self,
13155        kind: GotoDefinitionKind,
13156        split: bool,
13157        window: &mut Window,
13158        cx: &mut Context<Self>,
13159    ) -> Task<Result<Navigated>> {
13160        let Some(provider) = self.semantics_provider.clone() else {
13161            return Task::ready(Ok(Navigated::No));
13162        };
13163        let head = self.selections.newest::<usize>(cx).head();
13164        let buffer = self.buffer.read(cx);
13165        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13166            text_anchor
13167        } else {
13168            return Task::ready(Ok(Navigated::No));
13169        };
13170
13171        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13172            return Task::ready(Ok(Navigated::No));
13173        };
13174
13175        cx.spawn_in(window, async move |editor, cx| {
13176            let definitions = definitions.await?;
13177            let navigated = editor
13178                .update_in(cx, |editor, window, cx| {
13179                    editor.navigate_to_hover_links(
13180                        Some(kind),
13181                        definitions
13182                            .into_iter()
13183                            .filter(|location| {
13184                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13185                            })
13186                            .map(HoverLink::Text)
13187                            .collect::<Vec<_>>(),
13188                        split,
13189                        window,
13190                        cx,
13191                    )
13192                })?
13193                .await?;
13194            anyhow::Ok(navigated)
13195        })
13196    }
13197
13198    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13199        let selection = self.selections.newest_anchor();
13200        let head = selection.head();
13201        let tail = selection.tail();
13202
13203        let Some((buffer, start_position)) =
13204            self.buffer.read(cx).text_anchor_for_position(head, cx)
13205        else {
13206            return;
13207        };
13208
13209        let end_position = if head != tail {
13210            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13211                return;
13212            };
13213            Some(pos)
13214        } else {
13215            None
13216        };
13217
13218        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13219            let url = if let Some(end_pos) = end_position {
13220                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13221            } else {
13222                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13223            };
13224
13225            if let Some(url) = url {
13226                editor.update(cx, |_, cx| {
13227                    cx.open_url(&url);
13228                })
13229            } else {
13230                Ok(())
13231            }
13232        });
13233
13234        url_finder.detach();
13235    }
13236
13237    pub fn open_selected_filename(
13238        &mut self,
13239        _: &OpenSelectedFilename,
13240        window: &mut Window,
13241        cx: &mut Context<Self>,
13242    ) {
13243        let Some(workspace) = self.workspace() else {
13244            return;
13245        };
13246
13247        let position = self.selections.newest_anchor().head();
13248
13249        let Some((buffer, buffer_position)) =
13250            self.buffer.read(cx).text_anchor_for_position(position, cx)
13251        else {
13252            return;
13253        };
13254
13255        let project = self.project.clone();
13256
13257        cx.spawn_in(window, async move |_, cx| {
13258            let result = find_file(&buffer, project, buffer_position, cx).await;
13259
13260            if let Some((_, path)) = result {
13261                workspace
13262                    .update_in(cx, |workspace, window, cx| {
13263                        workspace.open_resolved_path(path, window, cx)
13264                    })?
13265                    .await?;
13266            }
13267            anyhow::Ok(())
13268        })
13269        .detach();
13270    }
13271
13272    pub(crate) fn navigate_to_hover_links(
13273        &mut self,
13274        kind: Option<GotoDefinitionKind>,
13275        mut definitions: Vec<HoverLink>,
13276        split: bool,
13277        window: &mut Window,
13278        cx: &mut Context<Editor>,
13279    ) -> Task<Result<Navigated>> {
13280        // If there is one definition, just open it directly
13281        if definitions.len() == 1 {
13282            let definition = definitions.pop().unwrap();
13283
13284            enum TargetTaskResult {
13285                Location(Option<Location>),
13286                AlreadyNavigated,
13287            }
13288
13289            let target_task = match definition {
13290                HoverLink::Text(link) => {
13291                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13292                }
13293                HoverLink::InlayHint(lsp_location, server_id) => {
13294                    let computation =
13295                        self.compute_target_location(lsp_location, server_id, window, cx);
13296                    cx.background_spawn(async move {
13297                        let location = computation.await?;
13298                        Ok(TargetTaskResult::Location(location))
13299                    })
13300                }
13301                HoverLink::Url(url) => {
13302                    cx.open_url(&url);
13303                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13304                }
13305                HoverLink::File(path) => {
13306                    if let Some(workspace) = self.workspace() {
13307                        cx.spawn_in(window, async move |_, cx| {
13308                            workspace
13309                                .update_in(cx, |workspace, window, cx| {
13310                                    workspace.open_resolved_path(path, window, cx)
13311                                })?
13312                                .await
13313                                .map(|_| TargetTaskResult::AlreadyNavigated)
13314                        })
13315                    } else {
13316                        Task::ready(Ok(TargetTaskResult::Location(None)))
13317                    }
13318                }
13319            };
13320            cx.spawn_in(window, async move |editor, cx| {
13321                let target = match target_task.await.context("target resolution task")? {
13322                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13323                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13324                    TargetTaskResult::Location(Some(target)) => target,
13325                };
13326
13327                editor.update_in(cx, |editor, window, cx| {
13328                    let Some(workspace) = editor.workspace() else {
13329                        return Navigated::No;
13330                    };
13331                    let pane = workspace.read(cx).active_pane().clone();
13332
13333                    let range = target.range.to_point(target.buffer.read(cx));
13334                    let range = editor.range_for_match(&range);
13335                    let range = collapse_multiline_range(range);
13336
13337                    if !split
13338                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13339                    {
13340                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13341                    } else {
13342                        window.defer(cx, move |window, cx| {
13343                            let target_editor: Entity<Self> =
13344                                workspace.update(cx, |workspace, cx| {
13345                                    let pane = if split {
13346                                        workspace.adjacent_pane(window, cx)
13347                                    } else {
13348                                        workspace.active_pane().clone()
13349                                    };
13350
13351                                    workspace.open_project_item(
13352                                        pane,
13353                                        target.buffer.clone(),
13354                                        true,
13355                                        true,
13356                                        window,
13357                                        cx,
13358                                    )
13359                                });
13360                            target_editor.update(cx, |target_editor, cx| {
13361                                // When selecting a definition in a different buffer, disable the nav history
13362                                // to avoid creating a history entry at the previous cursor location.
13363                                pane.update(cx, |pane, _| pane.disable_history());
13364                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13365                                pane.update(cx, |pane, _| pane.enable_history());
13366                            });
13367                        });
13368                    }
13369                    Navigated::Yes
13370                })
13371            })
13372        } else if !definitions.is_empty() {
13373            cx.spawn_in(window, async move |editor, cx| {
13374                let (title, location_tasks, workspace) = editor
13375                    .update_in(cx, |editor, window, cx| {
13376                        let tab_kind = match kind {
13377                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13378                            _ => "Definitions",
13379                        };
13380                        let title = definitions
13381                            .iter()
13382                            .find_map(|definition| match definition {
13383                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13384                                    let buffer = origin.buffer.read(cx);
13385                                    format!(
13386                                        "{} for {}",
13387                                        tab_kind,
13388                                        buffer
13389                                            .text_for_range(origin.range.clone())
13390                                            .collect::<String>()
13391                                    )
13392                                }),
13393                                HoverLink::InlayHint(_, _) => None,
13394                                HoverLink::Url(_) => None,
13395                                HoverLink::File(_) => None,
13396                            })
13397                            .unwrap_or(tab_kind.to_string());
13398                        let location_tasks = definitions
13399                            .into_iter()
13400                            .map(|definition| match definition {
13401                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13402                                HoverLink::InlayHint(lsp_location, server_id) => editor
13403                                    .compute_target_location(lsp_location, server_id, window, cx),
13404                                HoverLink::Url(_) => Task::ready(Ok(None)),
13405                                HoverLink::File(_) => Task::ready(Ok(None)),
13406                            })
13407                            .collect::<Vec<_>>();
13408                        (title, location_tasks, editor.workspace().clone())
13409                    })
13410                    .context("location tasks preparation")?;
13411
13412                let locations = future::join_all(location_tasks)
13413                    .await
13414                    .into_iter()
13415                    .filter_map(|location| location.transpose())
13416                    .collect::<Result<_>>()
13417                    .context("location tasks")?;
13418
13419                let Some(workspace) = workspace else {
13420                    return Ok(Navigated::No);
13421                };
13422                let opened = workspace
13423                    .update_in(cx, |workspace, window, cx| {
13424                        Self::open_locations_in_multibuffer(
13425                            workspace,
13426                            locations,
13427                            title,
13428                            split,
13429                            MultibufferSelectionMode::First,
13430                            window,
13431                            cx,
13432                        )
13433                    })
13434                    .ok();
13435
13436                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13437            })
13438        } else {
13439            Task::ready(Ok(Navigated::No))
13440        }
13441    }
13442
13443    fn compute_target_location(
13444        &self,
13445        lsp_location: lsp::Location,
13446        server_id: LanguageServerId,
13447        window: &mut Window,
13448        cx: &mut Context<Self>,
13449    ) -> Task<anyhow::Result<Option<Location>>> {
13450        let Some(project) = self.project.clone() else {
13451            return Task::ready(Ok(None));
13452        };
13453
13454        cx.spawn_in(window, async move |editor, cx| {
13455            let location_task = editor.update(cx, |_, cx| {
13456                project.update(cx, |project, cx| {
13457                    let language_server_name = project
13458                        .language_server_statuses(cx)
13459                        .find(|(id, _)| server_id == *id)
13460                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13461                    language_server_name.map(|language_server_name| {
13462                        project.open_local_buffer_via_lsp(
13463                            lsp_location.uri.clone(),
13464                            server_id,
13465                            language_server_name,
13466                            cx,
13467                        )
13468                    })
13469                })
13470            })?;
13471            let location = match location_task {
13472                Some(task) => Some({
13473                    let target_buffer_handle = task.await.context("open local buffer")?;
13474                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13475                        let target_start = target_buffer
13476                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13477                        let target_end = target_buffer
13478                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13479                        target_buffer.anchor_after(target_start)
13480                            ..target_buffer.anchor_before(target_end)
13481                    })?;
13482                    Location {
13483                        buffer: target_buffer_handle,
13484                        range,
13485                    }
13486                }),
13487                None => None,
13488            };
13489            Ok(location)
13490        })
13491    }
13492
13493    pub fn find_all_references(
13494        &mut self,
13495        _: &FindAllReferences,
13496        window: &mut Window,
13497        cx: &mut Context<Self>,
13498    ) -> Option<Task<Result<Navigated>>> {
13499        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13500
13501        let selection = self.selections.newest::<usize>(cx);
13502        let multi_buffer = self.buffer.read(cx);
13503        let head = selection.head();
13504
13505        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13506        let head_anchor = multi_buffer_snapshot.anchor_at(
13507            head,
13508            if head < selection.tail() {
13509                Bias::Right
13510            } else {
13511                Bias::Left
13512            },
13513        );
13514
13515        match self
13516            .find_all_references_task_sources
13517            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13518        {
13519            Ok(_) => {
13520                log::info!(
13521                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13522                );
13523                return None;
13524            }
13525            Err(i) => {
13526                self.find_all_references_task_sources.insert(i, head_anchor);
13527            }
13528        }
13529
13530        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13531        let workspace = self.workspace()?;
13532        let project = workspace.read(cx).project().clone();
13533        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13534        Some(cx.spawn_in(window, async move |editor, cx| {
13535            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13536                if let Ok(i) = editor
13537                    .find_all_references_task_sources
13538                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13539                {
13540                    editor.find_all_references_task_sources.remove(i);
13541                }
13542            });
13543
13544            let locations = references.await?;
13545            if locations.is_empty() {
13546                return anyhow::Ok(Navigated::No);
13547            }
13548
13549            workspace.update_in(cx, |workspace, window, cx| {
13550                let title = locations
13551                    .first()
13552                    .as_ref()
13553                    .map(|location| {
13554                        let buffer = location.buffer.read(cx);
13555                        format!(
13556                            "References to `{}`",
13557                            buffer
13558                                .text_for_range(location.range.clone())
13559                                .collect::<String>()
13560                        )
13561                    })
13562                    .unwrap();
13563                Self::open_locations_in_multibuffer(
13564                    workspace,
13565                    locations,
13566                    title,
13567                    false,
13568                    MultibufferSelectionMode::First,
13569                    window,
13570                    cx,
13571                );
13572                Navigated::Yes
13573            })
13574        }))
13575    }
13576
13577    /// Opens a multibuffer with the given project locations in it
13578    pub fn open_locations_in_multibuffer(
13579        workspace: &mut Workspace,
13580        mut locations: Vec<Location>,
13581        title: String,
13582        split: bool,
13583        multibuffer_selection_mode: MultibufferSelectionMode,
13584        window: &mut Window,
13585        cx: &mut Context<Workspace>,
13586    ) {
13587        // If there are multiple definitions, open them in a multibuffer
13588        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13589        let mut locations = locations.into_iter().peekable();
13590        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13591        let capability = workspace.project().read(cx).capability();
13592
13593        let excerpt_buffer = cx.new(|cx| {
13594            let mut multibuffer = MultiBuffer::new(capability);
13595            while let Some(location) = locations.next() {
13596                let buffer = location.buffer.read(cx);
13597                let mut ranges_for_buffer = Vec::new();
13598                let range = location.range.to_point(buffer);
13599                ranges_for_buffer.push(range.clone());
13600
13601                while let Some(next_location) = locations.peek() {
13602                    if next_location.buffer == location.buffer {
13603                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13604                        locations.next();
13605                    } else {
13606                        break;
13607                    }
13608                }
13609
13610                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13611                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13612                    PathKey::for_buffer(&location.buffer, cx),
13613                    location.buffer.clone(),
13614                    ranges_for_buffer,
13615                    DEFAULT_MULTIBUFFER_CONTEXT,
13616                    cx,
13617                );
13618                ranges.extend(new_ranges)
13619            }
13620
13621            multibuffer.with_title(title)
13622        });
13623
13624        let editor = cx.new(|cx| {
13625            Editor::for_multibuffer(
13626                excerpt_buffer,
13627                Some(workspace.project().clone()),
13628                window,
13629                cx,
13630            )
13631        });
13632        editor.update(cx, |editor, cx| {
13633            match multibuffer_selection_mode {
13634                MultibufferSelectionMode::First => {
13635                    if let Some(first_range) = ranges.first() {
13636                        editor.change_selections(None, window, cx, |selections| {
13637                            selections.clear_disjoint();
13638                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13639                        });
13640                    }
13641                    editor.highlight_background::<Self>(
13642                        &ranges,
13643                        |theme| theme.editor_highlighted_line_background,
13644                        cx,
13645                    );
13646                }
13647                MultibufferSelectionMode::All => {
13648                    editor.change_selections(None, window, cx, |selections| {
13649                        selections.clear_disjoint();
13650                        selections.select_anchor_ranges(ranges);
13651                    });
13652                }
13653            }
13654            editor.register_buffers_with_language_servers(cx);
13655        });
13656
13657        let item = Box::new(editor);
13658        let item_id = item.item_id();
13659
13660        if split {
13661            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13662        } else {
13663            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13664                let (preview_item_id, preview_item_idx) =
13665                    workspace.active_pane().update(cx, |pane, _| {
13666                        (pane.preview_item_id(), pane.preview_item_idx())
13667                    });
13668
13669                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13670
13671                if let Some(preview_item_id) = preview_item_id {
13672                    workspace.active_pane().update(cx, |pane, cx| {
13673                        pane.remove_item(preview_item_id, false, false, window, cx);
13674                    });
13675                }
13676            } else {
13677                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13678            }
13679        }
13680        workspace.active_pane().update(cx, |pane, cx| {
13681            pane.set_preview_item_id(Some(item_id), cx);
13682        });
13683    }
13684
13685    pub fn rename(
13686        &mut self,
13687        _: &Rename,
13688        window: &mut Window,
13689        cx: &mut Context<Self>,
13690    ) -> Option<Task<Result<()>>> {
13691        use language::ToOffset as _;
13692
13693        let provider = self.semantics_provider.clone()?;
13694        let selection = self.selections.newest_anchor().clone();
13695        let (cursor_buffer, cursor_buffer_position) = self
13696            .buffer
13697            .read(cx)
13698            .text_anchor_for_position(selection.head(), cx)?;
13699        let (tail_buffer, cursor_buffer_position_end) = self
13700            .buffer
13701            .read(cx)
13702            .text_anchor_for_position(selection.tail(), cx)?;
13703        if tail_buffer != cursor_buffer {
13704            return None;
13705        }
13706
13707        let snapshot = cursor_buffer.read(cx).snapshot();
13708        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13709        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13710        let prepare_rename = provider
13711            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13712            .unwrap_or_else(|| Task::ready(Ok(None)));
13713        drop(snapshot);
13714
13715        Some(cx.spawn_in(window, async move |this, cx| {
13716            let rename_range = if let Some(range) = prepare_rename.await? {
13717                Some(range)
13718            } else {
13719                this.update(cx, |this, cx| {
13720                    let buffer = this.buffer.read(cx).snapshot(cx);
13721                    let mut buffer_highlights = this
13722                        .document_highlights_for_position(selection.head(), &buffer)
13723                        .filter(|highlight| {
13724                            highlight.start.excerpt_id == selection.head().excerpt_id
13725                                && highlight.end.excerpt_id == selection.head().excerpt_id
13726                        });
13727                    buffer_highlights
13728                        .next()
13729                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13730                })?
13731            };
13732            if let Some(rename_range) = rename_range {
13733                this.update_in(cx, |this, window, cx| {
13734                    let snapshot = cursor_buffer.read(cx).snapshot();
13735                    let rename_buffer_range = rename_range.to_offset(&snapshot);
13736                    let cursor_offset_in_rename_range =
13737                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13738                    let cursor_offset_in_rename_range_end =
13739                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13740
13741                    this.take_rename(false, window, cx);
13742                    let buffer = this.buffer.read(cx).read(cx);
13743                    let cursor_offset = selection.head().to_offset(&buffer);
13744                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13745                    let rename_end = rename_start + rename_buffer_range.len();
13746                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13747                    let mut old_highlight_id = None;
13748                    let old_name: Arc<str> = buffer
13749                        .chunks(rename_start..rename_end, true)
13750                        .map(|chunk| {
13751                            if old_highlight_id.is_none() {
13752                                old_highlight_id = chunk.syntax_highlight_id;
13753                            }
13754                            chunk.text
13755                        })
13756                        .collect::<String>()
13757                        .into();
13758
13759                    drop(buffer);
13760
13761                    // Position the selection in the rename editor so that it matches the current selection.
13762                    this.show_local_selections = false;
13763                    let rename_editor = cx.new(|cx| {
13764                        let mut editor = Editor::single_line(window, cx);
13765                        editor.buffer.update(cx, |buffer, cx| {
13766                            buffer.edit([(0..0, old_name.clone())], None, cx)
13767                        });
13768                        let rename_selection_range = match cursor_offset_in_rename_range
13769                            .cmp(&cursor_offset_in_rename_range_end)
13770                        {
13771                            Ordering::Equal => {
13772                                editor.select_all(&SelectAll, window, cx);
13773                                return editor;
13774                            }
13775                            Ordering::Less => {
13776                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13777                            }
13778                            Ordering::Greater => {
13779                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13780                            }
13781                        };
13782                        if rename_selection_range.end > old_name.len() {
13783                            editor.select_all(&SelectAll, window, cx);
13784                        } else {
13785                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13786                                s.select_ranges([rename_selection_range]);
13787                            });
13788                        }
13789                        editor
13790                    });
13791                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13792                        if e == &EditorEvent::Focused {
13793                            cx.emit(EditorEvent::FocusedIn)
13794                        }
13795                    })
13796                    .detach();
13797
13798                    let write_highlights =
13799                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13800                    let read_highlights =
13801                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
13802                    let ranges = write_highlights
13803                        .iter()
13804                        .flat_map(|(_, ranges)| ranges.iter())
13805                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13806                        .cloned()
13807                        .collect();
13808
13809                    this.highlight_text::<Rename>(
13810                        ranges,
13811                        HighlightStyle {
13812                            fade_out: Some(0.6),
13813                            ..Default::default()
13814                        },
13815                        cx,
13816                    );
13817                    let rename_focus_handle = rename_editor.focus_handle(cx);
13818                    window.focus(&rename_focus_handle);
13819                    let block_id = this.insert_blocks(
13820                        [BlockProperties {
13821                            style: BlockStyle::Flex,
13822                            placement: BlockPlacement::Below(range.start),
13823                            height: Some(1),
13824                            render: Arc::new({
13825                                let rename_editor = rename_editor.clone();
13826                                move |cx: &mut BlockContext| {
13827                                    let mut text_style = cx.editor_style.text.clone();
13828                                    if let Some(highlight_style) = old_highlight_id
13829                                        .and_then(|h| h.style(&cx.editor_style.syntax))
13830                                    {
13831                                        text_style = text_style.highlight(highlight_style);
13832                                    }
13833                                    div()
13834                                        .block_mouse_down()
13835                                        .pl(cx.anchor_x)
13836                                        .child(EditorElement::new(
13837                                            &rename_editor,
13838                                            EditorStyle {
13839                                                background: cx.theme().system().transparent,
13840                                                local_player: cx.editor_style.local_player,
13841                                                text: text_style,
13842                                                scrollbar_width: cx.editor_style.scrollbar_width,
13843                                                syntax: cx.editor_style.syntax.clone(),
13844                                                status: cx.editor_style.status.clone(),
13845                                                inlay_hints_style: HighlightStyle {
13846                                                    font_weight: Some(FontWeight::BOLD),
13847                                                    ..make_inlay_hints_style(cx.app)
13848                                                },
13849                                                inline_completion_styles: make_suggestion_styles(
13850                                                    cx.app,
13851                                                ),
13852                                                ..EditorStyle::default()
13853                                            },
13854                                        ))
13855                                        .into_any_element()
13856                                }
13857                            }),
13858                            priority: 0,
13859                        }],
13860                        Some(Autoscroll::fit()),
13861                        cx,
13862                    )[0];
13863                    this.pending_rename = Some(RenameState {
13864                        range,
13865                        old_name,
13866                        editor: rename_editor,
13867                        block_id,
13868                    });
13869                })?;
13870            }
13871
13872            Ok(())
13873        }))
13874    }
13875
13876    pub fn confirm_rename(
13877        &mut self,
13878        _: &ConfirmRename,
13879        window: &mut Window,
13880        cx: &mut Context<Self>,
13881    ) -> Option<Task<Result<()>>> {
13882        let rename = self.take_rename(false, window, cx)?;
13883        let workspace = self.workspace()?.downgrade();
13884        let (buffer, start) = self
13885            .buffer
13886            .read(cx)
13887            .text_anchor_for_position(rename.range.start, cx)?;
13888        let (end_buffer, _) = self
13889            .buffer
13890            .read(cx)
13891            .text_anchor_for_position(rename.range.end, cx)?;
13892        if buffer != end_buffer {
13893            return None;
13894        }
13895
13896        let old_name = rename.old_name;
13897        let new_name = rename.editor.read(cx).text(cx);
13898
13899        let rename = self.semantics_provider.as_ref()?.perform_rename(
13900            &buffer,
13901            start,
13902            new_name.clone(),
13903            cx,
13904        )?;
13905
13906        Some(cx.spawn_in(window, async move |editor, cx| {
13907            let project_transaction = rename.await?;
13908            Self::open_project_transaction(
13909                &editor,
13910                workspace,
13911                project_transaction,
13912                format!("Rename: {}{}", old_name, new_name),
13913                cx,
13914            )
13915            .await?;
13916
13917            editor.update(cx, |editor, cx| {
13918                editor.refresh_document_highlights(cx);
13919            })?;
13920            Ok(())
13921        }))
13922    }
13923
13924    fn take_rename(
13925        &mut self,
13926        moving_cursor: bool,
13927        window: &mut Window,
13928        cx: &mut Context<Self>,
13929    ) -> Option<RenameState> {
13930        let rename = self.pending_rename.take()?;
13931        if rename.editor.focus_handle(cx).is_focused(window) {
13932            window.focus(&self.focus_handle);
13933        }
13934
13935        self.remove_blocks(
13936            [rename.block_id].into_iter().collect(),
13937            Some(Autoscroll::fit()),
13938            cx,
13939        );
13940        self.clear_highlights::<Rename>(cx);
13941        self.show_local_selections = true;
13942
13943        if moving_cursor {
13944            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13945                editor.selections.newest::<usize>(cx).head()
13946            });
13947
13948            // Update the selection to match the position of the selection inside
13949            // the rename editor.
13950            let snapshot = self.buffer.read(cx).read(cx);
13951            let rename_range = rename.range.to_offset(&snapshot);
13952            let cursor_in_editor = snapshot
13953                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13954                .min(rename_range.end);
13955            drop(snapshot);
13956
13957            self.change_selections(None, window, cx, |s| {
13958                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13959            });
13960        } else {
13961            self.refresh_document_highlights(cx);
13962        }
13963
13964        Some(rename)
13965    }
13966
13967    pub fn pending_rename(&self) -> Option<&RenameState> {
13968        self.pending_rename.as_ref()
13969    }
13970
13971    fn format(
13972        &mut self,
13973        _: &Format,
13974        window: &mut Window,
13975        cx: &mut Context<Self>,
13976    ) -> Option<Task<Result<()>>> {
13977        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13978
13979        let project = match &self.project {
13980            Some(project) => project.clone(),
13981            None => return None,
13982        };
13983
13984        Some(self.perform_format(
13985            project,
13986            FormatTrigger::Manual,
13987            FormatTarget::Buffers,
13988            window,
13989            cx,
13990        ))
13991    }
13992
13993    fn format_selections(
13994        &mut self,
13995        _: &FormatSelections,
13996        window: &mut Window,
13997        cx: &mut Context<Self>,
13998    ) -> Option<Task<Result<()>>> {
13999        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14000
14001        let project = match &self.project {
14002            Some(project) => project.clone(),
14003            None => return None,
14004        };
14005
14006        let ranges = self
14007            .selections
14008            .all_adjusted(cx)
14009            .into_iter()
14010            .map(|selection| selection.range())
14011            .collect_vec();
14012
14013        Some(self.perform_format(
14014            project,
14015            FormatTrigger::Manual,
14016            FormatTarget::Ranges(ranges),
14017            window,
14018            cx,
14019        ))
14020    }
14021
14022    fn perform_format(
14023        &mut self,
14024        project: Entity<Project>,
14025        trigger: FormatTrigger,
14026        target: FormatTarget,
14027        window: &mut Window,
14028        cx: &mut Context<Self>,
14029    ) -> Task<Result<()>> {
14030        let buffer = self.buffer.clone();
14031        let (buffers, target) = match target {
14032            FormatTarget::Buffers => {
14033                let mut buffers = buffer.read(cx).all_buffers();
14034                if trigger == FormatTrigger::Save {
14035                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14036                }
14037                (buffers, LspFormatTarget::Buffers)
14038            }
14039            FormatTarget::Ranges(selection_ranges) => {
14040                let multi_buffer = buffer.read(cx);
14041                let snapshot = multi_buffer.read(cx);
14042                let mut buffers = HashSet::default();
14043                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14044                    BTreeMap::new();
14045                for selection_range in selection_ranges {
14046                    for (buffer, buffer_range, _) in
14047                        snapshot.range_to_buffer_ranges(selection_range)
14048                    {
14049                        let buffer_id = buffer.remote_id();
14050                        let start = buffer.anchor_before(buffer_range.start);
14051                        let end = buffer.anchor_after(buffer_range.end);
14052                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14053                        buffer_id_to_ranges
14054                            .entry(buffer_id)
14055                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14056                            .or_insert_with(|| vec![start..end]);
14057                    }
14058                }
14059                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14060            }
14061        };
14062
14063        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14064        let format = project.update(cx, |project, cx| {
14065            project.format(buffers, target, true, trigger, cx)
14066        });
14067
14068        cx.spawn_in(window, async move |_, cx| {
14069            let transaction = futures::select_biased! {
14070                transaction = format.log_err().fuse() => transaction,
14071                () = timeout => {
14072                    log::warn!("timed out waiting for formatting");
14073                    None
14074                }
14075            };
14076
14077            buffer
14078                .update(cx, |buffer, cx| {
14079                    if let Some(transaction) = transaction {
14080                        if !buffer.is_singleton() {
14081                            buffer.push_transaction(&transaction.0, cx);
14082                        }
14083                    }
14084                    cx.notify();
14085                })
14086                .ok();
14087
14088            Ok(())
14089        })
14090    }
14091
14092    fn organize_imports(
14093        &mut self,
14094        _: &OrganizeImports,
14095        window: &mut Window,
14096        cx: &mut Context<Self>,
14097    ) -> Option<Task<Result<()>>> {
14098        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14099        let project = match &self.project {
14100            Some(project) => project.clone(),
14101            None => return None,
14102        };
14103        Some(self.perform_code_action_kind(
14104            project,
14105            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14106            window,
14107            cx,
14108        ))
14109    }
14110
14111    fn perform_code_action_kind(
14112        &mut self,
14113        project: Entity<Project>,
14114        kind: CodeActionKind,
14115        window: &mut Window,
14116        cx: &mut Context<Self>,
14117    ) -> Task<Result<()>> {
14118        let buffer = self.buffer.clone();
14119        let buffers = buffer.read(cx).all_buffers();
14120        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14121        let apply_action = project.update(cx, |project, cx| {
14122            project.apply_code_action_kind(buffers, kind, true, cx)
14123        });
14124        cx.spawn_in(window, async move |_, cx| {
14125            let transaction = futures::select_biased! {
14126                () = timeout => {
14127                    log::warn!("timed out waiting for executing code action");
14128                    None
14129                }
14130                transaction = apply_action.log_err().fuse() => transaction,
14131            };
14132            buffer
14133                .update(cx, |buffer, cx| {
14134                    // check if we need this
14135                    if let Some(transaction) = transaction {
14136                        if !buffer.is_singleton() {
14137                            buffer.push_transaction(&transaction.0, cx);
14138                        }
14139                    }
14140                    cx.notify();
14141                })
14142                .ok();
14143            Ok(())
14144        })
14145    }
14146
14147    fn restart_language_server(
14148        &mut self,
14149        _: &RestartLanguageServer,
14150        _: &mut Window,
14151        cx: &mut Context<Self>,
14152    ) {
14153        if let Some(project) = self.project.clone() {
14154            self.buffer.update(cx, |multi_buffer, cx| {
14155                project.update(cx, |project, cx| {
14156                    project.restart_language_servers_for_buffers(
14157                        multi_buffer.all_buffers().into_iter().collect(),
14158                        cx,
14159                    );
14160                });
14161            })
14162        }
14163    }
14164
14165    fn stop_language_server(
14166        &mut self,
14167        _: &StopLanguageServer,
14168        _: &mut Window,
14169        cx: &mut Context<Self>,
14170    ) {
14171        if let Some(project) = self.project.clone() {
14172            self.buffer.update(cx, |multi_buffer, cx| {
14173                project.update(cx, |project, cx| {
14174                    project.stop_language_servers_for_buffers(
14175                        multi_buffer.all_buffers().into_iter().collect(),
14176                        cx,
14177                    );
14178                    cx.emit(project::Event::RefreshInlayHints);
14179                });
14180            });
14181        }
14182    }
14183
14184    fn cancel_language_server_work(
14185        workspace: &mut Workspace,
14186        _: &actions::CancelLanguageServerWork,
14187        _: &mut Window,
14188        cx: &mut Context<Workspace>,
14189    ) {
14190        let project = workspace.project();
14191        let buffers = workspace
14192            .active_item(cx)
14193            .and_then(|item| item.act_as::<Editor>(cx))
14194            .map_or(HashSet::default(), |editor| {
14195                editor.read(cx).buffer.read(cx).all_buffers()
14196            });
14197        project.update(cx, |project, cx| {
14198            project.cancel_language_server_work_for_buffers(buffers, cx);
14199        });
14200    }
14201
14202    fn show_character_palette(
14203        &mut self,
14204        _: &ShowCharacterPalette,
14205        window: &mut Window,
14206        _: &mut Context<Self>,
14207    ) {
14208        window.show_character_palette();
14209    }
14210
14211    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14212        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14213            let buffer = self.buffer.read(cx).snapshot(cx);
14214            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14215            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14216            let is_valid = buffer
14217                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14218                .any(|entry| {
14219                    entry.diagnostic.is_primary
14220                        && !entry.range.is_empty()
14221                        && entry.range.start == primary_range_start
14222                        && entry.diagnostic.message == active_diagnostics.primary_message
14223                });
14224
14225            if is_valid != active_diagnostics.is_valid {
14226                active_diagnostics.is_valid = is_valid;
14227                if is_valid {
14228                    let mut new_styles = HashMap::default();
14229                    for (block_id, diagnostic) in &active_diagnostics.blocks {
14230                        new_styles.insert(
14231                            *block_id,
14232                            diagnostic_block_renderer(diagnostic.clone(), None, true),
14233                        );
14234                    }
14235                    self.display_map.update(cx, |display_map, _cx| {
14236                        display_map.replace_blocks(new_styles);
14237                    });
14238                } else {
14239                    self.dismiss_diagnostics(cx);
14240                }
14241            }
14242        }
14243    }
14244
14245    fn activate_diagnostics(
14246        &mut self,
14247        buffer_id: BufferId,
14248        group_id: usize,
14249        window: &mut Window,
14250        cx: &mut Context<Self>,
14251    ) {
14252        self.dismiss_diagnostics(cx);
14253        let snapshot = self.snapshot(window, cx);
14254        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14255            let buffer = self.buffer.read(cx).snapshot(cx);
14256
14257            let mut primary_range = None;
14258            let mut primary_message = None;
14259            let diagnostic_group = buffer
14260                .diagnostic_group(buffer_id, group_id)
14261                .filter_map(|entry| {
14262                    let start = entry.range.start;
14263                    let end = entry.range.end;
14264                    if snapshot.is_line_folded(MultiBufferRow(start.row))
14265                        && (start.row == end.row
14266                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
14267                    {
14268                        return None;
14269                    }
14270                    if entry.diagnostic.is_primary {
14271                        primary_range = Some(entry.range.clone());
14272                        primary_message = Some(entry.diagnostic.message.clone());
14273                    }
14274                    Some(entry)
14275                })
14276                .collect::<Vec<_>>();
14277            let primary_range = primary_range?;
14278            let primary_message = primary_message?;
14279
14280            let blocks = display_map
14281                .insert_blocks(
14282                    diagnostic_group.iter().map(|entry| {
14283                        let diagnostic = entry.diagnostic.clone();
14284                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14285                        BlockProperties {
14286                            style: BlockStyle::Fixed,
14287                            placement: BlockPlacement::Below(
14288                                buffer.anchor_after(entry.range.start),
14289                            ),
14290                            height: Some(message_height),
14291                            render: diagnostic_block_renderer(diagnostic, None, true),
14292                            priority: 0,
14293                        }
14294                    }),
14295                    cx,
14296                )
14297                .into_iter()
14298                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14299                .collect();
14300
14301            Some(ActiveDiagnosticGroup {
14302                primary_range: buffer.anchor_before(primary_range.start)
14303                    ..buffer.anchor_after(primary_range.end),
14304                primary_message,
14305                group_id,
14306                blocks,
14307                is_valid: true,
14308            })
14309        });
14310    }
14311
14312    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14313        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14314            self.display_map.update(cx, |display_map, cx| {
14315                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14316            });
14317            cx.notify();
14318        }
14319    }
14320
14321    /// Disable inline diagnostics rendering for this editor.
14322    pub fn disable_inline_diagnostics(&mut self) {
14323        self.inline_diagnostics_enabled = false;
14324        self.inline_diagnostics_update = Task::ready(());
14325        self.inline_diagnostics.clear();
14326    }
14327
14328    pub fn inline_diagnostics_enabled(&self) -> bool {
14329        self.inline_diagnostics_enabled
14330    }
14331
14332    pub fn show_inline_diagnostics(&self) -> bool {
14333        self.show_inline_diagnostics
14334    }
14335
14336    pub fn toggle_inline_diagnostics(
14337        &mut self,
14338        _: &ToggleInlineDiagnostics,
14339        window: &mut Window,
14340        cx: &mut Context<Editor>,
14341    ) {
14342        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14343        self.refresh_inline_diagnostics(false, window, cx);
14344    }
14345
14346    fn refresh_inline_diagnostics(
14347        &mut self,
14348        debounce: bool,
14349        window: &mut Window,
14350        cx: &mut Context<Self>,
14351    ) {
14352        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14353            self.inline_diagnostics_update = Task::ready(());
14354            self.inline_diagnostics.clear();
14355            return;
14356        }
14357
14358        let debounce_ms = ProjectSettings::get_global(cx)
14359            .diagnostics
14360            .inline
14361            .update_debounce_ms;
14362        let debounce = if debounce && debounce_ms > 0 {
14363            Some(Duration::from_millis(debounce_ms))
14364        } else {
14365            None
14366        };
14367        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14368            if let Some(debounce) = debounce {
14369                cx.background_executor().timer(debounce).await;
14370            }
14371            let Some(snapshot) = editor
14372                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14373                .ok()
14374            else {
14375                return;
14376            };
14377
14378            let new_inline_diagnostics = cx
14379                .background_spawn(async move {
14380                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14381                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14382                        let message = diagnostic_entry
14383                            .diagnostic
14384                            .message
14385                            .split_once('\n')
14386                            .map(|(line, _)| line)
14387                            .map(SharedString::new)
14388                            .unwrap_or_else(|| {
14389                                SharedString::from(diagnostic_entry.diagnostic.message)
14390                            });
14391                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14392                        let (Ok(i) | Err(i)) = inline_diagnostics
14393                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14394                        inline_diagnostics.insert(
14395                            i,
14396                            (
14397                                start_anchor,
14398                                InlineDiagnostic {
14399                                    message,
14400                                    group_id: diagnostic_entry.diagnostic.group_id,
14401                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14402                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14403                                    severity: diagnostic_entry.diagnostic.severity,
14404                                },
14405                            ),
14406                        );
14407                    }
14408                    inline_diagnostics
14409                })
14410                .await;
14411
14412            editor
14413                .update(cx, |editor, cx| {
14414                    editor.inline_diagnostics = new_inline_diagnostics;
14415                    cx.notify();
14416                })
14417                .ok();
14418        });
14419    }
14420
14421    pub fn set_selections_from_remote(
14422        &mut self,
14423        selections: Vec<Selection<Anchor>>,
14424        pending_selection: Option<Selection<Anchor>>,
14425        window: &mut Window,
14426        cx: &mut Context<Self>,
14427    ) {
14428        let old_cursor_position = self.selections.newest_anchor().head();
14429        self.selections.change_with(cx, |s| {
14430            s.select_anchors(selections);
14431            if let Some(pending_selection) = pending_selection {
14432                s.set_pending(pending_selection, SelectMode::Character);
14433            } else {
14434                s.clear_pending();
14435            }
14436        });
14437        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14438    }
14439
14440    fn push_to_selection_history(&mut self) {
14441        self.selection_history.push(SelectionHistoryEntry {
14442            selections: self.selections.disjoint_anchors(),
14443            select_next_state: self.select_next_state.clone(),
14444            select_prev_state: self.select_prev_state.clone(),
14445            add_selections_state: self.add_selections_state.clone(),
14446        });
14447    }
14448
14449    pub fn transact(
14450        &mut self,
14451        window: &mut Window,
14452        cx: &mut Context<Self>,
14453        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14454    ) -> Option<TransactionId> {
14455        self.start_transaction_at(Instant::now(), window, cx);
14456        update(self, window, cx);
14457        self.end_transaction_at(Instant::now(), cx)
14458    }
14459
14460    pub fn start_transaction_at(
14461        &mut self,
14462        now: Instant,
14463        window: &mut Window,
14464        cx: &mut Context<Self>,
14465    ) {
14466        self.end_selection(window, cx);
14467        if let Some(tx_id) = self
14468            .buffer
14469            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14470        {
14471            self.selection_history
14472                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14473            cx.emit(EditorEvent::TransactionBegun {
14474                transaction_id: tx_id,
14475            })
14476        }
14477    }
14478
14479    pub fn end_transaction_at(
14480        &mut self,
14481        now: Instant,
14482        cx: &mut Context<Self>,
14483    ) -> Option<TransactionId> {
14484        if let Some(transaction_id) = self
14485            .buffer
14486            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14487        {
14488            if let Some((_, end_selections)) =
14489                self.selection_history.transaction_mut(transaction_id)
14490            {
14491                *end_selections = Some(self.selections.disjoint_anchors());
14492            } else {
14493                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14494            }
14495
14496            cx.emit(EditorEvent::Edited { transaction_id });
14497            Some(transaction_id)
14498        } else {
14499            None
14500        }
14501    }
14502
14503    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14504        if self.selection_mark_mode {
14505            self.change_selections(None, window, cx, |s| {
14506                s.move_with(|_, sel| {
14507                    sel.collapse_to(sel.head(), SelectionGoal::None);
14508                });
14509            })
14510        }
14511        self.selection_mark_mode = true;
14512        cx.notify();
14513    }
14514
14515    pub fn swap_selection_ends(
14516        &mut self,
14517        _: &actions::SwapSelectionEnds,
14518        window: &mut Window,
14519        cx: &mut Context<Self>,
14520    ) {
14521        self.change_selections(None, window, cx, |s| {
14522            s.move_with(|_, sel| {
14523                if sel.start != sel.end {
14524                    sel.reversed = !sel.reversed
14525                }
14526            });
14527        });
14528        self.request_autoscroll(Autoscroll::newest(), cx);
14529        cx.notify();
14530    }
14531
14532    pub fn toggle_fold(
14533        &mut self,
14534        _: &actions::ToggleFold,
14535        window: &mut Window,
14536        cx: &mut Context<Self>,
14537    ) {
14538        if self.is_singleton(cx) {
14539            let selection = self.selections.newest::<Point>(cx);
14540
14541            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14542            let range = if selection.is_empty() {
14543                let point = selection.head().to_display_point(&display_map);
14544                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14545                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14546                    .to_point(&display_map);
14547                start..end
14548            } else {
14549                selection.range()
14550            };
14551            if display_map.folds_in_range(range).next().is_some() {
14552                self.unfold_lines(&Default::default(), window, cx)
14553            } else {
14554                self.fold(&Default::default(), window, cx)
14555            }
14556        } else {
14557            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14558            let buffer_ids: HashSet<_> = self
14559                .selections
14560                .disjoint_anchor_ranges()
14561                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14562                .collect();
14563
14564            let should_unfold = buffer_ids
14565                .iter()
14566                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14567
14568            for buffer_id in buffer_ids {
14569                if should_unfold {
14570                    self.unfold_buffer(buffer_id, cx);
14571                } else {
14572                    self.fold_buffer(buffer_id, cx);
14573                }
14574            }
14575        }
14576    }
14577
14578    pub fn toggle_fold_recursive(
14579        &mut self,
14580        _: &actions::ToggleFoldRecursive,
14581        window: &mut Window,
14582        cx: &mut Context<Self>,
14583    ) {
14584        let selection = self.selections.newest::<Point>(cx);
14585
14586        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14587        let range = if selection.is_empty() {
14588            let point = selection.head().to_display_point(&display_map);
14589            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14590            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14591                .to_point(&display_map);
14592            start..end
14593        } else {
14594            selection.range()
14595        };
14596        if display_map.folds_in_range(range).next().is_some() {
14597            self.unfold_recursive(&Default::default(), window, cx)
14598        } else {
14599            self.fold_recursive(&Default::default(), window, cx)
14600        }
14601    }
14602
14603    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14604        if self.is_singleton(cx) {
14605            let mut to_fold = Vec::new();
14606            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14607            let selections = self.selections.all_adjusted(cx);
14608
14609            for selection in selections {
14610                let range = selection.range().sorted();
14611                let buffer_start_row = range.start.row;
14612
14613                if range.start.row != range.end.row {
14614                    let mut found = false;
14615                    let mut row = range.start.row;
14616                    while row <= range.end.row {
14617                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14618                        {
14619                            found = true;
14620                            row = crease.range().end.row + 1;
14621                            to_fold.push(crease);
14622                        } else {
14623                            row += 1
14624                        }
14625                    }
14626                    if found {
14627                        continue;
14628                    }
14629                }
14630
14631                for row in (0..=range.start.row).rev() {
14632                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14633                        if crease.range().end.row >= buffer_start_row {
14634                            to_fold.push(crease);
14635                            if row <= range.start.row {
14636                                break;
14637                            }
14638                        }
14639                    }
14640                }
14641            }
14642
14643            self.fold_creases(to_fold, true, window, cx);
14644        } else {
14645            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14646            let buffer_ids = self
14647                .selections
14648                .disjoint_anchor_ranges()
14649                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14650                .collect::<HashSet<_>>();
14651            for buffer_id in buffer_ids {
14652                self.fold_buffer(buffer_id, cx);
14653            }
14654        }
14655    }
14656
14657    fn fold_at_level(
14658        &mut self,
14659        fold_at: &FoldAtLevel,
14660        window: &mut Window,
14661        cx: &mut Context<Self>,
14662    ) {
14663        if !self.buffer.read(cx).is_singleton() {
14664            return;
14665        }
14666
14667        let fold_at_level = fold_at.0;
14668        let snapshot = self.buffer.read(cx).snapshot(cx);
14669        let mut to_fold = Vec::new();
14670        let mut stack = vec![(0, snapshot.max_row().0, 1)];
14671
14672        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14673            while start_row < end_row {
14674                match self
14675                    .snapshot(window, cx)
14676                    .crease_for_buffer_row(MultiBufferRow(start_row))
14677                {
14678                    Some(crease) => {
14679                        let nested_start_row = crease.range().start.row + 1;
14680                        let nested_end_row = crease.range().end.row;
14681
14682                        if current_level < fold_at_level {
14683                            stack.push((nested_start_row, nested_end_row, current_level + 1));
14684                        } else if current_level == fold_at_level {
14685                            to_fold.push(crease);
14686                        }
14687
14688                        start_row = nested_end_row + 1;
14689                    }
14690                    None => start_row += 1,
14691                }
14692            }
14693        }
14694
14695        self.fold_creases(to_fold, true, window, cx);
14696    }
14697
14698    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14699        if self.buffer.read(cx).is_singleton() {
14700            let mut fold_ranges = Vec::new();
14701            let snapshot = self.buffer.read(cx).snapshot(cx);
14702
14703            for row in 0..snapshot.max_row().0 {
14704                if let Some(foldable_range) = self
14705                    .snapshot(window, cx)
14706                    .crease_for_buffer_row(MultiBufferRow(row))
14707                {
14708                    fold_ranges.push(foldable_range);
14709                }
14710            }
14711
14712            self.fold_creases(fold_ranges, true, window, cx);
14713        } else {
14714            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14715                editor
14716                    .update_in(cx, |editor, _, cx| {
14717                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14718                            editor.fold_buffer(buffer_id, cx);
14719                        }
14720                    })
14721                    .ok();
14722            });
14723        }
14724    }
14725
14726    pub fn fold_function_bodies(
14727        &mut self,
14728        _: &actions::FoldFunctionBodies,
14729        window: &mut Window,
14730        cx: &mut Context<Self>,
14731    ) {
14732        let snapshot = self.buffer.read(cx).snapshot(cx);
14733
14734        let ranges = snapshot
14735            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14736            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14737            .collect::<Vec<_>>();
14738
14739        let creases = ranges
14740            .into_iter()
14741            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14742            .collect();
14743
14744        self.fold_creases(creases, true, window, cx);
14745    }
14746
14747    pub fn fold_recursive(
14748        &mut self,
14749        _: &actions::FoldRecursive,
14750        window: &mut Window,
14751        cx: &mut Context<Self>,
14752    ) {
14753        let mut to_fold = Vec::new();
14754        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14755        let selections = self.selections.all_adjusted(cx);
14756
14757        for selection in selections {
14758            let range = selection.range().sorted();
14759            let buffer_start_row = range.start.row;
14760
14761            if range.start.row != range.end.row {
14762                let mut found = false;
14763                for row in range.start.row..=range.end.row {
14764                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14765                        found = true;
14766                        to_fold.push(crease);
14767                    }
14768                }
14769                if found {
14770                    continue;
14771                }
14772            }
14773
14774            for row in (0..=range.start.row).rev() {
14775                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14776                    if crease.range().end.row >= buffer_start_row {
14777                        to_fold.push(crease);
14778                    } else {
14779                        break;
14780                    }
14781                }
14782            }
14783        }
14784
14785        self.fold_creases(to_fold, true, window, cx);
14786    }
14787
14788    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14789        let buffer_row = fold_at.buffer_row;
14790        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14791
14792        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14793            let autoscroll = self
14794                .selections
14795                .all::<Point>(cx)
14796                .iter()
14797                .any(|selection| crease.range().overlaps(&selection.range()));
14798
14799            self.fold_creases(vec![crease], autoscroll, window, cx);
14800        }
14801    }
14802
14803    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14804        if self.is_singleton(cx) {
14805            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14806            let buffer = &display_map.buffer_snapshot;
14807            let selections = self.selections.all::<Point>(cx);
14808            let ranges = selections
14809                .iter()
14810                .map(|s| {
14811                    let range = s.display_range(&display_map).sorted();
14812                    let mut start = range.start.to_point(&display_map);
14813                    let mut end = range.end.to_point(&display_map);
14814                    start.column = 0;
14815                    end.column = buffer.line_len(MultiBufferRow(end.row));
14816                    start..end
14817                })
14818                .collect::<Vec<_>>();
14819
14820            self.unfold_ranges(&ranges, true, true, cx);
14821        } else {
14822            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14823            let buffer_ids = self
14824                .selections
14825                .disjoint_anchor_ranges()
14826                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14827                .collect::<HashSet<_>>();
14828            for buffer_id in buffer_ids {
14829                self.unfold_buffer(buffer_id, cx);
14830            }
14831        }
14832    }
14833
14834    pub fn unfold_recursive(
14835        &mut self,
14836        _: &UnfoldRecursive,
14837        _window: &mut Window,
14838        cx: &mut Context<Self>,
14839    ) {
14840        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14841        let selections = self.selections.all::<Point>(cx);
14842        let ranges = selections
14843            .iter()
14844            .map(|s| {
14845                let mut range = s.display_range(&display_map).sorted();
14846                *range.start.column_mut() = 0;
14847                *range.end.column_mut() = display_map.line_len(range.end.row());
14848                let start = range.start.to_point(&display_map);
14849                let end = range.end.to_point(&display_map);
14850                start..end
14851            })
14852            .collect::<Vec<_>>();
14853
14854        self.unfold_ranges(&ranges, true, true, cx);
14855    }
14856
14857    pub fn unfold_at(
14858        &mut self,
14859        unfold_at: &UnfoldAt,
14860        _window: &mut Window,
14861        cx: &mut Context<Self>,
14862    ) {
14863        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14864
14865        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14866            ..Point::new(
14867                unfold_at.buffer_row.0,
14868                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14869            );
14870
14871        let autoscroll = self
14872            .selections
14873            .all::<Point>(cx)
14874            .iter()
14875            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14876
14877        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14878    }
14879
14880    pub fn unfold_all(
14881        &mut self,
14882        _: &actions::UnfoldAll,
14883        _window: &mut Window,
14884        cx: &mut Context<Self>,
14885    ) {
14886        if self.buffer.read(cx).is_singleton() {
14887            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14888            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14889        } else {
14890            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14891                editor
14892                    .update(cx, |editor, cx| {
14893                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14894                            editor.unfold_buffer(buffer_id, cx);
14895                        }
14896                    })
14897                    .ok();
14898            });
14899        }
14900    }
14901
14902    pub fn fold_selected_ranges(
14903        &mut self,
14904        _: &FoldSelectedRanges,
14905        window: &mut Window,
14906        cx: &mut Context<Self>,
14907    ) {
14908        let selections = self.selections.all_adjusted(cx);
14909        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14910        let ranges = selections
14911            .into_iter()
14912            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
14913            .collect::<Vec<_>>();
14914        self.fold_creases(ranges, true, window, cx);
14915    }
14916
14917    pub fn fold_ranges<T: ToOffset + Clone>(
14918        &mut self,
14919        ranges: Vec<Range<T>>,
14920        auto_scroll: bool,
14921        window: &mut Window,
14922        cx: &mut Context<Self>,
14923    ) {
14924        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14925        let ranges = ranges
14926            .into_iter()
14927            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14928            .collect::<Vec<_>>();
14929        self.fold_creases(ranges, auto_scroll, window, cx);
14930    }
14931
14932    pub fn fold_creases<T: ToOffset + Clone>(
14933        &mut self,
14934        creases: Vec<Crease<T>>,
14935        auto_scroll: bool,
14936        window: &mut Window,
14937        cx: &mut Context<Self>,
14938    ) {
14939        if creases.is_empty() {
14940            return;
14941        }
14942
14943        let mut buffers_affected = HashSet::default();
14944        let multi_buffer = self.buffer().read(cx);
14945        for crease in &creases {
14946            if let Some((_, buffer, _)) =
14947                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14948            {
14949                buffers_affected.insert(buffer.read(cx).remote_id());
14950            };
14951        }
14952
14953        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14954
14955        if auto_scroll {
14956            self.request_autoscroll(Autoscroll::fit(), cx);
14957        }
14958
14959        cx.notify();
14960
14961        if let Some(active_diagnostics) = self.active_diagnostics.take() {
14962            // Clear diagnostics block when folding a range that contains it.
14963            let snapshot = self.snapshot(window, cx);
14964            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14965                drop(snapshot);
14966                self.active_diagnostics = Some(active_diagnostics);
14967                self.dismiss_diagnostics(cx);
14968            } else {
14969                self.active_diagnostics = Some(active_diagnostics);
14970            }
14971        }
14972
14973        self.scrollbar_marker_state.dirty = true;
14974        self.folds_did_change(cx);
14975    }
14976
14977    /// Removes any folds whose ranges intersect any of the given ranges.
14978    pub fn unfold_ranges<T: ToOffset + Clone>(
14979        &mut self,
14980        ranges: &[Range<T>],
14981        inclusive: bool,
14982        auto_scroll: bool,
14983        cx: &mut Context<Self>,
14984    ) {
14985        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14986            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14987        });
14988        self.folds_did_change(cx);
14989    }
14990
14991    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14992        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14993            return;
14994        }
14995        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14996        self.display_map.update(cx, |display_map, cx| {
14997            display_map.fold_buffers([buffer_id], cx)
14998        });
14999        cx.emit(EditorEvent::BufferFoldToggled {
15000            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15001            folded: true,
15002        });
15003        cx.notify();
15004    }
15005
15006    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15007        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15008            return;
15009        }
15010        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15011        self.display_map.update(cx, |display_map, cx| {
15012            display_map.unfold_buffers([buffer_id], cx);
15013        });
15014        cx.emit(EditorEvent::BufferFoldToggled {
15015            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15016            folded: false,
15017        });
15018        cx.notify();
15019    }
15020
15021    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15022        self.display_map.read(cx).is_buffer_folded(buffer)
15023    }
15024
15025    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15026        self.display_map.read(cx).folded_buffers()
15027    }
15028
15029    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15030        self.display_map.update(cx, |display_map, cx| {
15031            display_map.disable_header_for_buffer(buffer_id, cx);
15032        });
15033        cx.notify();
15034    }
15035
15036    /// Removes any folds with the given ranges.
15037    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15038        &mut self,
15039        ranges: &[Range<T>],
15040        type_id: TypeId,
15041        auto_scroll: bool,
15042        cx: &mut Context<Self>,
15043    ) {
15044        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15045            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15046        });
15047        self.folds_did_change(cx);
15048    }
15049
15050    fn remove_folds_with<T: ToOffset + Clone>(
15051        &mut self,
15052        ranges: &[Range<T>],
15053        auto_scroll: bool,
15054        cx: &mut Context<Self>,
15055        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15056    ) {
15057        if ranges.is_empty() {
15058            return;
15059        }
15060
15061        let mut buffers_affected = HashSet::default();
15062        let multi_buffer = self.buffer().read(cx);
15063        for range in ranges {
15064            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15065                buffers_affected.insert(buffer.read(cx).remote_id());
15066            };
15067        }
15068
15069        self.display_map.update(cx, update);
15070
15071        if auto_scroll {
15072            self.request_autoscroll(Autoscroll::fit(), cx);
15073        }
15074
15075        cx.notify();
15076        self.scrollbar_marker_state.dirty = true;
15077        self.active_indent_guides_state.dirty = true;
15078    }
15079
15080    pub fn update_fold_widths(
15081        &mut self,
15082        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15083        cx: &mut Context<Self>,
15084    ) -> bool {
15085        self.display_map
15086            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15087    }
15088
15089    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15090        self.display_map.read(cx).fold_placeholder.clone()
15091    }
15092
15093    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15094        self.buffer.update(cx, |buffer, cx| {
15095            buffer.set_all_diff_hunks_expanded(cx);
15096        });
15097    }
15098
15099    pub fn expand_all_diff_hunks(
15100        &mut self,
15101        _: &ExpandAllDiffHunks,
15102        _window: &mut Window,
15103        cx: &mut Context<Self>,
15104    ) {
15105        self.buffer.update(cx, |buffer, cx| {
15106            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15107        });
15108    }
15109
15110    pub fn toggle_selected_diff_hunks(
15111        &mut self,
15112        _: &ToggleSelectedDiffHunks,
15113        _window: &mut Window,
15114        cx: &mut Context<Self>,
15115    ) {
15116        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15117        self.toggle_diff_hunks_in_ranges(ranges, cx);
15118    }
15119
15120    pub fn diff_hunks_in_ranges<'a>(
15121        &'a self,
15122        ranges: &'a [Range<Anchor>],
15123        buffer: &'a MultiBufferSnapshot,
15124    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15125        ranges.iter().flat_map(move |range| {
15126            let end_excerpt_id = range.end.excerpt_id;
15127            let range = range.to_point(buffer);
15128            let mut peek_end = range.end;
15129            if range.end.row < buffer.max_row().0 {
15130                peek_end = Point::new(range.end.row + 1, 0);
15131            }
15132            buffer
15133                .diff_hunks_in_range(range.start..peek_end)
15134                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15135        })
15136    }
15137
15138    pub fn has_stageable_diff_hunks_in_ranges(
15139        &self,
15140        ranges: &[Range<Anchor>],
15141        snapshot: &MultiBufferSnapshot,
15142    ) -> bool {
15143        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15144        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15145    }
15146
15147    pub fn toggle_staged_selected_diff_hunks(
15148        &mut self,
15149        _: &::git::ToggleStaged,
15150        _: &mut Window,
15151        cx: &mut Context<Self>,
15152    ) {
15153        let snapshot = self.buffer.read(cx).snapshot(cx);
15154        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15155        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15156        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15157    }
15158
15159    pub fn set_render_diff_hunk_controls(
15160        &mut self,
15161        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15162        cx: &mut Context<Self>,
15163    ) {
15164        self.render_diff_hunk_controls = render_diff_hunk_controls;
15165        cx.notify();
15166    }
15167
15168    pub fn stage_and_next(
15169        &mut self,
15170        _: &::git::StageAndNext,
15171        window: &mut Window,
15172        cx: &mut Context<Self>,
15173    ) {
15174        self.do_stage_or_unstage_and_next(true, window, cx);
15175    }
15176
15177    pub fn unstage_and_next(
15178        &mut self,
15179        _: &::git::UnstageAndNext,
15180        window: &mut Window,
15181        cx: &mut Context<Self>,
15182    ) {
15183        self.do_stage_or_unstage_and_next(false, window, cx);
15184    }
15185
15186    pub fn stage_or_unstage_diff_hunks(
15187        &mut self,
15188        stage: bool,
15189        ranges: Vec<Range<Anchor>>,
15190        cx: &mut Context<Self>,
15191    ) {
15192        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15193        cx.spawn(async move |this, cx| {
15194            task.await?;
15195            this.update(cx, |this, cx| {
15196                let snapshot = this.buffer.read(cx).snapshot(cx);
15197                let chunk_by = this
15198                    .diff_hunks_in_ranges(&ranges, &snapshot)
15199                    .chunk_by(|hunk| hunk.buffer_id);
15200                for (buffer_id, hunks) in &chunk_by {
15201                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15202                }
15203            })
15204        })
15205        .detach_and_log_err(cx);
15206    }
15207
15208    fn save_buffers_for_ranges_if_needed(
15209        &mut self,
15210        ranges: &[Range<Anchor>],
15211        cx: &mut Context<Editor>,
15212    ) -> Task<Result<()>> {
15213        let multibuffer = self.buffer.read(cx);
15214        let snapshot = multibuffer.read(cx);
15215        let buffer_ids: HashSet<_> = ranges
15216            .iter()
15217            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15218            .collect();
15219        drop(snapshot);
15220
15221        let mut buffers = HashSet::default();
15222        for buffer_id in buffer_ids {
15223            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15224                let buffer = buffer_entity.read(cx);
15225                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15226                {
15227                    buffers.insert(buffer_entity);
15228                }
15229            }
15230        }
15231
15232        if let Some(project) = &self.project {
15233            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15234        } else {
15235            Task::ready(Ok(()))
15236        }
15237    }
15238
15239    fn do_stage_or_unstage_and_next(
15240        &mut self,
15241        stage: bool,
15242        window: &mut Window,
15243        cx: &mut Context<Self>,
15244    ) {
15245        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15246
15247        if ranges.iter().any(|range| range.start != range.end) {
15248            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15249            return;
15250        }
15251
15252        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15253        let snapshot = self.snapshot(window, cx);
15254        let position = self.selections.newest::<Point>(cx).head();
15255        let mut row = snapshot
15256            .buffer_snapshot
15257            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15258            .find(|hunk| hunk.row_range.start.0 > position.row)
15259            .map(|hunk| hunk.row_range.start);
15260
15261        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15262        // Outside of the project diff editor, wrap around to the beginning.
15263        if !all_diff_hunks_expanded {
15264            row = row.or_else(|| {
15265                snapshot
15266                    .buffer_snapshot
15267                    .diff_hunks_in_range(Point::zero()..position)
15268                    .find(|hunk| hunk.row_range.end.0 < position.row)
15269                    .map(|hunk| hunk.row_range.start)
15270            });
15271        }
15272
15273        if let Some(row) = row {
15274            let destination = Point::new(row.0, 0);
15275            let autoscroll = Autoscroll::center();
15276
15277            self.unfold_ranges(&[destination..destination], false, false, cx);
15278            self.change_selections(Some(autoscroll), window, cx, |s| {
15279                s.select_ranges([destination..destination]);
15280            });
15281        }
15282    }
15283
15284    fn do_stage_or_unstage(
15285        &self,
15286        stage: bool,
15287        buffer_id: BufferId,
15288        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15289        cx: &mut App,
15290    ) -> Option<()> {
15291        let project = self.project.as_ref()?;
15292        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15293        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15294        let buffer_snapshot = buffer.read(cx).snapshot();
15295        let file_exists = buffer_snapshot
15296            .file()
15297            .is_some_and(|file| file.disk_state().exists());
15298        diff.update(cx, |diff, cx| {
15299            diff.stage_or_unstage_hunks(
15300                stage,
15301                &hunks
15302                    .map(|hunk| buffer_diff::DiffHunk {
15303                        buffer_range: hunk.buffer_range,
15304                        diff_base_byte_range: hunk.diff_base_byte_range,
15305                        secondary_status: hunk.secondary_status,
15306                        range: Point::zero()..Point::zero(), // unused
15307                    })
15308                    .collect::<Vec<_>>(),
15309                &buffer_snapshot,
15310                file_exists,
15311                cx,
15312            )
15313        });
15314        None
15315    }
15316
15317    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15318        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15319        self.buffer
15320            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15321    }
15322
15323    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15324        self.buffer.update(cx, |buffer, cx| {
15325            let ranges = vec![Anchor::min()..Anchor::max()];
15326            if !buffer.all_diff_hunks_expanded()
15327                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15328            {
15329                buffer.collapse_diff_hunks(ranges, cx);
15330                true
15331            } else {
15332                false
15333            }
15334        })
15335    }
15336
15337    fn toggle_diff_hunks_in_ranges(
15338        &mut self,
15339        ranges: Vec<Range<Anchor>>,
15340        cx: &mut Context<Editor>,
15341    ) {
15342        self.buffer.update(cx, |buffer, cx| {
15343            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15344            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15345        })
15346    }
15347
15348    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15349        self.buffer.update(cx, |buffer, cx| {
15350            let snapshot = buffer.snapshot(cx);
15351            let excerpt_id = range.end.excerpt_id;
15352            let point_range = range.to_point(&snapshot);
15353            let expand = !buffer.single_hunk_is_expanded(range, cx);
15354            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15355        })
15356    }
15357
15358    pub(crate) fn apply_all_diff_hunks(
15359        &mut self,
15360        _: &ApplyAllDiffHunks,
15361        window: &mut Window,
15362        cx: &mut Context<Self>,
15363    ) {
15364        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15365
15366        let buffers = self.buffer.read(cx).all_buffers();
15367        for branch_buffer in buffers {
15368            branch_buffer.update(cx, |branch_buffer, cx| {
15369                branch_buffer.merge_into_base(Vec::new(), cx);
15370            });
15371        }
15372
15373        if let Some(project) = self.project.clone() {
15374            self.save(true, project, window, cx).detach_and_log_err(cx);
15375        }
15376    }
15377
15378    pub(crate) fn apply_selected_diff_hunks(
15379        &mut self,
15380        _: &ApplyDiffHunk,
15381        window: &mut Window,
15382        cx: &mut Context<Self>,
15383    ) {
15384        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15385        let snapshot = self.snapshot(window, cx);
15386        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15387        let mut ranges_by_buffer = HashMap::default();
15388        self.transact(window, cx, |editor, _window, cx| {
15389            for hunk in hunks {
15390                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15391                    ranges_by_buffer
15392                        .entry(buffer.clone())
15393                        .or_insert_with(Vec::new)
15394                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15395                }
15396            }
15397
15398            for (buffer, ranges) in ranges_by_buffer {
15399                buffer.update(cx, |buffer, cx| {
15400                    buffer.merge_into_base(ranges, cx);
15401                });
15402            }
15403        });
15404
15405        if let Some(project) = self.project.clone() {
15406            self.save(true, project, window, cx).detach_and_log_err(cx);
15407        }
15408    }
15409
15410    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15411        if hovered != self.gutter_hovered {
15412            self.gutter_hovered = hovered;
15413            cx.notify();
15414        }
15415    }
15416
15417    pub fn insert_blocks(
15418        &mut self,
15419        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15420        autoscroll: Option<Autoscroll>,
15421        cx: &mut Context<Self>,
15422    ) -> Vec<CustomBlockId> {
15423        let blocks = self
15424            .display_map
15425            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15426        if let Some(autoscroll) = autoscroll {
15427            self.request_autoscroll(autoscroll, cx);
15428        }
15429        cx.notify();
15430        blocks
15431    }
15432
15433    pub fn resize_blocks(
15434        &mut self,
15435        heights: HashMap<CustomBlockId, u32>,
15436        autoscroll: Option<Autoscroll>,
15437        cx: &mut Context<Self>,
15438    ) {
15439        self.display_map
15440            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15441        if let Some(autoscroll) = autoscroll {
15442            self.request_autoscroll(autoscroll, cx);
15443        }
15444        cx.notify();
15445    }
15446
15447    pub fn replace_blocks(
15448        &mut self,
15449        renderers: HashMap<CustomBlockId, RenderBlock>,
15450        autoscroll: Option<Autoscroll>,
15451        cx: &mut Context<Self>,
15452    ) {
15453        self.display_map
15454            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15455        if let Some(autoscroll) = autoscroll {
15456            self.request_autoscroll(autoscroll, cx);
15457        }
15458        cx.notify();
15459    }
15460
15461    pub fn remove_blocks(
15462        &mut self,
15463        block_ids: HashSet<CustomBlockId>,
15464        autoscroll: Option<Autoscroll>,
15465        cx: &mut Context<Self>,
15466    ) {
15467        self.display_map.update(cx, |display_map, cx| {
15468            display_map.remove_blocks(block_ids, cx)
15469        });
15470        if let Some(autoscroll) = autoscroll {
15471            self.request_autoscroll(autoscroll, cx);
15472        }
15473        cx.notify();
15474    }
15475
15476    pub fn row_for_block(
15477        &self,
15478        block_id: CustomBlockId,
15479        cx: &mut Context<Self>,
15480    ) -> Option<DisplayRow> {
15481        self.display_map
15482            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15483    }
15484
15485    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15486        self.focused_block = Some(focused_block);
15487    }
15488
15489    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15490        self.focused_block.take()
15491    }
15492
15493    pub fn insert_creases(
15494        &mut self,
15495        creases: impl IntoIterator<Item = Crease<Anchor>>,
15496        cx: &mut Context<Self>,
15497    ) -> Vec<CreaseId> {
15498        self.display_map
15499            .update(cx, |map, cx| map.insert_creases(creases, cx))
15500    }
15501
15502    pub fn remove_creases(
15503        &mut self,
15504        ids: impl IntoIterator<Item = CreaseId>,
15505        cx: &mut Context<Self>,
15506    ) {
15507        self.display_map
15508            .update(cx, |map, cx| map.remove_creases(ids, cx));
15509    }
15510
15511    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15512        self.display_map
15513            .update(cx, |map, cx| map.snapshot(cx))
15514            .longest_row()
15515    }
15516
15517    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15518        self.display_map
15519            .update(cx, |map, cx| map.snapshot(cx))
15520            .max_point()
15521    }
15522
15523    pub fn text(&self, cx: &App) -> String {
15524        self.buffer.read(cx).read(cx).text()
15525    }
15526
15527    pub fn is_empty(&self, cx: &App) -> bool {
15528        self.buffer.read(cx).read(cx).is_empty()
15529    }
15530
15531    pub fn text_option(&self, cx: &App) -> Option<String> {
15532        let text = self.text(cx);
15533        let text = text.trim();
15534
15535        if text.is_empty() {
15536            return None;
15537        }
15538
15539        Some(text.to_string())
15540    }
15541
15542    pub fn set_text(
15543        &mut self,
15544        text: impl Into<Arc<str>>,
15545        window: &mut Window,
15546        cx: &mut Context<Self>,
15547    ) {
15548        self.transact(window, cx, |this, _, cx| {
15549            this.buffer
15550                .read(cx)
15551                .as_singleton()
15552                .expect("you can only call set_text on editors for singleton buffers")
15553                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15554        });
15555    }
15556
15557    pub fn display_text(&self, cx: &mut App) -> String {
15558        self.display_map
15559            .update(cx, |map, cx| map.snapshot(cx))
15560            .text()
15561    }
15562
15563    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15564        let mut wrap_guides = smallvec::smallvec![];
15565
15566        if self.show_wrap_guides == Some(false) {
15567            return wrap_guides;
15568        }
15569
15570        let settings = self.buffer.read(cx).language_settings(cx);
15571        if settings.show_wrap_guides {
15572            match self.soft_wrap_mode(cx) {
15573                SoftWrap::Column(soft_wrap) => {
15574                    wrap_guides.push((soft_wrap as usize, true));
15575                }
15576                SoftWrap::Bounded(soft_wrap) => {
15577                    wrap_guides.push((soft_wrap as usize, true));
15578                }
15579                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15580            }
15581            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15582        }
15583
15584        wrap_guides
15585    }
15586
15587    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15588        let settings = self.buffer.read(cx).language_settings(cx);
15589        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15590        match mode {
15591            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15592                SoftWrap::None
15593            }
15594            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15595            language_settings::SoftWrap::PreferredLineLength => {
15596                SoftWrap::Column(settings.preferred_line_length)
15597            }
15598            language_settings::SoftWrap::Bounded => {
15599                SoftWrap::Bounded(settings.preferred_line_length)
15600            }
15601        }
15602    }
15603
15604    pub fn set_soft_wrap_mode(
15605        &mut self,
15606        mode: language_settings::SoftWrap,
15607
15608        cx: &mut Context<Self>,
15609    ) {
15610        self.soft_wrap_mode_override = Some(mode);
15611        cx.notify();
15612    }
15613
15614    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15615        self.hard_wrap = hard_wrap;
15616        cx.notify();
15617    }
15618
15619    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15620        self.text_style_refinement = Some(style);
15621    }
15622
15623    /// called by the Element so we know what style we were most recently rendered with.
15624    pub(crate) fn set_style(
15625        &mut self,
15626        style: EditorStyle,
15627        window: &mut Window,
15628        cx: &mut Context<Self>,
15629    ) {
15630        let rem_size = window.rem_size();
15631        self.display_map.update(cx, |map, cx| {
15632            map.set_font(
15633                style.text.font(),
15634                style.text.font_size.to_pixels(rem_size),
15635                cx,
15636            )
15637        });
15638        self.style = Some(style);
15639    }
15640
15641    pub fn style(&self) -> Option<&EditorStyle> {
15642        self.style.as_ref()
15643    }
15644
15645    // Called by the element. This method is not designed to be called outside of the editor
15646    // element's layout code because it does not notify when rewrapping is computed synchronously.
15647    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15648        self.display_map
15649            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15650    }
15651
15652    pub fn set_soft_wrap(&mut self) {
15653        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15654    }
15655
15656    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15657        if self.soft_wrap_mode_override.is_some() {
15658            self.soft_wrap_mode_override.take();
15659        } else {
15660            let soft_wrap = match self.soft_wrap_mode(cx) {
15661                SoftWrap::GitDiff => return,
15662                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15663                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15664                    language_settings::SoftWrap::None
15665                }
15666            };
15667            self.soft_wrap_mode_override = Some(soft_wrap);
15668        }
15669        cx.notify();
15670    }
15671
15672    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15673        let Some(workspace) = self.workspace() else {
15674            return;
15675        };
15676        let fs = workspace.read(cx).app_state().fs.clone();
15677        let current_show = TabBarSettings::get_global(cx).show;
15678        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15679            setting.show = Some(!current_show);
15680        });
15681    }
15682
15683    pub fn toggle_indent_guides(
15684        &mut self,
15685        _: &ToggleIndentGuides,
15686        _: &mut Window,
15687        cx: &mut Context<Self>,
15688    ) {
15689        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15690            self.buffer
15691                .read(cx)
15692                .language_settings(cx)
15693                .indent_guides
15694                .enabled
15695        });
15696        self.show_indent_guides = Some(!currently_enabled);
15697        cx.notify();
15698    }
15699
15700    fn should_show_indent_guides(&self) -> Option<bool> {
15701        self.show_indent_guides
15702    }
15703
15704    pub fn toggle_line_numbers(
15705        &mut self,
15706        _: &ToggleLineNumbers,
15707        _: &mut Window,
15708        cx: &mut Context<Self>,
15709    ) {
15710        let mut editor_settings = EditorSettings::get_global(cx).clone();
15711        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15712        EditorSettings::override_global(editor_settings, cx);
15713    }
15714
15715    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15716        if let Some(show_line_numbers) = self.show_line_numbers {
15717            return show_line_numbers;
15718        }
15719        EditorSettings::get_global(cx).gutter.line_numbers
15720    }
15721
15722    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15723        self.use_relative_line_numbers
15724            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15725    }
15726
15727    pub fn toggle_relative_line_numbers(
15728        &mut self,
15729        _: &ToggleRelativeLineNumbers,
15730        _: &mut Window,
15731        cx: &mut Context<Self>,
15732    ) {
15733        let is_relative = self.should_use_relative_line_numbers(cx);
15734        self.set_relative_line_number(Some(!is_relative), cx)
15735    }
15736
15737    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15738        self.use_relative_line_numbers = is_relative;
15739        cx.notify();
15740    }
15741
15742    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15743        self.show_gutter = show_gutter;
15744        cx.notify();
15745    }
15746
15747    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15748        self.show_scrollbars = show_scrollbars;
15749        cx.notify();
15750    }
15751
15752    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15753        self.show_line_numbers = Some(show_line_numbers);
15754        cx.notify();
15755    }
15756
15757    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15758        self.show_git_diff_gutter = Some(show_git_diff_gutter);
15759        cx.notify();
15760    }
15761
15762    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15763        self.show_code_actions = Some(show_code_actions);
15764        cx.notify();
15765    }
15766
15767    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15768        self.show_runnables = Some(show_runnables);
15769        cx.notify();
15770    }
15771
15772    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15773        self.show_breakpoints = Some(show_breakpoints);
15774        cx.notify();
15775    }
15776
15777    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15778        if self.display_map.read(cx).masked != masked {
15779            self.display_map.update(cx, |map, _| map.masked = masked);
15780        }
15781        cx.notify()
15782    }
15783
15784    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15785        self.show_wrap_guides = Some(show_wrap_guides);
15786        cx.notify();
15787    }
15788
15789    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15790        self.show_indent_guides = Some(show_indent_guides);
15791        cx.notify();
15792    }
15793
15794    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15795        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15796            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15797                if let Some(dir) = file.abs_path(cx).parent() {
15798                    return Some(dir.to_owned());
15799                }
15800            }
15801
15802            if let Some(project_path) = buffer.read(cx).project_path(cx) {
15803                return Some(project_path.path.to_path_buf());
15804            }
15805        }
15806
15807        None
15808    }
15809
15810    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15811        self.active_excerpt(cx)?
15812            .1
15813            .read(cx)
15814            .file()
15815            .and_then(|f| f.as_local())
15816    }
15817
15818    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15819        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15820            let buffer = buffer.read(cx);
15821            if let Some(project_path) = buffer.project_path(cx) {
15822                let project = self.project.as_ref()?.read(cx);
15823                project.absolute_path(&project_path, cx)
15824            } else {
15825                buffer
15826                    .file()
15827                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15828            }
15829        })
15830    }
15831
15832    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15833        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15834            let project_path = buffer.read(cx).project_path(cx)?;
15835            let project = self.project.as_ref()?.read(cx);
15836            let entry = project.entry_for_path(&project_path, cx)?;
15837            let path = entry.path.to_path_buf();
15838            Some(path)
15839        })
15840    }
15841
15842    pub fn reveal_in_finder(
15843        &mut self,
15844        _: &RevealInFileManager,
15845        _window: &mut Window,
15846        cx: &mut Context<Self>,
15847    ) {
15848        if let Some(target) = self.target_file(cx) {
15849            cx.reveal_path(&target.abs_path(cx));
15850        }
15851    }
15852
15853    pub fn copy_path(
15854        &mut self,
15855        _: &zed_actions::workspace::CopyPath,
15856        _window: &mut Window,
15857        cx: &mut Context<Self>,
15858    ) {
15859        if let Some(path) = self.target_file_abs_path(cx) {
15860            if let Some(path) = path.to_str() {
15861                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15862            }
15863        }
15864    }
15865
15866    pub fn copy_relative_path(
15867        &mut self,
15868        _: &zed_actions::workspace::CopyRelativePath,
15869        _window: &mut Window,
15870        cx: &mut Context<Self>,
15871    ) {
15872        if let Some(path) = self.target_file_path(cx) {
15873            if let Some(path) = path.to_str() {
15874                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15875            }
15876        }
15877    }
15878
15879    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
15880        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15881            buffer.read(cx).project_path(cx)
15882        } else {
15883            None
15884        }
15885    }
15886
15887    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15888        let _ = maybe!({
15889            let breakpoint_store = self.breakpoint_store.as_ref()?;
15890
15891            let Some((_, _, active_position)) =
15892                breakpoint_store.read(cx).active_position().cloned()
15893            else {
15894                self.clear_row_highlights::<DebugCurrentRowHighlight>();
15895                return None;
15896            };
15897
15898            let snapshot = self
15899                .project
15900                .as_ref()?
15901                .read(cx)
15902                .buffer_for_id(active_position.buffer_id?, cx)?
15903                .read(cx)
15904                .snapshot();
15905
15906            for (id, ExcerptRange { context, .. }) in self
15907                .buffer
15908                .read(cx)
15909                .excerpts_for_buffer(active_position.buffer_id?, cx)
15910            {
15911                if context.start.cmp(&active_position, &snapshot).is_ge()
15912                    || context.end.cmp(&active_position, &snapshot).is_lt()
15913                {
15914                    continue;
15915                }
15916                let snapshot = self.buffer.read(cx).snapshot(cx);
15917                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15918
15919                self.clear_row_highlights::<DebugCurrentRowHighlight>();
15920                self.go_to_line::<DebugCurrentRowHighlight>(
15921                    multibuffer_anchor,
15922                    Some(cx.theme().colors().editor_debugger_active_line_background),
15923                    window,
15924                    cx,
15925                );
15926
15927                cx.notify();
15928            }
15929
15930            Some(())
15931        });
15932    }
15933
15934    pub fn copy_file_name_without_extension(
15935        &mut self,
15936        _: &CopyFileNameWithoutExtension,
15937        _: &mut Window,
15938        cx: &mut Context<Self>,
15939    ) {
15940        if let Some(file) = self.target_file(cx) {
15941            if let Some(file_stem) = file.path().file_stem() {
15942                if let Some(name) = file_stem.to_str() {
15943                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15944                }
15945            }
15946        }
15947    }
15948
15949    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15950        if let Some(file) = self.target_file(cx) {
15951            if let Some(file_name) = file.path().file_name() {
15952                if let Some(name) = file_name.to_str() {
15953                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15954                }
15955            }
15956        }
15957    }
15958
15959    pub fn toggle_git_blame(
15960        &mut self,
15961        _: &::git::Blame,
15962        window: &mut Window,
15963        cx: &mut Context<Self>,
15964    ) {
15965        self.show_git_blame_gutter = !self.show_git_blame_gutter;
15966
15967        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15968            self.start_git_blame(true, window, cx);
15969        }
15970
15971        cx.notify();
15972    }
15973
15974    pub fn toggle_git_blame_inline(
15975        &mut self,
15976        _: &ToggleGitBlameInline,
15977        window: &mut Window,
15978        cx: &mut Context<Self>,
15979    ) {
15980        self.toggle_git_blame_inline_internal(true, window, cx);
15981        cx.notify();
15982    }
15983
15984    pub fn open_git_blame_commit(
15985        &mut self,
15986        _: &OpenGitBlameCommit,
15987        window: &mut Window,
15988        cx: &mut Context<Self>,
15989    ) {
15990        self.open_git_blame_commit_internal(window, cx);
15991    }
15992
15993    fn open_git_blame_commit_internal(
15994        &mut self,
15995        window: &mut Window,
15996        cx: &mut Context<Self>,
15997    ) -> Option<()> {
15998        let blame = self.blame.as_ref()?;
15999        let snapshot = self.snapshot(window, cx);
16000        let cursor = self.selections.newest::<Point>(cx).head();
16001        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16002        let blame_entry = blame
16003            .update(cx, |blame, cx| {
16004                blame
16005                    .blame_for_rows(
16006                        &[RowInfo {
16007                            buffer_id: Some(buffer.remote_id()),
16008                            buffer_row: Some(point.row),
16009                            ..Default::default()
16010                        }],
16011                        cx,
16012                    )
16013                    .next()
16014            })
16015            .flatten()?;
16016        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16017        let repo = blame.read(cx).repository(cx)?;
16018        let workspace = self.workspace()?.downgrade();
16019        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16020        None
16021    }
16022
16023    pub fn git_blame_inline_enabled(&self) -> bool {
16024        self.git_blame_inline_enabled
16025    }
16026
16027    pub fn toggle_selection_menu(
16028        &mut self,
16029        _: &ToggleSelectionMenu,
16030        _: &mut Window,
16031        cx: &mut Context<Self>,
16032    ) {
16033        self.show_selection_menu = self
16034            .show_selection_menu
16035            .map(|show_selections_menu| !show_selections_menu)
16036            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16037
16038        cx.notify();
16039    }
16040
16041    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16042        self.show_selection_menu
16043            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16044    }
16045
16046    fn start_git_blame(
16047        &mut self,
16048        user_triggered: bool,
16049        window: &mut Window,
16050        cx: &mut Context<Self>,
16051    ) {
16052        if let Some(project) = self.project.as_ref() {
16053            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16054                return;
16055            };
16056
16057            if buffer.read(cx).file().is_none() {
16058                return;
16059            }
16060
16061            let focused = self.focus_handle(cx).contains_focused(window, cx);
16062
16063            let project = project.clone();
16064            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16065            self.blame_subscription =
16066                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16067            self.blame = Some(blame);
16068        }
16069    }
16070
16071    fn toggle_git_blame_inline_internal(
16072        &mut self,
16073        user_triggered: bool,
16074        window: &mut Window,
16075        cx: &mut Context<Self>,
16076    ) {
16077        if self.git_blame_inline_enabled {
16078            self.git_blame_inline_enabled = false;
16079            self.show_git_blame_inline = false;
16080            self.show_git_blame_inline_delay_task.take();
16081        } else {
16082            self.git_blame_inline_enabled = true;
16083            self.start_git_blame_inline(user_triggered, window, cx);
16084        }
16085
16086        cx.notify();
16087    }
16088
16089    fn start_git_blame_inline(
16090        &mut self,
16091        user_triggered: bool,
16092        window: &mut Window,
16093        cx: &mut Context<Self>,
16094    ) {
16095        self.start_git_blame(user_triggered, window, cx);
16096
16097        if ProjectSettings::get_global(cx)
16098            .git
16099            .inline_blame_delay()
16100            .is_some()
16101        {
16102            self.start_inline_blame_timer(window, cx);
16103        } else {
16104            self.show_git_blame_inline = true
16105        }
16106    }
16107
16108    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16109        self.blame.as_ref()
16110    }
16111
16112    pub fn show_git_blame_gutter(&self) -> bool {
16113        self.show_git_blame_gutter
16114    }
16115
16116    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16117        self.show_git_blame_gutter && self.has_blame_entries(cx)
16118    }
16119
16120    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16121        self.show_git_blame_inline
16122            && (self.focus_handle.is_focused(window)
16123                || self
16124                    .git_blame_inline_tooltip
16125                    .as_ref()
16126                    .and_then(|t| t.upgrade())
16127                    .is_some())
16128            && !self.newest_selection_head_on_empty_line(cx)
16129            && self.has_blame_entries(cx)
16130    }
16131
16132    fn has_blame_entries(&self, cx: &App) -> bool {
16133        self.blame()
16134            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16135    }
16136
16137    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16138        let cursor_anchor = self.selections.newest_anchor().head();
16139
16140        let snapshot = self.buffer.read(cx).snapshot(cx);
16141        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16142
16143        snapshot.line_len(buffer_row) == 0
16144    }
16145
16146    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16147        let buffer_and_selection = maybe!({
16148            let selection = self.selections.newest::<Point>(cx);
16149            let selection_range = selection.range();
16150
16151            let multi_buffer = self.buffer().read(cx);
16152            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16153            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16154
16155            let (buffer, range, _) = if selection.reversed {
16156                buffer_ranges.first()
16157            } else {
16158                buffer_ranges.last()
16159            }?;
16160
16161            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16162                ..text::ToPoint::to_point(&range.end, &buffer).row;
16163            Some((
16164                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16165                selection,
16166            ))
16167        });
16168
16169        let Some((buffer, selection)) = buffer_and_selection else {
16170            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16171        };
16172
16173        let Some(project) = self.project.as_ref() else {
16174            return Task::ready(Err(anyhow!("editor does not have project")));
16175        };
16176
16177        project.update(cx, |project, cx| {
16178            project.get_permalink_to_line(&buffer, selection, cx)
16179        })
16180    }
16181
16182    pub fn copy_permalink_to_line(
16183        &mut self,
16184        _: &CopyPermalinkToLine,
16185        window: &mut Window,
16186        cx: &mut Context<Self>,
16187    ) {
16188        let permalink_task = self.get_permalink_to_line(cx);
16189        let workspace = self.workspace();
16190
16191        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16192            Ok(permalink) => {
16193                cx.update(|_, cx| {
16194                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16195                })
16196                .ok();
16197            }
16198            Err(err) => {
16199                let message = format!("Failed to copy permalink: {err}");
16200
16201                Err::<(), anyhow::Error>(err).log_err();
16202
16203                if let Some(workspace) = workspace {
16204                    workspace
16205                        .update_in(cx, |workspace, _, cx| {
16206                            struct CopyPermalinkToLine;
16207
16208                            workspace.show_toast(
16209                                Toast::new(
16210                                    NotificationId::unique::<CopyPermalinkToLine>(),
16211                                    message,
16212                                ),
16213                                cx,
16214                            )
16215                        })
16216                        .ok();
16217                }
16218            }
16219        })
16220        .detach();
16221    }
16222
16223    pub fn copy_file_location(
16224        &mut self,
16225        _: &CopyFileLocation,
16226        _: &mut Window,
16227        cx: &mut Context<Self>,
16228    ) {
16229        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16230        if let Some(file) = self.target_file(cx) {
16231            if let Some(path) = file.path().to_str() {
16232                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16233            }
16234        }
16235    }
16236
16237    pub fn open_permalink_to_line(
16238        &mut self,
16239        _: &OpenPermalinkToLine,
16240        window: &mut Window,
16241        cx: &mut Context<Self>,
16242    ) {
16243        let permalink_task = self.get_permalink_to_line(cx);
16244        let workspace = self.workspace();
16245
16246        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16247            Ok(permalink) => {
16248                cx.update(|_, cx| {
16249                    cx.open_url(permalink.as_ref());
16250                })
16251                .ok();
16252            }
16253            Err(err) => {
16254                let message = format!("Failed to open permalink: {err}");
16255
16256                Err::<(), anyhow::Error>(err).log_err();
16257
16258                if let Some(workspace) = workspace {
16259                    workspace
16260                        .update(cx, |workspace, cx| {
16261                            struct OpenPermalinkToLine;
16262
16263                            workspace.show_toast(
16264                                Toast::new(
16265                                    NotificationId::unique::<OpenPermalinkToLine>(),
16266                                    message,
16267                                ),
16268                                cx,
16269                            )
16270                        })
16271                        .ok();
16272                }
16273            }
16274        })
16275        .detach();
16276    }
16277
16278    pub fn insert_uuid_v4(
16279        &mut self,
16280        _: &InsertUuidV4,
16281        window: &mut Window,
16282        cx: &mut Context<Self>,
16283    ) {
16284        self.insert_uuid(UuidVersion::V4, window, cx);
16285    }
16286
16287    pub fn insert_uuid_v7(
16288        &mut self,
16289        _: &InsertUuidV7,
16290        window: &mut Window,
16291        cx: &mut Context<Self>,
16292    ) {
16293        self.insert_uuid(UuidVersion::V7, window, cx);
16294    }
16295
16296    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16297        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16298        self.transact(window, cx, |this, window, cx| {
16299            let edits = this
16300                .selections
16301                .all::<Point>(cx)
16302                .into_iter()
16303                .map(|selection| {
16304                    let uuid = match version {
16305                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16306                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16307                    };
16308
16309                    (selection.range(), uuid.to_string())
16310                });
16311            this.edit(edits, cx);
16312            this.refresh_inline_completion(true, false, window, cx);
16313        });
16314    }
16315
16316    pub fn open_selections_in_multibuffer(
16317        &mut self,
16318        _: &OpenSelectionsInMultibuffer,
16319        window: &mut Window,
16320        cx: &mut Context<Self>,
16321    ) {
16322        let multibuffer = self.buffer.read(cx);
16323
16324        let Some(buffer) = multibuffer.as_singleton() else {
16325            return;
16326        };
16327
16328        let Some(workspace) = self.workspace() else {
16329            return;
16330        };
16331
16332        let locations = self
16333            .selections
16334            .disjoint_anchors()
16335            .iter()
16336            .map(|range| Location {
16337                buffer: buffer.clone(),
16338                range: range.start.text_anchor..range.end.text_anchor,
16339            })
16340            .collect::<Vec<_>>();
16341
16342        let title = multibuffer.title(cx).to_string();
16343
16344        cx.spawn_in(window, async move |_, cx| {
16345            workspace.update_in(cx, |workspace, window, cx| {
16346                Self::open_locations_in_multibuffer(
16347                    workspace,
16348                    locations,
16349                    format!("Selections for '{title}'"),
16350                    false,
16351                    MultibufferSelectionMode::All,
16352                    window,
16353                    cx,
16354                );
16355            })
16356        })
16357        .detach();
16358    }
16359
16360    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16361    /// last highlight added will be used.
16362    ///
16363    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16364    pub fn highlight_rows<T: 'static>(
16365        &mut self,
16366        range: Range<Anchor>,
16367        color: Hsla,
16368        should_autoscroll: bool,
16369        cx: &mut Context<Self>,
16370    ) {
16371        let snapshot = self.buffer().read(cx).snapshot(cx);
16372        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16373        let ix = row_highlights.binary_search_by(|highlight| {
16374            Ordering::Equal
16375                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16376                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16377        });
16378
16379        if let Err(mut ix) = ix {
16380            let index = post_inc(&mut self.highlight_order);
16381
16382            // If this range intersects with the preceding highlight, then merge it with
16383            // the preceding highlight. Otherwise insert a new highlight.
16384            let mut merged = false;
16385            if ix > 0 {
16386                let prev_highlight = &mut row_highlights[ix - 1];
16387                if prev_highlight
16388                    .range
16389                    .end
16390                    .cmp(&range.start, &snapshot)
16391                    .is_ge()
16392                {
16393                    ix -= 1;
16394                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16395                        prev_highlight.range.end = range.end;
16396                    }
16397                    merged = true;
16398                    prev_highlight.index = index;
16399                    prev_highlight.color = color;
16400                    prev_highlight.should_autoscroll = should_autoscroll;
16401                }
16402            }
16403
16404            if !merged {
16405                row_highlights.insert(
16406                    ix,
16407                    RowHighlight {
16408                        range: range.clone(),
16409                        index,
16410                        color,
16411                        should_autoscroll,
16412                    },
16413                );
16414            }
16415
16416            // If any of the following highlights intersect with this one, merge them.
16417            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16418                let highlight = &row_highlights[ix];
16419                if next_highlight
16420                    .range
16421                    .start
16422                    .cmp(&highlight.range.end, &snapshot)
16423                    .is_le()
16424                {
16425                    if next_highlight
16426                        .range
16427                        .end
16428                        .cmp(&highlight.range.end, &snapshot)
16429                        .is_gt()
16430                    {
16431                        row_highlights[ix].range.end = next_highlight.range.end;
16432                    }
16433                    row_highlights.remove(ix + 1);
16434                } else {
16435                    break;
16436                }
16437            }
16438        }
16439    }
16440
16441    /// Remove any highlighted row ranges of the given type that intersect the
16442    /// given ranges.
16443    pub fn remove_highlighted_rows<T: 'static>(
16444        &mut self,
16445        ranges_to_remove: Vec<Range<Anchor>>,
16446        cx: &mut Context<Self>,
16447    ) {
16448        let snapshot = self.buffer().read(cx).snapshot(cx);
16449        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16450        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16451        row_highlights.retain(|highlight| {
16452            while let Some(range_to_remove) = ranges_to_remove.peek() {
16453                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16454                    Ordering::Less | Ordering::Equal => {
16455                        ranges_to_remove.next();
16456                    }
16457                    Ordering::Greater => {
16458                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16459                            Ordering::Less | Ordering::Equal => {
16460                                return false;
16461                            }
16462                            Ordering::Greater => break,
16463                        }
16464                    }
16465                }
16466            }
16467
16468            true
16469        })
16470    }
16471
16472    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16473    pub fn clear_row_highlights<T: 'static>(&mut self) {
16474        self.highlighted_rows.remove(&TypeId::of::<T>());
16475    }
16476
16477    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16478    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16479        self.highlighted_rows
16480            .get(&TypeId::of::<T>())
16481            .map_or(&[] as &[_], |vec| vec.as_slice())
16482            .iter()
16483            .map(|highlight| (highlight.range.clone(), highlight.color))
16484    }
16485
16486    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16487    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16488    /// Allows to ignore certain kinds of highlights.
16489    pub fn highlighted_display_rows(
16490        &self,
16491        window: &mut Window,
16492        cx: &mut App,
16493    ) -> BTreeMap<DisplayRow, LineHighlight> {
16494        let snapshot = self.snapshot(window, cx);
16495        let mut used_highlight_orders = HashMap::default();
16496        self.highlighted_rows
16497            .iter()
16498            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16499            .fold(
16500                BTreeMap::<DisplayRow, LineHighlight>::new(),
16501                |mut unique_rows, highlight| {
16502                    let start = highlight.range.start.to_display_point(&snapshot);
16503                    let end = highlight.range.end.to_display_point(&snapshot);
16504                    let start_row = start.row().0;
16505                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16506                        && end.column() == 0
16507                    {
16508                        end.row().0.saturating_sub(1)
16509                    } else {
16510                        end.row().0
16511                    };
16512                    for row in start_row..=end_row {
16513                        let used_index =
16514                            used_highlight_orders.entry(row).or_insert(highlight.index);
16515                        if highlight.index >= *used_index {
16516                            *used_index = highlight.index;
16517                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16518                        }
16519                    }
16520                    unique_rows
16521                },
16522            )
16523    }
16524
16525    pub fn highlighted_display_row_for_autoscroll(
16526        &self,
16527        snapshot: &DisplaySnapshot,
16528    ) -> Option<DisplayRow> {
16529        self.highlighted_rows
16530            .values()
16531            .flat_map(|highlighted_rows| highlighted_rows.iter())
16532            .filter_map(|highlight| {
16533                if highlight.should_autoscroll {
16534                    Some(highlight.range.start.to_display_point(snapshot).row())
16535                } else {
16536                    None
16537                }
16538            })
16539            .min()
16540    }
16541
16542    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16543        self.highlight_background::<SearchWithinRange>(
16544            ranges,
16545            |colors| colors.editor_document_highlight_read_background,
16546            cx,
16547        )
16548    }
16549
16550    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16551        self.breadcrumb_header = Some(new_header);
16552    }
16553
16554    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16555        self.clear_background_highlights::<SearchWithinRange>(cx);
16556    }
16557
16558    pub fn highlight_background<T: 'static>(
16559        &mut self,
16560        ranges: &[Range<Anchor>],
16561        color_fetcher: fn(&ThemeColors) -> Hsla,
16562        cx: &mut Context<Self>,
16563    ) {
16564        self.background_highlights
16565            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16566        self.scrollbar_marker_state.dirty = true;
16567        cx.notify();
16568    }
16569
16570    pub fn clear_background_highlights<T: 'static>(
16571        &mut self,
16572        cx: &mut Context<Self>,
16573    ) -> Option<BackgroundHighlight> {
16574        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16575        if !text_highlights.1.is_empty() {
16576            self.scrollbar_marker_state.dirty = true;
16577            cx.notify();
16578        }
16579        Some(text_highlights)
16580    }
16581
16582    pub fn highlight_gutter<T: 'static>(
16583        &mut self,
16584        ranges: &[Range<Anchor>],
16585        color_fetcher: fn(&App) -> Hsla,
16586        cx: &mut Context<Self>,
16587    ) {
16588        self.gutter_highlights
16589            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16590        cx.notify();
16591    }
16592
16593    pub fn clear_gutter_highlights<T: 'static>(
16594        &mut self,
16595        cx: &mut Context<Self>,
16596    ) -> Option<GutterHighlight> {
16597        cx.notify();
16598        self.gutter_highlights.remove(&TypeId::of::<T>())
16599    }
16600
16601    #[cfg(feature = "test-support")]
16602    pub fn all_text_background_highlights(
16603        &self,
16604        window: &mut Window,
16605        cx: &mut Context<Self>,
16606    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16607        let snapshot = self.snapshot(window, cx);
16608        let buffer = &snapshot.buffer_snapshot;
16609        let start = buffer.anchor_before(0);
16610        let end = buffer.anchor_after(buffer.len());
16611        let theme = cx.theme().colors();
16612        self.background_highlights_in_range(start..end, &snapshot, theme)
16613    }
16614
16615    #[cfg(feature = "test-support")]
16616    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16617        let snapshot = self.buffer().read(cx).snapshot(cx);
16618
16619        let highlights = self
16620            .background_highlights
16621            .get(&TypeId::of::<items::BufferSearchHighlights>());
16622
16623        if let Some((_color, ranges)) = highlights {
16624            ranges
16625                .iter()
16626                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16627                .collect_vec()
16628        } else {
16629            vec![]
16630        }
16631    }
16632
16633    fn document_highlights_for_position<'a>(
16634        &'a self,
16635        position: Anchor,
16636        buffer: &'a MultiBufferSnapshot,
16637    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16638        let read_highlights = self
16639            .background_highlights
16640            .get(&TypeId::of::<DocumentHighlightRead>())
16641            .map(|h| &h.1);
16642        let write_highlights = self
16643            .background_highlights
16644            .get(&TypeId::of::<DocumentHighlightWrite>())
16645            .map(|h| &h.1);
16646        let left_position = position.bias_left(buffer);
16647        let right_position = position.bias_right(buffer);
16648        read_highlights
16649            .into_iter()
16650            .chain(write_highlights)
16651            .flat_map(move |ranges| {
16652                let start_ix = match ranges.binary_search_by(|probe| {
16653                    let cmp = probe.end.cmp(&left_position, buffer);
16654                    if cmp.is_ge() {
16655                        Ordering::Greater
16656                    } else {
16657                        Ordering::Less
16658                    }
16659                }) {
16660                    Ok(i) | Err(i) => i,
16661                };
16662
16663                ranges[start_ix..]
16664                    .iter()
16665                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16666            })
16667    }
16668
16669    pub fn has_background_highlights<T: 'static>(&self) -> bool {
16670        self.background_highlights
16671            .get(&TypeId::of::<T>())
16672            .map_or(false, |(_, highlights)| !highlights.is_empty())
16673    }
16674
16675    pub fn background_highlights_in_range(
16676        &self,
16677        search_range: Range<Anchor>,
16678        display_snapshot: &DisplaySnapshot,
16679        theme: &ThemeColors,
16680    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16681        let mut results = Vec::new();
16682        for (color_fetcher, ranges) in self.background_highlights.values() {
16683            let color = color_fetcher(theme);
16684            let start_ix = match ranges.binary_search_by(|probe| {
16685                let cmp = probe
16686                    .end
16687                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16688                if cmp.is_gt() {
16689                    Ordering::Greater
16690                } else {
16691                    Ordering::Less
16692                }
16693            }) {
16694                Ok(i) | Err(i) => i,
16695            };
16696            for range in &ranges[start_ix..] {
16697                if range
16698                    .start
16699                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16700                    .is_ge()
16701                {
16702                    break;
16703                }
16704
16705                let start = range.start.to_display_point(display_snapshot);
16706                let end = range.end.to_display_point(display_snapshot);
16707                results.push((start..end, color))
16708            }
16709        }
16710        results
16711    }
16712
16713    pub fn background_highlight_row_ranges<T: 'static>(
16714        &self,
16715        search_range: Range<Anchor>,
16716        display_snapshot: &DisplaySnapshot,
16717        count: usize,
16718    ) -> Vec<RangeInclusive<DisplayPoint>> {
16719        let mut results = Vec::new();
16720        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16721            return vec![];
16722        };
16723
16724        let start_ix = match ranges.binary_search_by(|probe| {
16725            let cmp = probe
16726                .end
16727                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16728            if cmp.is_gt() {
16729                Ordering::Greater
16730            } else {
16731                Ordering::Less
16732            }
16733        }) {
16734            Ok(i) | Err(i) => i,
16735        };
16736        let mut push_region = |start: Option<Point>, end: Option<Point>| {
16737            if let (Some(start_display), Some(end_display)) = (start, end) {
16738                results.push(
16739                    start_display.to_display_point(display_snapshot)
16740                        ..=end_display.to_display_point(display_snapshot),
16741                );
16742            }
16743        };
16744        let mut start_row: Option<Point> = None;
16745        let mut end_row: Option<Point> = None;
16746        if ranges.len() > count {
16747            return Vec::new();
16748        }
16749        for range in &ranges[start_ix..] {
16750            if range
16751                .start
16752                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16753                .is_ge()
16754            {
16755                break;
16756            }
16757            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16758            if let Some(current_row) = &end_row {
16759                if end.row == current_row.row {
16760                    continue;
16761                }
16762            }
16763            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16764            if start_row.is_none() {
16765                assert_eq!(end_row, None);
16766                start_row = Some(start);
16767                end_row = Some(end);
16768                continue;
16769            }
16770            if let Some(current_end) = end_row.as_mut() {
16771                if start.row > current_end.row + 1 {
16772                    push_region(start_row, end_row);
16773                    start_row = Some(start);
16774                    end_row = Some(end);
16775                } else {
16776                    // Merge two hunks.
16777                    *current_end = end;
16778                }
16779            } else {
16780                unreachable!();
16781            }
16782        }
16783        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16784        push_region(start_row, end_row);
16785        results
16786    }
16787
16788    pub fn gutter_highlights_in_range(
16789        &self,
16790        search_range: Range<Anchor>,
16791        display_snapshot: &DisplaySnapshot,
16792        cx: &App,
16793    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16794        let mut results = Vec::new();
16795        for (color_fetcher, ranges) in self.gutter_highlights.values() {
16796            let color = color_fetcher(cx);
16797            let start_ix = match ranges.binary_search_by(|probe| {
16798                let cmp = probe
16799                    .end
16800                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16801                if cmp.is_gt() {
16802                    Ordering::Greater
16803                } else {
16804                    Ordering::Less
16805                }
16806            }) {
16807                Ok(i) | Err(i) => i,
16808            };
16809            for range in &ranges[start_ix..] {
16810                if range
16811                    .start
16812                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16813                    .is_ge()
16814                {
16815                    break;
16816                }
16817
16818                let start = range.start.to_display_point(display_snapshot);
16819                let end = range.end.to_display_point(display_snapshot);
16820                results.push((start..end, color))
16821            }
16822        }
16823        results
16824    }
16825
16826    /// Get the text ranges corresponding to the redaction query
16827    pub fn redacted_ranges(
16828        &self,
16829        search_range: Range<Anchor>,
16830        display_snapshot: &DisplaySnapshot,
16831        cx: &App,
16832    ) -> Vec<Range<DisplayPoint>> {
16833        display_snapshot
16834            .buffer_snapshot
16835            .redacted_ranges(search_range, |file| {
16836                if let Some(file) = file {
16837                    file.is_private()
16838                        && EditorSettings::get(
16839                            Some(SettingsLocation {
16840                                worktree_id: file.worktree_id(cx),
16841                                path: file.path().as_ref(),
16842                            }),
16843                            cx,
16844                        )
16845                        .redact_private_values
16846                } else {
16847                    false
16848                }
16849            })
16850            .map(|range| {
16851                range.start.to_display_point(display_snapshot)
16852                    ..range.end.to_display_point(display_snapshot)
16853            })
16854            .collect()
16855    }
16856
16857    pub fn highlight_text<T: 'static>(
16858        &mut self,
16859        ranges: Vec<Range<Anchor>>,
16860        style: HighlightStyle,
16861        cx: &mut Context<Self>,
16862    ) {
16863        self.display_map.update(cx, |map, _| {
16864            map.highlight_text(TypeId::of::<T>(), ranges, style)
16865        });
16866        cx.notify();
16867    }
16868
16869    pub(crate) fn highlight_inlays<T: 'static>(
16870        &mut self,
16871        highlights: Vec<InlayHighlight>,
16872        style: HighlightStyle,
16873        cx: &mut Context<Self>,
16874    ) {
16875        self.display_map.update(cx, |map, _| {
16876            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16877        });
16878        cx.notify();
16879    }
16880
16881    pub fn text_highlights<'a, T: 'static>(
16882        &'a self,
16883        cx: &'a App,
16884    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16885        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16886    }
16887
16888    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16889        let cleared = self
16890            .display_map
16891            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16892        if cleared {
16893            cx.notify();
16894        }
16895    }
16896
16897    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16898        (self.read_only(cx) || self.blink_manager.read(cx).visible())
16899            && self.focus_handle.is_focused(window)
16900    }
16901
16902    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16903        self.show_cursor_when_unfocused = is_enabled;
16904        cx.notify();
16905    }
16906
16907    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16908        cx.notify();
16909    }
16910
16911    fn on_buffer_event(
16912        &mut self,
16913        multibuffer: &Entity<MultiBuffer>,
16914        event: &multi_buffer::Event,
16915        window: &mut Window,
16916        cx: &mut Context<Self>,
16917    ) {
16918        match event {
16919            multi_buffer::Event::Edited {
16920                singleton_buffer_edited,
16921                edited_buffer: buffer_edited,
16922            } => {
16923                self.scrollbar_marker_state.dirty = true;
16924                self.active_indent_guides_state.dirty = true;
16925                self.refresh_active_diagnostics(cx);
16926                self.refresh_code_actions(window, cx);
16927                if self.has_active_inline_completion() {
16928                    self.update_visible_inline_completion(window, cx);
16929                }
16930                if let Some(buffer) = buffer_edited {
16931                    let buffer_id = buffer.read(cx).remote_id();
16932                    if !self.registered_buffers.contains_key(&buffer_id) {
16933                        if let Some(project) = self.project.as_ref() {
16934                            project.update(cx, |project, cx| {
16935                                self.registered_buffers.insert(
16936                                    buffer_id,
16937                                    project.register_buffer_with_language_servers(&buffer, cx),
16938                                );
16939                            })
16940                        }
16941                    }
16942                }
16943                cx.emit(EditorEvent::BufferEdited);
16944                cx.emit(SearchEvent::MatchesInvalidated);
16945                if *singleton_buffer_edited {
16946                    if let Some(project) = &self.project {
16947                        #[allow(clippy::mutable_key_type)]
16948                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16949                            multibuffer
16950                                .all_buffers()
16951                                .into_iter()
16952                                .filter_map(|buffer| {
16953                                    buffer.update(cx, |buffer, cx| {
16954                                        let language = buffer.language()?;
16955                                        let should_discard = project.update(cx, |project, cx| {
16956                                            project.is_local()
16957                                                && !project.has_language_servers_for(buffer, cx)
16958                                        });
16959                                        should_discard.not().then_some(language.clone())
16960                                    })
16961                                })
16962                                .collect::<HashSet<_>>()
16963                        });
16964                        if !languages_affected.is_empty() {
16965                            self.refresh_inlay_hints(
16966                                InlayHintRefreshReason::BufferEdited(languages_affected),
16967                                cx,
16968                            );
16969                        }
16970                    }
16971                }
16972
16973                let Some(project) = &self.project else { return };
16974                let (telemetry, is_via_ssh) = {
16975                    let project = project.read(cx);
16976                    let telemetry = project.client().telemetry().clone();
16977                    let is_via_ssh = project.is_via_ssh();
16978                    (telemetry, is_via_ssh)
16979                };
16980                refresh_linked_ranges(self, window, cx);
16981                telemetry.log_edit_event("editor", is_via_ssh);
16982            }
16983            multi_buffer::Event::ExcerptsAdded {
16984                buffer,
16985                predecessor,
16986                excerpts,
16987            } => {
16988                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16989                let buffer_id = buffer.read(cx).remote_id();
16990                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16991                    if let Some(project) = &self.project {
16992                        get_uncommitted_diff_for_buffer(
16993                            project,
16994                            [buffer.clone()],
16995                            self.buffer.clone(),
16996                            cx,
16997                        )
16998                        .detach();
16999                    }
17000                }
17001                cx.emit(EditorEvent::ExcerptsAdded {
17002                    buffer: buffer.clone(),
17003                    predecessor: *predecessor,
17004                    excerpts: excerpts.clone(),
17005                });
17006                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17007            }
17008            multi_buffer::Event::ExcerptsRemoved { ids } => {
17009                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17010                let buffer = self.buffer.read(cx);
17011                self.registered_buffers
17012                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17013                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17014                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17015            }
17016            multi_buffer::Event::ExcerptsEdited {
17017                excerpt_ids,
17018                buffer_ids,
17019            } => {
17020                self.display_map.update(cx, |map, cx| {
17021                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17022                });
17023                cx.emit(EditorEvent::ExcerptsEdited {
17024                    ids: excerpt_ids.clone(),
17025                })
17026            }
17027            multi_buffer::Event::ExcerptsExpanded { ids } => {
17028                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17029                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17030            }
17031            multi_buffer::Event::Reparsed(buffer_id) => {
17032                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17033                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17034
17035                cx.emit(EditorEvent::Reparsed(*buffer_id));
17036            }
17037            multi_buffer::Event::DiffHunksToggled => {
17038                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17039            }
17040            multi_buffer::Event::LanguageChanged(buffer_id) => {
17041                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17042                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17043                cx.emit(EditorEvent::Reparsed(*buffer_id));
17044                cx.notify();
17045            }
17046            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17047            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17048            multi_buffer::Event::FileHandleChanged
17049            | multi_buffer::Event::Reloaded
17050            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17051            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17052            multi_buffer::Event::DiagnosticsUpdated => {
17053                self.refresh_active_diagnostics(cx);
17054                self.refresh_inline_diagnostics(true, window, cx);
17055                self.scrollbar_marker_state.dirty = true;
17056                cx.notify();
17057            }
17058            _ => {}
17059        };
17060    }
17061
17062    fn on_display_map_changed(
17063        &mut self,
17064        _: Entity<DisplayMap>,
17065        _: &mut Window,
17066        cx: &mut Context<Self>,
17067    ) {
17068        cx.notify();
17069    }
17070
17071    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17072        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17073        self.update_edit_prediction_settings(cx);
17074        self.refresh_inline_completion(true, false, window, cx);
17075        self.refresh_inlay_hints(
17076            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17077                self.selections.newest_anchor().head(),
17078                &self.buffer.read(cx).snapshot(cx),
17079                cx,
17080            )),
17081            cx,
17082        );
17083
17084        let old_cursor_shape = self.cursor_shape;
17085
17086        {
17087            let editor_settings = EditorSettings::get_global(cx);
17088            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17089            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17090            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17091            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17092        }
17093
17094        if old_cursor_shape != self.cursor_shape {
17095            cx.emit(EditorEvent::CursorShapeChanged);
17096        }
17097
17098        let project_settings = ProjectSettings::get_global(cx);
17099        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17100
17101        if self.mode == EditorMode::Full {
17102            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17103            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17104            if self.show_inline_diagnostics != show_inline_diagnostics {
17105                self.show_inline_diagnostics = show_inline_diagnostics;
17106                self.refresh_inline_diagnostics(false, window, cx);
17107            }
17108
17109            if self.git_blame_inline_enabled != inline_blame_enabled {
17110                self.toggle_git_blame_inline_internal(false, window, cx);
17111            }
17112        }
17113
17114        cx.notify();
17115    }
17116
17117    pub fn set_searchable(&mut self, searchable: bool) {
17118        self.searchable = searchable;
17119    }
17120
17121    pub fn searchable(&self) -> bool {
17122        self.searchable
17123    }
17124
17125    fn open_proposed_changes_editor(
17126        &mut self,
17127        _: &OpenProposedChangesEditor,
17128        window: &mut Window,
17129        cx: &mut Context<Self>,
17130    ) {
17131        let Some(workspace) = self.workspace() else {
17132            cx.propagate();
17133            return;
17134        };
17135
17136        let selections = self.selections.all::<usize>(cx);
17137        let multi_buffer = self.buffer.read(cx);
17138        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17139        let mut new_selections_by_buffer = HashMap::default();
17140        for selection in selections {
17141            for (buffer, range, _) in
17142                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17143            {
17144                let mut range = range.to_point(buffer);
17145                range.start.column = 0;
17146                range.end.column = buffer.line_len(range.end.row);
17147                new_selections_by_buffer
17148                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17149                    .or_insert(Vec::new())
17150                    .push(range)
17151            }
17152        }
17153
17154        let proposed_changes_buffers = new_selections_by_buffer
17155            .into_iter()
17156            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17157            .collect::<Vec<_>>();
17158        let proposed_changes_editor = cx.new(|cx| {
17159            ProposedChangesEditor::new(
17160                "Proposed changes",
17161                proposed_changes_buffers,
17162                self.project.clone(),
17163                window,
17164                cx,
17165            )
17166        });
17167
17168        window.defer(cx, move |window, cx| {
17169            workspace.update(cx, |workspace, cx| {
17170                workspace.active_pane().update(cx, |pane, cx| {
17171                    pane.add_item(
17172                        Box::new(proposed_changes_editor),
17173                        true,
17174                        true,
17175                        None,
17176                        window,
17177                        cx,
17178                    );
17179                });
17180            });
17181        });
17182    }
17183
17184    pub fn open_excerpts_in_split(
17185        &mut self,
17186        _: &OpenExcerptsSplit,
17187        window: &mut Window,
17188        cx: &mut Context<Self>,
17189    ) {
17190        self.open_excerpts_common(None, true, window, cx)
17191    }
17192
17193    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17194        self.open_excerpts_common(None, false, window, cx)
17195    }
17196
17197    fn open_excerpts_common(
17198        &mut self,
17199        jump_data: Option<JumpData>,
17200        split: bool,
17201        window: &mut Window,
17202        cx: &mut Context<Self>,
17203    ) {
17204        let Some(workspace) = self.workspace() else {
17205            cx.propagate();
17206            return;
17207        };
17208
17209        if self.buffer.read(cx).is_singleton() {
17210            cx.propagate();
17211            return;
17212        }
17213
17214        let mut new_selections_by_buffer = HashMap::default();
17215        match &jump_data {
17216            Some(JumpData::MultiBufferPoint {
17217                excerpt_id,
17218                position,
17219                anchor,
17220                line_offset_from_top,
17221            }) => {
17222                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17223                if let Some(buffer) = multi_buffer_snapshot
17224                    .buffer_id_for_excerpt(*excerpt_id)
17225                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17226                {
17227                    let buffer_snapshot = buffer.read(cx).snapshot();
17228                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17229                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17230                    } else {
17231                        buffer_snapshot.clip_point(*position, Bias::Left)
17232                    };
17233                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17234                    new_selections_by_buffer.insert(
17235                        buffer,
17236                        (
17237                            vec![jump_to_offset..jump_to_offset],
17238                            Some(*line_offset_from_top),
17239                        ),
17240                    );
17241                }
17242            }
17243            Some(JumpData::MultiBufferRow {
17244                row,
17245                line_offset_from_top,
17246            }) => {
17247                let point = MultiBufferPoint::new(row.0, 0);
17248                if let Some((buffer, buffer_point, _)) =
17249                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17250                {
17251                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17252                    new_selections_by_buffer
17253                        .entry(buffer)
17254                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17255                        .0
17256                        .push(buffer_offset..buffer_offset)
17257                }
17258            }
17259            None => {
17260                let selections = self.selections.all::<usize>(cx);
17261                let multi_buffer = self.buffer.read(cx);
17262                for selection in selections {
17263                    for (snapshot, range, _, anchor) in multi_buffer
17264                        .snapshot(cx)
17265                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17266                    {
17267                        if let Some(anchor) = anchor {
17268                            // selection is in a deleted hunk
17269                            let Some(buffer_id) = anchor.buffer_id else {
17270                                continue;
17271                            };
17272                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17273                                continue;
17274                            };
17275                            let offset = text::ToOffset::to_offset(
17276                                &anchor.text_anchor,
17277                                &buffer_handle.read(cx).snapshot(),
17278                            );
17279                            let range = offset..offset;
17280                            new_selections_by_buffer
17281                                .entry(buffer_handle)
17282                                .or_insert((Vec::new(), None))
17283                                .0
17284                                .push(range)
17285                        } else {
17286                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17287                            else {
17288                                continue;
17289                            };
17290                            new_selections_by_buffer
17291                                .entry(buffer_handle)
17292                                .or_insert((Vec::new(), None))
17293                                .0
17294                                .push(range)
17295                        }
17296                    }
17297                }
17298            }
17299        }
17300
17301        new_selections_by_buffer
17302            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17303
17304        if new_selections_by_buffer.is_empty() {
17305            return;
17306        }
17307
17308        // We defer the pane interaction because we ourselves are a workspace item
17309        // and activating a new item causes the pane to call a method on us reentrantly,
17310        // which panics if we're on the stack.
17311        window.defer(cx, move |window, cx| {
17312            workspace.update(cx, |workspace, cx| {
17313                let pane = if split {
17314                    workspace.adjacent_pane(window, cx)
17315                } else {
17316                    workspace.active_pane().clone()
17317                };
17318
17319                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17320                    let editor = buffer
17321                        .read(cx)
17322                        .file()
17323                        .is_none()
17324                        .then(|| {
17325                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17326                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17327                            // Instead, we try to activate the existing editor in the pane first.
17328                            let (editor, pane_item_index) =
17329                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17330                                    let editor = item.downcast::<Editor>()?;
17331                                    let singleton_buffer =
17332                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17333                                    if singleton_buffer == buffer {
17334                                        Some((editor, i))
17335                                    } else {
17336                                        None
17337                                    }
17338                                })?;
17339                            pane.update(cx, |pane, cx| {
17340                                pane.activate_item(pane_item_index, true, true, window, cx)
17341                            });
17342                            Some(editor)
17343                        })
17344                        .flatten()
17345                        .unwrap_or_else(|| {
17346                            workspace.open_project_item::<Self>(
17347                                pane.clone(),
17348                                buffer,
17349                                true,
17350                                true,
17351                                window,
17352                                cx,
17353                            )
17354                        });
17355
17356                    editor.update(cx, |editor, cx| {
17357                        let autoscroll = match scroll_offset {
17358                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17359                            None => Autoscroll::newest(),
17360                        };
17361                        let nav_history = editor.nav_history.take();
17362                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17363                            s.select_ranges(ranges);
17364                        });
17365                        editor.nav_history = nav_history;
17366                    });
17367                }
17368            })
17369        });
17370    }
17371
17372    // For now, don't allow opening excerpts in buffers that aren't backed by
17373    // regular project files.
17374    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17375        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17376    }
17377
17378    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17379        let snapshot = self.buffer.read(cx).read(cx);
17380        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17381        Some(
17382            ranges
17383                .iter()
17384                .map(move |range| {
17385                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17386                })
17387                .collect(),
17388        )
17389    }
17390
17391    fn selection_replacement_ranges(
17392        &self,
17393        range: Range<OffsetUtf16>,
17394        cx: &mut App,
17395    ) -> Vec<Range<OffsetUtf16>> {
17396        let selections = self.selections.all::<OffsetUtf16>(cx);
17397        let newest_selection = selections
17398            .iter()
17399            .max_by_key(|selection| selection.id)
17400            .unwrap();
17401        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17402        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17403        let snapshot = self.buffer.read(cx).read(cx);
17404        selections
17405            .into_iter()
17406            .map(|mut selection| {
17407                selection.start.0 =
17408                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17409                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17410                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17411                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17412            })
17413            .collect()
17414    }
17415
17416    fn report_editor_event(
17417        &self,
17418        event_type: &'static str,
17419        file_extension: Option<String>,
17420        cx: &App,
17421    ) {
17422        if cfg!(any(test, feature = "test-support")) {
17423            return;
17424        }
17425
17426        let Some(project) = &self.project else { return };
17427
17428        // If None, we are in a file without an extension
17429        let file = self
17430            .buffer
17431            .read(cx)
17432            .as_singleton()
17433            .and_then(|b| b.read(cx).file());
17434        let file_extension = file_extension.or(file
17435            .as_ref()
17436            .and_then(|file| Path::new(file.file_name(cx)).extension())
17437            .and_then(|e| e.to_str())
17438            .map(|a| a.to_string()));
17439
17440        let vim_mode = cx
17441            .global::<SettingsStore>()
17442            .raw_user_settings()
17443            .get("vim_mode")
17444            == Some(&serde_json::Value::Bool(true));
17445
17446        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17447        let copilot_enabled = edit_predictions_provider
17448            == language::language_settings::EditPredictionProvider::Copilot;
17449        let copilot_enabled_for_language = self
17450            .buffer
17451            .read(cx)
17452            .language_settings(cx)
17453            .show_edit_predictions;
17454
17455        let project = project.read(cx);
17456        telemetry::event!(
17457            event_type,
17458            file_extension,
17459            vim_mode,
17460            copilot_enabled,
17461            copilot_enabled_for_language,
17462            edit_predictions_provider,
17463            is_via_ssh = project.is_via_ssh(),
17464        );
17465    }
17466
17467    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17468    /// with each line being an array of {text, highlight} objects.
17469    fn copy_highlight_json(
17470        &mut self,
17471        _: &CopyHighlightJson,
17472        window: &mut Window,
17473        cx: &mut Context<Self>,
17474    ) {
17475        #[derive(Serialize)]
17476        struct Chunk<'a> {
17477            text: String,
17478            highlight: Option<&'a str>,
17479        }
17480
17481        let snapshot = self.buffer.read(cx).snapshot(cx);
17482        let range = self
17483            .selected_text_range(false, window, cx)
17484            .and_then(|selection| {
17485                if selection.range.is_empty() {
17486                    None
17487                } else {
17488                    Some(selection.range)
17489                }
17490            })
17491            .unwrap_or_else(|| 0..snapshot.len());
17492
17493        let chunks = snapshot.chunks(range, true);
17494        let mut lines = Vec::new();
17495        let mut line: VecDeque<Chunk> = VecDeque::new();
17496
17497        let Some(style) = self.style.as_ref() else {
17498            return;
17499        };
17500
17501        for chunk in chunks {
17502            let highlight = chunk
17503                .syntax_highlight_id
17504                .and_then(|id| id.name(&style.syntax));
17505            let mut chunk_lines = chunk.text.split('\n').peekable();
17506            while let Some(text) = chunk_lines.next() {
17507                let mut merged_with_last_token = false;
17508                if let Some(last_token) = line.back_mut() {
17509                    if last_token.highlight == highlight {
17510                        last_token.text.push_str(text);
17511                        merged_with_last_token = true;
17512                    }
17513                }
17514
17515                if !merged_with_last_token {
17516                    line.push_back(Chunk {
17517                        text: text.into(),
17518                        highlight,
17519                    });
17520                }
17521
17522                if chunk_lines.peek().is_some() {
17523                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17524                        line.pop_front();
17525                    }
17526                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17527                        line.pop_back();
17528                    }
17529
17530                    lines.push(mem::take(&mut line));
17531                }
17532            }
17533        }
17534
17535        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17536            return;
17537        };
17538        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17539    }
17540
17541    pub fn open_context_menu(
17542        &mut self,
17543        _: &OpenContextMenu,
17544        window: &mut Window,
17545        cx: &mut Context<Self>,
17546    ) {
17547        self.request_autoscroll(Autoscroll::newest(), cx);
17548        let position = self.selections.newest_display(cx).start;
17549        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17550    }
17551
17552    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17553        &self.inlay_hint_cache
17554    }
17555
17556    pub fn replay_insert_event(
17557        &mut self,
17558        text: &str,
17559        relative_utf16_range: Option<Range<isize>>,
17560        window: &mut Window,
17561        cx: &mut Context<Self>,
17562    ) {
17563        if !self.input_enabled {
17564            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17565            return;
17566        }
17567        if let Some(relative_utf16_range) = relative_utf16_range {
17568            let selections = self.selections.all::<OffsetUtf16>(cx);
17569            self.change_selections(None, window, cx, |s| {
17570                let new_ranges = selections.into_iter().map(|range| {
17571                    let start = OffsetUtf16(
17572                        range
17573                            .head()
17574                            .0
17575                            .saturating_add_signed(relative_utf16_range.start),
17576                    );
17577                    let end = OffsetUtf16(
17578                        range
17579                            .head()
17580                            .0
17581                            .saturating_add_signed(relative_utf16_range.end),
17582                    );
17583                    start..end
17584                });
17585                s.select_ranges(new_ranges);
17586            });
17587        }
17588
17589        self.handle_input(text, window, cx);
17590    }
17591
17592    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17593        let Some(provider) = self.semantics_provider.as_ref() else {
17594            return false;
17595        };
17596
17597        let mut supports = false;
17598        self.buffer().update(cx, |this, cx| {
17599            this.for_each_buffer(|buffer| {
17600                supports |= provider.supports_inlay_hints(buffer, cx);
17601            });
17602        });
17603
17604        supports
17605    }
17606
17607    pub fn is_focused(&self, window: &Window) -> bool {
17608        self.focus_handle.is_focused(window)
17609    }
17610
17611    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17612        cx.emit(EditorEvent::Focused);
17613
17614        if let Some(descendant) = self
17615            .last_focused_descendant
17616            .take()
17617            .and_then(|descendant| descendant.upgrade())
17618        {
17619            window.focus(&descendant);
17620        } else {
17621            if let Some(blame) = self.blame.as_ref() {
17622                blame.update(cx, GitBlame::focus)
17623            }
17624
17625            self.blink_manager.update(cx, BlinkManager::enable);
17626            self.show_cursor_names(window, cx);
17627            self.buffer.update(cx, |buffer, cx| {
17628                buffer.finalize_last_transaction(cx);
17629                if self.leader_peer_id.is_none() {
17630                    buffer.set_active_selections(
17631                        &self.selections.disjoint_anchors(),
17632                        self.selections.line_mode,
17633                        self.cursor_shape,
17634                        cx,
17635                    );
17636                }
17637            });
17638        }
17639    }
17640
17641    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17642        cx.emit(EditorEvent::FocusedIn)
17643    }
17644
17645    fn handle_focus_out(
17646        &mut self,
17647        event: FocusOutEvent,
17648        _window: &mut Window,
17649        cx: &mut Context<Self>,
17650    ) {
17651        if event.blurred != self.focus_handle {
17652            self.last_focused_descendant = Some(event.blurred);
17653        }
17654        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17655    }
17656
17657    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17658        self.blink_manager.update(cx, BlinkManager::disable);
17659        self.buffer
17660            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17661
17662        if let Some(blame) = self.blame.as_ref() {
17663            blame.update(cx, GitBlame::blur)
17664        }
17665        if !self.hover_state.focused(window, cx) {
17666            hide_hover(self, cx);
17667        }
17668        if !self
17669            .context_menu
17670            .borrow()
17671            .as_ref()
17672            .is_some_and(|context_menu| context_menu.focused(window, cx))
17673        {
17674            self.hide_context_menu(window, cx);
17675        }
17676        self.discard_inline_completion(false, cx);
17677        cx.emit(EditorEvent::Blurred);
17678        cx.notify();
17679    }
17680
17681    pub fn register_action<A: Action>(
17682        &mut self,
17683        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17684    ) -> Subscription {
17685        let id = self.next_editor_action_id.post_inc();
17686        let listener = Arc::new(listener);
17687        self.editor_actions.borrow_mut().insert(
17688            id,
17689            Box::new(move |window, _| {
17690                let listener = listener.clone();
17691                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17692                    let action = action.downcast_ref().unwrap();
17693                    if phase == DispatchPhase::Bubble {
17694                        listener(action, window, cx)
17695                    }
17696                })
17697            }),
17698        );
17699
17700        let editor_actions = self.editor_actions.clone();
17701        Subscription::new(move || {
17702            editor_actions.borrow_mut().remove(&id);
17703        })
17704    }
17705
17706    pub fn file_header_size(&self) -> u32 {
17707        FILE_HEADER_HEIGHT
17708    }
17709
17710    pub fn restore(
17711        &mut self,
17712        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17713        window: &mut Window,
17714        cx: &mut Context<Self>,
17715    ) {
17716        let workspace = self.workspace();
17717        let project = self.project.as_ref();
17718        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17719            let mut tasks = Vec::new();
17720            for (buffer_id, changes) in revert_changes {
17721                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17722                    buffer.update(cx, |buffer, cx| {
17723                        buffer.edit(
17724                            changes
17725                                .into_iter()
17726                                .map(|(range, text)| (range, text.to_string())),
17727                            None,
17728                            cx,
17729                        );
17730                    });
17731
17732                    if let Some(project) =
17733                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17734                    {
17735                        project.update(cx, |project, cx| {
17736                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17737                        })
17738                    }
17739                }
17740            }
17741            tasks
17742        });
17743        cx.spawn_in(window, async move |_, cx| {
17744            for (buffer, task) in save_tasks {
17745                let result = task.await;
17746                if result.is_err() {
17747                    let Some(path) = buffer
17748                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
17749                        .ok()
17750                    else {
17751                        continue;
17752                    };
17753                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17754                        let Some(task) = cx
17755                            .update_window_entity(&workspace, |workspace, window, cx| {
17756                                workspace
17757                                    .open_path_preview(path, None, false, false, false, window, cx)
17758                            })
17759                            .ok()
17760                        else {
17761                            continue;
17762                        };
17763                        task.await.log_err();
17764                    }
17765                }
17766            }
17767        })
17768        .detach();
17769        self.change_selections(None, window, cx, |selections| selections.refresh());
17770    }
17771
17772    pub fn to_pixel_point(
17773        &self,
17774        source: multi_buffer::Anchor,
17775        editor_snapshot: &EditorSnapshot,
17776        window: &mut Window,
17777    ) -> Option<gpui::Point<Pixels>> {
17778        let source_point = source.to_display_point(editor_snapshot);
17779        self.display_to_pixel_point(source_point, editor_snapshot, window)
17780    }
17781
17782    pub fn display_to_pixel_point(
17783        &self,
17784        source: DisplayPoint,
17785        editor_snapshot: &EditorSnapshot,
17786        window: &mut Window,
17787    ) -> Option<gpui::Point<Pixels>> {
17788        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17789        let text_layout_details = self.text_layout_details(window);
17790        let scroll_top = text_layout_details
17791            .scroll_anchor
17792            .scroll_position(editor_snapshot)
17793            .y;
17794
17795        if source.row().as_f32() < scroll_top.floor() {
17796            return None;
17797        }
17798        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17799        let source_y = line_height * (source.row().as_f32() - scroll_top);
17800        Some(gpui::Point::new(source_x, source_y))
17801    }
17802
17803    pub fn has_visible_completions_menu(&self) -> bool {
17804        !self.edit_prediction_preview_is_active()
17805            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17806                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17807            })
17808    }
17809
17810    pub fn register_addon<T: Addon>(&mut self, instance: T) {
17811        self.addons
17812            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17813    }
17814
17815    pub fn unregister_addon<T: Addon>(&mut self) {
17816        self.addons.remove(&std::any::TypeId::of::<T>());
17817    }
17818
17819    pub fn addon<T: Addon>(&self) -> Option<&T> {
17820        let type_id = std::any::TypeId::of::<T>();
17821        self.addons
17822            .get(&type_id)
17823            .and_then(|item| item.to_any().downcast_ref::<T>())
17824    }
17825
17826    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17827        let text_layout_details = self.text_layout_details(window);
17828        let style = &text_layout_details.editor_style;
17829        let font_id = window.text_system().resolve_font(&style.text.font());
17830        let font_size = style.text.font_size.to_pixels(window.rem_size());
17831        let line_height = style.text.line_height_in_pixels(window.rem_size());
17832        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17833
17834        gpui::Size::new(em_width, line_height)
17835    }
17836
17837    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17838        self.load_diff_task.clone()
17839    }
17840
17841    fn read_metadata_from_db(
17842        &mut self,
17843        item_id: u64,
17844        workspace_id: WorkspaceId,
17845        window: &mut Window,
17846        cx: &mut Context<Editor>,
17847    ) {
17848        if self.is_singleton(cx)
17849            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17850        {
17851            let buffer_snapshot = OnceCell::new();
17852
17853            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17854                if !folds.is_empty() {
17855                    let snapshot =
17856                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17857                    self.fold_ranges(
17858                        folds
17859                            .into_iter()
17860                            .map(|(start, end)| {
17861                                snapshot.clip_offset(start, Bias::Left)
17862                                    ..snapshot.clip_offset(end, Bias::Right)
17863                            })
17864                            .collect(),
17865                        false,
17866                        window,
17867                        cx,
17868                    );
17869                }
17870            }
17871
17872            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17873                if !selections.is_empty() {
17874                    let snapshot =
17875                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17876                    self.change_selections(None, window, cx, |s| {
17877                        s.select_ranges(selections.into_iter().map(|(start, end)| {
17878                            snapshot.clip_offset(start, Bias::Left)
17879                                ..snapshot.clip_offset(end, Bias::Right)
17880                        }));
17881                    });
17882                }
17883            };
17884        }
17885
17886        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17887    }
17888}
17889
17890fn insert_extra_newline_brackets(
17891    buffer: &MultiBufferSnapshot,
17892    range: Range<usize>,
17893    language: &language::LanguageScope,
17894) -> bool {
17895    let leading_whitespace_len = buffer
17896        .reversed_chars_at(range.start)
17897        .take_while(|c| c.is_whitespace() && *c != '\n')
17898        .map(|c| c.len_utf8())
17899        .sum::<usize>();
17900    let trailing_whitespace_len = buffer
17901        .chars_at(range.end)
17902        .take_while(|c| c.is_whitespace() && *c != '\n')
17903        .map(|c| c.len_utf8())
17904        .sum::<usize>();
17905    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17906
17907    language.brackets().any(|(pair, enabled)| {
17908        let pair_start = pair.start.trim_end();
17909        let pair_end = pair.end.trim_start();
17910
17911        enabled
17912            && pair.newline
17913            && buffer.contains_str_at(range.end, pair_end)
17914            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17915    })
17916}
17917
17918fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17919    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17920        [(buffer, range, _)] => (*buffer, range.clone()),
17921        _ => return false,
17922    };
17923    let pair = {
17924        let mut result: Option<BracketMatch> = None;
17925
17926        for pair in buffer
17927            .all_bracket_ranges(range.clone())
17928            .filter(move |pair| {
17929                pair.open_range.start <= range.start && pair.close_range.end >= range.end
17930            })
17931        {
17932            let len = pair.close_range.end - pair.open_range.start;
17933
17934            if let Some(existing) = &result {
17935                let existing_len = existing.close_range.end - existing.open_range.start;
17936                if len > existing_len {
17937                    continue;
17938                }
17939            }
17940
17941            result = Some(pair);
17942        }
17943
17944        result
17945    };
17946    let Some(pair) = pair else {
17947        return false;
17948    };
17949    pair.newline_only
17950        && buffer
17951            .chars_for_range(pair.open_range.end..range.start)
17952            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17953            .all(|c| c.is_whitespace() && c != '\n')
17954}
17955
17956fn get_uncommitted_diff_for_buffer(
17957    project: &Entity<Project>,
17958    buffers: impl IntoIterator<Item = Entity<Buffer>>,
17959    buffer: Entity<MultiBuffer>,
17960    cx: &mut App,
17961) -> Task<()> {
17962    let mut tasks = Vec::new();
17963    project.update(cx, |project, cx| {
17964        for buffer in buffers {
17965            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
17966                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17967            }
17968        }
17969    });
17970    cx.spawn(async move |cx| {
17971        let diffs = future::join_all(tasks).await;
17972        buffer
17973            .update(cx, |buffer, cx| {
17974                for diff in diffs.into_iter().flatten() {
17975                    buffer.add_diff(diff, cx);
17976                }
17977            })
17978            .ok();
17979    })
17980}
17981
17982fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17983    let tab_size = tab_size.get() as usize;
17984    let mut width = offset;
17985
17986    for ch in text.chars() {
17987        width += if ch == '\t' {
17988            tab_size - (width % tab_size)
17989        } else {
17990            1
17991        };
17992    }
17993
17994    width - offset
17995}
17996
17997#[cfg(test)]
17998mod tests {
17999    use super::*;
18000
18001    #[test]
18002    fn test_string_size_with_expanded_tabs() {
18003        let nz = |val| NonZeroU32::new(val).unwrap();
18004        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18005        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18006        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18007        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18008        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18009        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18010        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18011        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18012    }
18013}
18014
18015/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18016struct WordBreakingTokenizer<'a> {
18017    input: &'a str,
18018}
18019
18020impl<'a> WordBreakingTokenizer<'a> {
18021    fn new(input: &'a str) -> Self {
18022        Self { input }
18023    }
18024}
18025
18026fn is_char_ideographic(ch: char) -> bool {
18027    use unicode_script::Script::*;
18028    use unicode_script::UnicodeScript;
18029    matches!(ch.script(), Han | Tangut | Yi)
18030}
18031
18032fn is_grapheme_ideographic(text: &str) -> bool {
18033    text.chars().any(is_char_ideographic)
18034}
18035
18036fn is_grapheme_whitespace(text: &str) -> bool {
18037    text.chars().any(|x| x.is_whitespace())
18038}
18039
18040fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18041    text.chars().next().map_or(false, |ch| {
18042        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18043    })
18044}
18045
18046#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18047enum WordBreakToken<'a> {
18048    Word { token: &'a str, grapheme_len: usize },
18049    InlineWhitespace { token: &'a str, grapheme_len: usize },
18050    Newline,
18051}
18052
18053impl<'a> Iterator for WordBreakingTokenizer<'a> {
18054    /// Yields a span, the count of graphemes in the token, and whether it was
18055    /// whitespace. Note that it also breaks at word boundaries.
18056    type Item = WordBreakToken<'a>;
18057
18058    fn next(&mut self) -> Option<Self::Item> {
18059        use unicode_segmentation::UnicodeSegmentation;
18060        if self.input.is_empty() {
18061            return None;
18062        }
18063
18064        let mut iter = self.input.graphemes(true).peekable();
18065        let mut offset = 0;
18066        let mut grapheme_len = 0;
18067        if let Some(first_grapheme) = iter.next() {
18068            let is_newline = first_grapheme == "\n";
18069            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18070            offset += first_grapheme.len();
18071            grapheme_len += 1;
18072            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18073                if let Some(grapheme) = iter.peek().copied() {
18074                    if should_stay_with_preceding_ideograph(grapheme) {
18075                        offset += grapheme.len();
18076                        grapheme_len += 1;
18077                    }
18078                }
18079            } else {
18080                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18081                let mut next_word_bound = words.peek().copied();
18082                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18083                    next_word_bound = words.next();
18084                }
18085                while let Some(grapheme) = iter.peek().copied() {
18086                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18087                        break;
18088                    };
18089                    if is_grapheme_whitespace(grapheme) != is_whitespace
18090                        || (grapheme == "\n") != is_newline
18091                    {
18092                        break;
18093                    };
18094                    offset += grapheme.len();
18095                    grapheme_len += 1;
18096                    iter.next();
18097                }
18098            }
18099            let token = &self.input[..offset];
18100            self.input = &self.input[offset..];
18101            if token == "\n" {
18102                Some(WordBreakToken::Newline)
18103            } else if is_whitespace {
18104                Some(WordBreakToken::InlineWhitespace {
18105                    token,
18106                    grapheme_len,
18107                })
18108            } else {
18109                Some(WordBreakToken::Word {
18110                    token,
18111                    grapheme_len,
18112                })
18113            }
18114        } else {
18115            None
18116        }
18117    }
18118}
18119
18120#[test]
18121fn test_word_breaking_tokenizer() {
18122    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18123        ("", &[]),
18124        ("  ", &[whitespace("  ", 2)]),
18125        ("Ʒ", &[word("Ʒ", 1)]),
18126        ("Ǽ", &[word("Ǽ", 1)]),
18127        ("", &[word("", 1)]),
18128        ("⋑⋑", &[word("⋑⋑", 2)]),
18129        (
18130            "原理,进而",
18131            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18132        ),
18133        (
18134            "hello world",
18135            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18136        ),
18137        (
18138            "hello, world",
18139            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18140        ),
18141        (
18142            "  hello world",
18143            &[
18144                whitespace("  ", 2),
18145                word("hello", 5),
18146                whitespace(" ", 1),
18147                word("world", 5),
18148            ],
18149        ),
18150        (
18151            "这是什么 \n 钢笔",
18152            &[
18153                word("", 1),
18154                word("", 1),
18155                word("", 1),
18156                word("", 1),
18157                whitespace(" ", 1),
18158                newline(),
18159                whitespace(" ", 1),
18160                word("", 1),
18161                word("", 1),
18162            ],
18163        ),
18164        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18165    ];
18166
18167    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18168        WordBreakToken::Word {
18169            token,
18170            grapheme_len,
18171        }
18172    }
18173
18174    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18175        WordBreakToken::InlineWhitespace {
18176            token,
18177            grapheme_len,
18178        }
18179    }
18180
18181    fn newline() -> WordBreakToken<'static> {
18182        WordBreakToken::Newline
18183    }
18184
18185    for (input, result) in tests {
18186        assert_eq!(
18187            WordBreakingTokenizer::new(input)
18188                .collect::<Vec<_>>()
18189                .as_slice(),
18190            *result,
18191        );
18192    }
18193}
18194
18195fn wrap_with_prefix(
18196    line_prefix: String,
18197    unwrapped_text: String,
18198    wrap_column: usize,
18199    tab_size: NonZeroU32,
18200    preserve_existing_whitespace: bool,
18201) -> String {
18202    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18203    let mut wrapped_text = String::new();
18204    let mut current_line = line_prefix.clone();
18205
18206    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18207    let mut current_line_len = line_prefix_len;
18208    let mut in_whitespace = false;
18209    for token in tokenizer {
18210        let have_preceding_whitespace = in_whitespace;
18211        match token {
18212            WordBreakToken::Word {
18213                token,
18214                grapheme_len,
18215            } => {
18216                in_whitespace = false;
18217                if current_line_len + grapheme_len > wrap_column
18218                    && current_line_len != line_prefix_len
18219                {
18220                    wrapped_text.push_str(current_line.trim_end());
18221                    wrapped_text.push('\n');
18222                    current_line.truncate(line_prefix.len());
18223                    current_line_len = line_prefix_len;
18224                }
18225                current_line.push_str(token);
18226                current_line_len += grapheme_len;
18227            }
18228            WordBreakToken::InlineWhitespace {
18229                mut token,
18230                mut grapheme_len,
18231            } => {
18232                in_whitespace = true;
18233                if have_preceding_whitespace && !preserve_existing_whitespace {
18234                    continue;
18235                }
18236                if !preserve_existing_whitespace {
18237                    token = " ";
18238                    grapheme_len = 1;
18239                }
18240                if current_line_len + grapheme_len > wrap_column {
18241                    wrapped_text.push_str(current_line.trim_end());
18242                    wrapped_text.push('\n');
18243                    current_line.truncate(line_prefix.len());
18244                    current_line_len = line_prefix_len;
18245                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18246                    current_line.push_str(token);
18247                    current_line_len += grapheme_len;
18248                }
18249            }
18250            WordBreakToken::Newline => {
18251                in_whitespace = true;
18252                if preserve_existing_whitespace {
18253                    wrapped_text.push_str(current_line.trim_end());
18254                    wrapped_text.push('\n');
18255                    current_line.truncate(line_prefix.len());
18256                    current_line_len = line_prefix_len;
18257                } else if have_preceding_whitespace {
18258                    continue;
18259                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18260                {
18261                    wrapped_text.push_str(current_line.trim_end());
18262                    wrapped_text.push('\n');
18263                    current_line.truncate(line_prefix.len());
18264                    current_line_len = line_prefix_len;
18265                } else if current_line_len != line_prefix_len {
18266                    current_line.push(' ');
18267                    current_line_len += 1;
18268                }
18269            }
18270        }
18271    }
18272
18273    if !current_line.is_empty() {
18274        wrapped_text.push_str(&current_line);
18275    }
18276    wrapped_text
18277}
18278
18279#[test]
18280fn test_wrap_with_prefix() {
18281    assert_eq!(
18282        wrap_with_prefix(
18283            "# ".to_string(),
18284            "abcdefg".to_string(),
18285            4,
18286            NonZeroU32::new(4).unwrap(),
18287            false,
18288        ),
18289        "# abcdefg"
18290    );
18291    assert_eq!(
18292        wrap_with_prefix(
18293            "".to_string(),
18294            "\thello world".to_string(),
18295            8,
18296            NonZeroU32::new(4).unwrap(),
18297            false,
18298        ),
18299        "hello\nworld"
18300    );
18301    assert_eq!(
18302        wrap_with_prefix(
18303            "// ".to_string(),
18304            "xx \nyy zz aa bb cc".to_string(),
18305            12,
18306            NonZeroU32::new(4).unwrap(),
18307            false,
18308        ),
18309        "// xx yy zz\n// aa bb cc"
18310    );
18311    assert_eq!(
18312        wrap_with_prefix(
18313            String::new(),
18314            "这是什么 \n 钢笔".to_string(),
18315            3,
18316            NonZeroU32::new(4).unwrap(),
18317            false,
18318        ),
18319        "这是什\n么 钢\n"
18320    );
18321}
18322
18323pub trait CollaborationHub {
18324    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18325    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18326    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18327}
18328
18329impl CollaborationHub for Entity<Project> {
18330    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18331        self.read(cx).collaborators()
18332    }
18333
18334    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18335        self.read(cx).user_store().read(cx).participant_indices()
18336    }
18337
18338    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18339        let this = self.read(cx);
18340        let user_ids = this.collaborators().values().map(|c| c.user_id);
18341        this.user_store().read_with(cx, |user_store, cx| {
18342            user_store.participant_names(user_ids, cx)
18343        })
18344    }
18345}
18346
18347pub trait SemanticsProvider {
18348    fn hover(
18349        &self,
18350        buffer: &Entity<Buffer>,
18351        position: text::Anchor,
18352        cx: &mut App,
18353    ) -> Option<Task<Vec<project::Hover>>>;
18354
18355    fn inlay_hints(
18356        &self,
18357        buffer_handle: Entity<Buffer>,
18358        range: Range<text::Anchor>,
18359        cx: &mut App,
18360    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18361
18362    fn resolve_inlay_hint(
18363        &self,
18364        hint: InlayHint,
18365        buffer_handle: Entity<Buffer>,
18366        server_id: LanguageServerId,
18367        cx: &mut App,
18368    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18369
18370    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18371
18372    fn document_highlights(
18373        &self,
18374        buffer: &Entity<Buffer>,
18375        position: text::Anchor,
18376        cx: &mut App,
18377    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18378
18379    fn definitions(
18380        &self,
18381        buffer: &Entity<Buffer>,
18382        position: text::Anchor,
18383        kind: GotoDefinitionKind,
18384        cx: &mut App,
18385    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18386
18387    fn range_for_rename(
18388        &self,
18389        buffer: &Entity<Buffer>,
18390        position: text::Anchor,
18391        cx: &mut App,
18392    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18393
18394    fn perform_rename(
18395        &self,
18396        buffer: &Entity<Buffer>,
18397        position: text::Anchor,
18398        new_name: String,
18399        cx: &mut App,
18400    ) -> Option<Task<Result<ProjectTransaction>>>;
18401}
18402
18403pub trait CompletionProvider {
18404    fn completions(
18405        &self,
18406        excerpt_id: ExcerptId,
18407        buffer: &Entity<Buffer>,
18408        buffer_position: text::Anchor,
18409        trigger: CompletionContext,
18410        window: &mut Window,
18411        cx: &mut Context<Editor>,
18412    ) -> Task<Result<Option<Vec<Completion>>>>;
18413
18414    fn resolve_completions(
18415        &self,
18416        buffer: Entity<Buffer>,
18417        completion_indices: Vec<usize>,
18418        completions: Rc<RefCell<Box<[Completion]>>>,
18419        cx: &mut Context<Editor>,
18420    ) -> Task<Result<bool>>;
18421
18422    fn apply_additional_edits_for_completion(
18423        &self,
18424        _buffer: Entity<Buffer>,
18425        _completions: Rc<RefCell<Box<[Completion]>>>,
18426        _completion_index: usize,
18427        _push_to_history: bool,
18428        _cx: &mut Context<Editor>,
18429    ) -> Task<Result<Option<language::Transaction>>> {
18430        Task::ready(Ok(None))
18431    }
18432
18433    fn is_completion_trigger(
18434        &self,
18435        buffer: &Entity<Buffer>,
18436        position: language::Anchor,
18437        text: &str,
18438        trigger_in_words: bool,
18439        cx: &mut Context<Editor>,
18440    ) -> bool;
18441
18442    fn sort_completions(&self) -> bool {
18443        true
18444    }
18445
18446    fn filter_completions(&self) -> bool {
18447        true
18448    }
18449}
18450
18451pub trait CodeActionProvider {
18452    fn id(&self) -> Arc<str>;
18453
18454    fn code_actions(
18455        &self,
18456        buffer: &Entity<Buffer>,
18457        range: Range<text::Anchor>,
18458        window: &mut Window,
18459        cx: &mut App,
18460    ) -> Task<Result<Vec<CodeAction>>>;
18461
18462    fn apply_code_action(
18463        &self,
18464        buffer_handle: Entity<Buffer>,
18465        action: CodeAction,
18466        excerpt_id: ExcerptId,
18467        push_to_history: bool,
18468        window: &mut Window,
18469        cx: &mut App,
18470    ) -> Task<Result<ProjectTransaction>>;
18471}
18472
18473impl CodeActionProvider for Entity<Project> {
18474    fn id(&self) -> Arc<str> {
18475        "project".into()
18476    }
18477
18478    fn code_actions(
18479        &self,
18480        buffer: &Entity<Buffer>,
18481        range: Range<text::Anchor>,
18482        _window: &mut Window,
18483        cx: &mut App,
18484    ) -> Task<Result<Vec<CodeAction>>> {
18485        self.update(cx, |project, cx| {
18486            let code_lens = project.code_lens(buffer, range.clone(), cx);
18487            let code_actions = project.code_actions(buffer, range, None, cx);
18488            cx.background_spawn(async move {
18489                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18490                Ok(code_lens
18491                    .context("code lens fetch")?
18492                    .into_iter()
18493                    .chain(code_actions.context("code action fetch")?)
18494                    .collect())
18495            })
18496        })
18497    }
18498
18499    fn apply_code_action(
18500        &self,
18501        buffer_handle: Entity<Buffer>,
18502        action: CodeAction,
18503        _excerpt_id: ExcerptId,
18504        push_to_history: bool,
18505        _window: &mut Window,
18506        cx: &mut App,
18507    ) -> Task<Result<ProjectTransaction>> {
18508        self.update(cx, |project, cx| {
18509            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18510        })
18511    }
18512}
18513
18514fn snippet_completions(
18515    project: &Project,
18516    buffer: &Entity<Buffer>,
18517    buffer_position: text::Anchor,
18518    cx: &mut App,
18519) -> Task<Result<Vec<Completion>>> {
18520    let language = buffer.read(cx).language_at(buffer_position);
18521    let language_name = language.as_ref().map(|language| language.lsp_id());
18522    let snippet_store = project.snippets().read(cx);
18523    let snippets = snippet_store.snippets_for(language_name, cx);
18524
18525    if snippets.is_empty() {
18526        return Task::ready(Ok(vec![]));
18527    }
18528    let snapshot = buffer.read(cx).text_snapshot();
18529    let chars: String = snapshot
18530        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18531        .collect();
18532
18533    let scope = language.map(|language| language.default_scope());
18534    let executor = cx.background_executor().clone();
18535
18536    cx.background_spawn(async move {
18537        let classifier = CharClassifier::new(scope).for_completion(true);
18538        let mut last_word = chars
18539            .chars()
18540            .take_while(|c| classifier.is_word(*c))
18541            .collect::<String>();
18542        last_word = last_word.chars().rev().collect();
18543
18544        if last_word.is_empty() {
18545            return Ok(vec![]);
18546        }
18547
18548        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18549        let to_lsp = |point: &text::Anchor| {
18550            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18551            point_to_lsp(end)
18552        };
18553        let lsp_end = to_lsp(&buffer_position);
18554
18555        let candidates = snippets
18556            .iter()
18557            .enumerate()
18558            .flat_map(|(ix, snippet)| {
18559                snippet
18560                    .prefix
18561                    .iter()
18562                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18563            })
18564            .collect::<Vec<StringMatchCandidate>>();
18565
18566        let mut matches = fuzzy::match_strings(
18567            &candidates,
18568            &last_word,
18569            last_word.chars().any(|c| c.is_uppercase()),
18570            100,
18571            &Default::default(),
18572            executor,
18573        )
18574        .await;
18575
18576        // Remove all candidates where the query's start does not match the start of any word in the candidate
18577        if let Some(query_start) = last_word.chars().next() {
18578            matches.retain(|string_match| {
18579                split_words(&string_match.string).any(|word| {
18580                    // Check that the first codepoint of the word as lowercase matches the first
18581                    // codepoint of the query as lowercase
18582                    word.chars()
18583                        .flat_map(|codepoint| codepoint.to_lowercase())
18584                        .zip(query_start.to_lowercase())
18585                        .all(|(word_cp, query_cp)| word_cp == query_cp)
18586                })
18587            });
18588        }
18589
18590        let matched_strings = matches
18591            .into_iter()
18592            .map(|m| m.string)
18593            .collect::<HashSet<_>>();
18594
18595        let result: Vec<Completion> = snippets
18596            .into_iter()
18597            .filter_map(|snippet| {
18598                let matching_prefix = snippet
18599                    .prefix
18600                    .iter()
18601                    .find(|prefix| matched_strings.contains(*prefix))?;
18602                let start = as_offset - last_word.len();
18603                let start = snapshot.anchor_before(start);
18604                let range = start..buffer_position;
18605                let lsp_start = to_lsp(&start);
18606                let lsp_range = lsp::Range {
18607                    start: lsp_start,
18608                    end: lsp_end,
18609                };
18610                Some(Completion {
18611                    old_range: range,
18612                    new_text: snippet.body.clone(),
18613                    source: CompletionSource::Lsp {
18614                        server_id: LanguageServerId(usize::MAX),
18615                        resolved: true,
18616                        lsp_completion: Box::new(lsp::CompletionItem {
18617                            label: snippet.prefix.first().unwrap().clone(),
18618                            kind: Some(CompletionItemKind::SNIPPET),
18619                            label_details: snippet.description.as_ref().map(|description| {
18620                                lsp::CompletionItemLabelDetails {
18621                                    detail: Some(description.clone()),
18622                                    description: None,
18623                                }
18624                            }),
18625                            insert_text_format: Some(InsertTextFormat::SNIPPET),
18626                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18627                                lsp::InsertReplaceEdit {
18628                                    new_text: snippet.body.clone(),
18629                                    insert: lsp_range,
18630                                    replace: lsp_range,
18631                                },
18632                            )),
18633                            filter_text: Some(snippet.body.clone()),
18634                            sort_text: Some(char::MAX.to_string()),
18635                            ..lsp::CompletionItem::default()
18636                        }),
18637                        lsp_defaults: None,
18638                    },
18639                    label: CodeLabel {
18640                        text: matching_prefix.clone(),
18641                        runs: Vec::new(),
18642                        filter_range: 0..matching_prefix.len(),
18643                    },
18644                    icon_path: None,
18645                    documentation: snippet
18646                        .description
18647                        .clone()
18648                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
18649                    insert_text_mode: None,
18650                    confirm: None,
18651                })
18652            })
18653            .collect();
18654
18655        Ok(result)
18656    })
18657}
18658
18659impl CompletionProvider for Entity<Project> {
18660    fn completions(
18661        &self,
18662        _excerpt_id: ExcerptId,
18663        buffer: &Entity<Buffer>,
18664        buffer_position: text::Anchor,
18665        options: CompletionContext,
18666        _window: &mut Window,
18667        cx: &mut Context<Editor>,
18668    ) -> Task<Result<Option<Vec<Completion>>>> {
18669        self.update(cx, |project, cx| {
18670            let snippets = snippet_completions(project, buffer, buffer_position, cx);
18671            let project_completions = project.completions(buffer, buffer_position, options, cx);
18672            cx.background_spawn(async move {
18673                let snippets_completions = snippets.await?;
18674                match project_completions.await? {
18675                    Some(mut completions) => {
18676                        completions.extend(snippets_completions);
18677                        Ok(Some(completions))
18678                    }
18679                    None => {
18680                        if snippets_completions.is_empty() {
18681                            Ok(None)
18682                        } else {
18683                            Ok(Some(snippets_completions))
18684                        }
18685                    }
18686                }
18687            })
18688        })
18689    }
18690
18691    fn resolve_completions(
18692        &self,
18693        buffer: Entity<Buffer>,
18694        completion_indices: Vec<usize>,
18695        completions: Rc<RefCell<Box<[Completion]>>>,
18696        cx: &mut Context<Editor>,
18697    ) -> Task<Result<bool>> {
18698        self.update(cx, |project, cx| {
18699            project.lsp_store().update(cx, |lsp_store, cx| {
18700                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18701            })
18702        })
18703    }
18704
18705    fn apply_additional_edits_for_completion(
18706        &self,
18707        buffer: Entity<Buffer>,
18708        completions: Rc<RefCell<Box<[Completion]>>>,
18709        completion_index: usize,
18710        push_to_history: bool,
18711        cx: &mut Context<Editor>,
18712    ) -> Task<Result<Option<language::Transaction>>> {
18713        self.update(cx, |project, cx| {
18714            project.lsp_store().update(cx, |lsp_store, cx| {
18715                lsp_store.apply_additional_edits_for_completion(
18716                    buffer,
18717                    completions,
18718                    completion_index,
18719                    push_to_history,
18720                    cx,
18721                )
18722            })
18723        })
18724    }
18725
18726    fn is_completion_trigger(
18727        &self,
18728        buffer: &Entity<Buffer>,
18729        position: language::Anchor,
18730        text: &str,
18731        trigger_in_words: bool,
18732        cx: &mut Context<Editor>,
18733    ) -> bool {
18734        let mut chars = text.chars();
18735        let char = if let Some(char) = chars.next() {
18736            char
18737        } else {
18738            return false;
18739        };
18740        if chars.next().is_some() {
18741            return false;
18742        }
18743
18744        let buffer = buffer.read(cx);
18745        let snapshot = buffer.snapshot();
18746        if !snapshot.settings_at(position, cx).show_completions_on_input {
18747            return false;
18748        }
18749        let classifier = snapshot.char_classifier_at(position).for_completion(true);
18750        if trigger_in_words && classifier.is_word(char) {
18751            return true;
18752        }
18753
18754        buffer.completion_triggers().contains(text)
18755    }
18756}
18757
18758impl SemanticsProvider for Entity<Project> {
18759    fn hover(
18760        &self,
18761        buffer: &Entity<Buffer>,
18762        position: text::Anchor,
18763        cx: &mut App,
18764    ) -> Option<Task<Vec<project::Hover>>> {
18765        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18766    }
18767
18768    fn document_highlights(
18769        &self,
18770        buffer: &Entity<Buffer>,
18771        position: text::Anchor,
18772        cx: &mut App,
18773    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18774        Some(self.update(cx, |project, cx| {
18775            project.document_highlights(buffer, position, cx)
18776        }))
18777    }
18778
18779    fn definitions(
18780        &self,
18781        buffer: &Entity<Buffer>,
18782        position: text::Anchor,
18783        kind: GotoDefinitionKind,
18784        cx: &mut App,
18785    ) -> Option<Task<Result<Vec<LocationLink>>>> {
18786        Some(self.update(cx, |project, cx| match kind {
18787            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18788            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18789            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18790            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18791        }))
18792    }
18793
18794    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18795        // TODO: make this work for remote projects
18796        self.update(cx, |this, cx| {
18797            buffer.update(cx, |buffer, cx| {
18798                this.any_language_server_supports_inlay_hints(buffer, cx)
18799            })
18800        })
18801    }
18802
18803    fn inlay_hints(
18804        &self,
18805        buffer_handle: Entity<Buffer>,
18806        range: Range<text::Anchor>,
18807        cx: &mut App,
18808    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18809        Some(self.update(cx, |project, cx| {
18810            project.inlay_hints(buffer_handle, range, cx)
18811        }))
18812    }
18813
18814    fn resolve_inlay_hint(
18815        &self,
18816        hint: InlayHint,
18817        buffer_handle: Entity<Buffer>,
18818        server_id: LanguageServerId,
18819        cx: &mut App,
18820    ) -> Option<Task<anyhow::Result<InlayHint>>> {
18821        Some(self.update(cx, |project, cx| {
18822            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18823        }))
18824    }
18825
18826    fn range_for_rename(
18827        &self,
18828        buffer: &Entity<Buffer>,
18829        position: text::Anchor,
18830        cx: &mut App,
18831    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18832        Some(self.update(cx, |project, cx| {
18833            let buffer = buffer.clone();
18834            let task = project.prepare_rename(buffer.clone(), position, cx);
18835            cx.spawn(async move |_, cx| {
18836                Ok(match task.await? {
18837                    PrepareRenameResponse::Success(range) => Some(range),
18838                    PrepareRenameResponse::InvalidPosition => None,
18839                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18840                        // Fallback on using TreeSitter info to determine identifier range
18841                        buffer.update(cx, |buffer, _| {
18842                            let snapshot = buffer.snapshot();
18843                            let (range, kind) = snapshot.surrounding_word(position);
18844                            if kind != Some(CharKind::Word) {
18845                                return None;
18846                            }
18847                            Some(
18848                                snapshot.anchor_before(range.start)
18849                                    ..snapshot.anchor_after(range.end),
18850                            )
18851                        })?
18852                    }
18853                })
18854            })
18855        }))
18856    }
18857
18858    fn perform_rename(
18859        &self,
18860        buffer: &Entity<Buffer>,
18861        position: text::Anchor,
18862        new_name: String,
18863        cx: &mut App,
18864    ) -> Option<Task<Result<ProjectTransaction>>> {
18865        Some(self.update(cx, |project, cx| {
18866            project.perform_rename(buffer.clone(), position, new_name, cx)
18867        }))
18868    }
18869}
18870
18871fn inlay_hint_settings(
18872    location: Anchor,
18873    snapshot: &MultiBufferSnapshot,
18874    cx: &mut Context<Editor>,
18875) -> InlayHintSettings {
18876    let file = snapshot.file_at(location);
18877    let language = snapshot.language_at(location).map(|l| l.name());
18878    language_settings(language, file, cx).inlay_hints
18879}
18880
18881fn consume_contiguous_rows(
18882    contiguous_row_selections: &mut Vec<Selection<Point>>,
18883    selection: &Selection<Point>,
18884    display_map: &DisplaySnapshot,
18885    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18886) -> (MultiBufferRow, MultiBufferRow) {
18887    contiguous_row_selections.push(selection.clone());
18888    let start_row = MultiBufferRow(selection.start.row);
18889    let mut end_row = ending_row(selection, display_map);
18890
18891    while let Some(next_selection) = selections.peek() {
18892        if next_selection.start.row <= end_row.0 {
18893            end_row = ending_row(next_selection, display_map);
18894            contiguous_row_selections.push(selections.next().unwrap().clone());
18895        } else {
18896            break;
18897        }
18898    }
18899    (start_row, end_row)
18900}
18901
18902fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18903    if next_selection.end.column > 0 || next_selection.is_empty() {
18904        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18905    } else {
18906        MultiBufferRow(next_selection.end.row)
18907    }
18908}
18909
18910impl EditorSnapshot {
18911    pub fn remote_selections_in_range<'a>(
18912        &'a self,
18913        range: &'a Range<Anchor>,
18914        collaboration_hub: &dyn CollaborationHub,
18915        cx: &'a App,
18916    ) -> impl 'a + Iterator<Item = RemoteSelection> {
18917        let participant_names = collaboration_hub.user_names(cx);
18918        let participant_indices = collaboration_hub.user_participant_indices(cx);
18919        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18920        let collaborators_by_replica_id = collaborators_by_peer_id
18921            .iter()
18922            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18923            .collect::<HashMap<_, _>>();
18924        self.buffer_snapshot
18925            .selections_in_range(range, false)
18926            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18927                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18928                let participant_index = participant_indices.get(&collaborator.user_id).copied();
18929                let user_name = participant_names.get(&collaborator.user_id).cloned();
18930                Some(RemoteSelection {
18931                    replica_id,
18932                    selection,
18933                    cursor_shape,
18934                    line_mode,
18935                    participant_index,
18936                    peer_id: collaborator.peer_id,
18937                    user_name,
18938                })
18939            })
18940    }
18941
18942    pub fn hunks_for_ranges(
18943        &self,
18944        ranges: impl IntoIterator<Item = Range<Point>>,
18945    ) -> Vec<MultiBufferDiffHunk> {
18946        let mut hunks = Vec::new();
18947        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18948            HashMap::default();
18949        for query_range in ranges {
18950            let query_rows =
18951                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18952            for hunk in self.buffer_snapshot.diff_hunks_in_range(
18953                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18954            ) {
18955                // Include deleted hunks that are adjacent to the query range, because
18956                // otherwise they would be missed.
18957                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18958                if hunk.status().is_deleted() {
18959                    intersects_range |= hunk.row_range.start == query_rows.end;
18960                    intersects_range |= hunk.row_range.end == query_rows.start;
18961                }
18962                if intersects_range {
18963                    if !processed_buffer_rows
18964                        .entry(hunk.buffer_id)
18965                        .or_default()
18966                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18967                    {
18968                        continue;
18969                    }
18970                    hunks.push(hunk);
18971                }
18972            }
18973        }
18974
18975        hunks
18976    }
18977
18978    fn display_diff_hunks_for_rows<'a>(
18979        &'a self,
18980        display_rows: Range<DisplayRow>,
18981        folded_buffers: &'a HashSet<BufferId>,
18982    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18983        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18984        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18985
18986        self.buffer_snapshot
18987            .diff_hunks_in_range(buffer_start..buffer_end)
18988            .filter_map(|hunk| {
18989                if folded_buffers.contains(&hunk.buffer_id) {
18990                    return None;
18991                }
18992
18993                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18994                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18995
18996                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18997                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18998
18999                let display_hunk = if hunk_display_start.column() != 0 {
19000                    DisplayDiffHunk::Folded {
19001                        display_row: hunk_display_start.row(),
19002                    }
19003                } else {
19004                    let mut end_row = hunk_display_end.row();
19005                    if hunk_display_end.column() > 0 {
19006                        end_row.0 += 1;
19007                    }
19008                    let is_created_file = hunk.is_created_file();
19009                    DisplayDiffHunk::Unfolded {
19010                        status: hunk.status(),
19011                        diff_base_byte_range: hunk.diff_base_byte_range,
19012                        display_row_range: hunk_display_start.row()..end_row,
19013                        multi_buffer_range: Anchor::range_in_buffer(
19014                            hunk.excerpt_id,
19015                            hunk.buffer_id,
19016                            hunk.buffer_range,
19017                        ),
19018                        is_created_file,
19019                    }
19020                };
19021
19022                Some(display_hunk)
19023            })
19024    }
19025
19026    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19027        self.display_snapshot.buffer_snapshot.language_at(position)
19028    }
19029
19030    pub fn is_focused(&self) -> bool {
19031        self.is_focused
19032    }
19033
19034    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19035        self.placeholder_text.as_ref()
19036    }
19037
19038    pub fn scroll_position(&self) -> gpui::Point<f32> {
19039        self.scroll_anchor.scroll_position(&self.display_snapshot)
19040    }
19041
19042    fn gutter_dimensions(
19043        &self,
19044        font_id: FontId,
19045        font_size: Pixels,
19046        max_line_number_width: Pixels,
19047        cx: &App,
19048    ) -> Option<GutterDimensions> {
19049        if !self.show_gutter {
19050            return None;
19051        }
19052
19053        let descent = cx.text_system().descent(font_id, font_size);
19054        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19055        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19056
19057        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19058            matches!(
19059                ProjectSettings::get_global(cx).git.git_gutter,
19060                Some(GitGutterSetting::TrackedFiles)
19061            )
19062        });
19063        let gutter_settings = EditorSettings::get_global(cx).gutter;
19064        let show_line_numbers = self
19065            .show_line_numbers
19066            .unwrap_or(gutter_settings.line_numbers);
19067        let line_gutter_width = if show_line_numbers {
19068            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19069            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19070            max_line_number_width.max(min_width_for_number_on_gutter)
19071        } else {
19072            0.0.into()
19073        };
19074
19075        let show_code_actions = self
19076            .show_code_actions
19077            .unwrap_or(gutter_settings.code_actions);
19078
19079        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19080        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19081
19082        let git_blame_entries_width =
19083            self.git_blame_gutter_max_author_length
19084                .map(|max_author_length| {
19085                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19086                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19087
19088                    /// The number of characters to dedicate to gaps and margins.
19089                    const SPACING_WIDTH: usize = 4;
19090
19091                    let max_char_count = max_author_length.min(renderer.max_author_length())
19092                        + ::git::SHORT_SHA_LENGTH
19093                        + MAX_RELATIVE_TIMESTAMP.len()
19094                        + SPACING_WIDTH;
19095
19096                    em_advance * max_char_count
19097                });
19098
19099        let is_singleton = self.buffer_snapshot.is_singleton();
19100
19101        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19102        left_padding += if !is_singleton {
19103            em_width * 4.0
19104        } else if show_code_actions || show_runnables || show_breakpoints {
19105            em_width * 3.0
19106        } else if show_git_gutter && show_line_numbers {
19107            em_width * 2.0
19108        } else if show_git_gutter || show_line_numbers {
19109            em_width
19110        } else {
19111            px(0.)
19112        };
19113
19114        let shows_folds = is_singleton && gutter_settings.folds;
19115
19116        let right_padding = if shows_folds && show_line_numbers {
19117            em_width * 4.0
19118        } else if shows_folds || (!is_singleton && show_line_numbers) {
19119            em_width * 3.0
19120        } else if show_line_numbers {
19121            em_width
19122        } else {
19123            px(0.)
19124        };
19125
19126        Some(GutterDimensions {
19127            left_padding,
19128            right_padding,
19129            width: line_gutter_width + left_padding + right_padding,
19130            margin: -descent,
19131            git_blame_entries_width,
19132        })
19133    }
19134
19135    pub fn render_crease_toggle(
19136        &self,
19137        buffer_row: MultiBufferRow,
19138        row_contains_cursor: bool,
19139        editor: Entity<Editor>,
19140        window: &mut Window,
19141        cx: &mut App,
19142    ) -> Option<AnyElement> {
19143        let folded = self.is_line_folded(buffer_row);
19144        let mut is_foldable = false;
19145
19146        if let Some(crease) = self
19147            .crease_snapshot
19148            .query_row(buffer_row, &self.buffer_snapshot)
19149        {
19150            is_foldable = true;
19151            match crease {
19152                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19153                    if let Some(render_toggle) = render_toggle {
19154                        let toggle_callback =
19155                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19156                                if folded {
19157                                    editor.update(cx, |editor, cx| {
19158                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
19159                                    });
19160                                } else {
19161                                    editor.update(cx, |editor, cx| {
19162                                        editor.unfold_at(
19163                                            &crate::UnfoldAt { buffer_row },
19164                                            window,
19165                                            cx,
19166                                        )
19167                                    });
19168                                }
19169                            });
19170                        return Some((render_toggle)(
19171                            buffer_row,
19172                            folded,
19173                            toggle_callback,
19174                            window,
19175                            cx,
19176                        ));
19177                    }
19178                }
19179            }
19180        }
19181
19182        is_foldable |= self.starts_indent(buffer_row);
19183
19184        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19185            Some(
19186                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19187                    .toggle_state(folded)
19188                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19189                        if folded {
19190                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
19191                        } else {
19192                            this.fold_at(&FoldAt { buffer_row }, window, cx);
19193                        }
19194                    }))
19195                    .into_any_element(),
19196            )
19197        } else {
19198            None
19199        }
19200    }
19201
19202    pub fn render_crease_trailer(
19203        &self,
19204        buffer_row: MultiBufferRow,
19205        window: &mut Window,
19206        cx: &mut App,
19207    ) -> Option<AnyElement> {
19208        let folded = self.is_line_folded(buffer_row);
19209        if let Crease::Inline { render_trailer, .. } = self
19210            .crease_snapshot
19211            .query_row(buffer_row, &self.buffer_snapshot)?
19212        {
19213            let render_trailer = render_trailer.as_ref()?;
19214            Some(render_trailer(buffer_row, folded, window, cx))
19215        } else {
19216            None
19217        }
19218    }
19219}
19220
19221impl Deref for EditorSnapshot {
19222    type Target = DisplaySnapshot;
19223
19224    fn deref(&self) -> &Self::Target {
19225        &self.display_snapshot
19226    }
19227}
19228
19229#[derive(Clone, Debug, PartialEq, Eq)]
19230pub enum EditorEvent {
19231    InputIgnored {
19232        text: Arc<str>,
19233    },
19234    InputHandled {
19235        utf16_range_to_replace: Option<Range<isize>>,
19236        text: Arc<str>,
19237    },
19238    ExcerptsAdded {
19239        buffer: Entity<Buffer>,
19240        predecessor: ExcerptId,
19241        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19242    },
19243    ExcerptsRemoved {
19244        ids: Vec<ExcerptId>,
19245    },
19246    BufferFoldToggled {
19247        ids: Vec<ExcerptId>,
19248        folded: bool,
19249    },
19250    ExcerptsEdited {
19251        ids: Vec<ExcerptId>,
19252    },
19253    ExcerptsExpanded {
19254        ids: Vec<ExcerptId>,
19255    },
19256    BufferEdited,
19257    Edited {
19258        transaction_id: clock::Lamport,
19259    },
19260    Reparsed(BufferId),
19261    Focused,
19262    FocusedIn,
19263    Blurred,
19264    DirtyChanged,
19265    Saved,
19266    TitleChanged,
19267    DiffBaseChanged,
19268    SelectionsChanged {
19269        local: bool,
19270    },
19271    ScrollPositionChanged {
19272        local: bool,
19273        autoscroll: bool,
19274    },
19275    Closed,
19276    TransactionUndone {
19277        transaction_id: clock::Lamport,
19278    },
19279    TransactionBegun {
19280        transaction_id: clock::Lamport,
19281    },
19282    Reloaded,
19283    CursorShapeChanged,
19284    PushedToNavHistory {
19285        anchor: Anchor,
19286        is_deactivate: bool,
19287    },
19288}
19289
19290impl EventEmitter<EditorEvent> for Editor {}
19291
19292impl Focusable for Editor {
19293    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19294        self.focus_handle.clone()
19295    }
19296}
19297
19298impl Render for Editor {
19299    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19300        let settings = ThemeSettings::get_global(cx);
19301
19302        let mut text_style = match self.mode {
19303            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19304                color: cx.theme().colors().editor_foreground,
19305                font_family: settings.ui_font.family.clone(),
19306                font_features: settings.ui_font.features.clone(),
19307                font_fallbacks: settings.ui_font.fallbacks.clone(),
19308                font_size: rems(0.875).into(),
19309                font_weight: settings.ui_font.weight,
19310                line_height: relative(settings.buffer_line_height.value()),
19311                ..Default::default()
19312            },
19313            EditorMode::Full => TextStyle {
19314                color: cx.theme().colors().editor_foreground,
19315                font_family: settings.buffer_font.family.clone(),
19316                font_features: settings.buffer_font.features.clone(),
19317                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19318                font_size: settings.buffer_font_size(cx).into(),
19319                font_weight: settings.buffer_font.weight,
19320                line_height: relative(settings.buffer_line_height.value()),
19321                ..Default::default()
19322            },
19323        };
19324        if let Some(text_style_refinement) = &self.text_style_refinement {
19325            text_style.refine(text_style_refinement)
19326        }
19327
19328        let background = match self.mode {
19329            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19330            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19331            EditorMode::Full => cx.theme().colors().editor_background,
19332        };
19333
19334        EditorElement::new(
19335            &cx.entity(),
19336            EditorStyle {
19337                background,
19338                local_player: cx.theme().players().local(),
19339                text: text_style,
19340                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19341                syntax: cx.theme().syntax().clone(),
19342                status: cx.theme().status().clone(),
19343                inlay_hints_style: make_inlay_hints_style(cx),
19344                inline_completion_styles: make_suggestion_styles(cx),
19345                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19346            },
19347        )
19348    }
19349}
19350
19351impl EntityInputHandler for Editor {
19352    fn text_for_range(
19353        &mut self,
19354        range_utf16: Range<usize>,
19355        adjusted_range: &mut Option<Range<usize>>,
19356        _: &mut Window,
19357        cx: &mut Context<Self>,
19358    ) -> Option<String> {
19359        let snapshot = self.buffer.read(cx).read(cx);
19360        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19361        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19362        if (start.0..end.0) != range_utf16 {
19363            adjusted_range.replace(start.0..end.0);
19364        }
19365        Some(snapshot.text_for_range(start..end).collect())
19366    }
19367
19368    fn selected_text_range(
19369        &mut self,
19370        ignore_disabled_input: bool,
19371        _: &mut Window,
19372        cx: &mut Context<Self>,
19373    ) -> Option<UTF16Selection> {
19374        // Prevent the IME menu from appearing when holding down an alphabetic key
19375        // while input is disabled.
19376        if !ignore_disabled_input && !self.input_enabled {
19377            return None;
19378        }
19379
19380        let selection = self.selections.newest::<OffsetUtf16>(cx);
19381        let range = selection.range();
19382
19383        Some(UTF16Selection {
19384            range: range.start.0..range.end.0,
19385            reversed: selection.reversed,
19386        })
19387    }
19388
19389    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19390        let snapshot = self.buffer.read(cx).read(cx);
19391        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19392        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19393    }
19394
19395    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19396        self.clear_highlights::<InputComposition>(cx);
19397        self.ime_transaction.take();
19398    }
19399
19400    fn replace_text_in_range(
19401        &mut self,
19402        range_utf16: Option<Range<usize>>,
19403        text: &str,
19404        window: &mut Window,
19405        cx: &mut Context<Self>,
19406    ) {
19407        if !self.input_enabled {
19408            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19409            return;
19410        }
19411
19412        self.transact(window, cx, |this, window, cx| {
19413            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19414                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19415                Some(this.selection_replacement_ranges(range_utf16, cx))
19416            } else {
19417                this.marked_text_ranges(cx)
19418            };
19419
19420            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19421                let newest_selection_id = this.selections.newest_anchor().id;
19422                this.selections
19423                    .all::<OffsetUtf16>(cx)
19424                    .iter()
19425                    .zip(ranges_to_replace.iter())
19426                    .find_map(|(selection, range)| {
19427                        if selection.id == newest_selection_id {
19428                            Some(
19429                                (range.start.0 as isize - selection.head().0 as isize)
19430                                    ..(range.end.0 as isize - selection.head().0 as isize),
19431                            )
19432                        } else {
19433                            None
19434                        }
19435                    })
19436            });
19437
19438            cx.emit(EditorEvent::InputHandled {
19439                utf16_range_to_replace: range_to_replace,
19440                text: text.into(),
19441            });
19442
19443            if let Some(new_selected_ranges) = new_selected_ranges {
19444                this.change_selections(None, window, cx, |selections| {
19445                    selections.select_ranges(new_selected_ranges)
19446                });
19447                this.backspace(&Default::default(), window, cx);
19448            }
19449
19450            this.handle_input(text, window, cx);
19451        });
19452
19453        if let Some(transaction) = self.ime_transaction {
19454            self.buffer.update(cx, |buffer, cx| {
19455                buffer.group_until_transaction(transaction, cx);
19456            });
19457        }
19458
19459        self.unmark_text(window, cx);
19460    }
19461
19462    fn replace_and_mark_text_in_range(
19463        &mut self,
19464        range_utf16: Option<Range<usize>>,
19465        text: &str,
19466        new_selected_range_utf16: Option<Range<usize>>,
19467        window: &mut Window,
19468        cx: &mut Context<Self>,
19469    ) {
19470        if !self.input_enabled {
19471            return;
19472        }
19473
19474        let transaction = self.transact(window, cx, |this, window, cx| {
19475            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19476                let snapshot = this.buffer.read(cx).read(cx);
19477                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19478                    for marked_range in &mut marked_ranges {
19479                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19480                        marked_range.start.0 += relative_range_utf16.start;
19481                        marked_range.start =
19482                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19483                        marked_range.end =
19484                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19485                    }
19486                }
19487                Some(marked_ranges)
19488            } else if let Some(range_utf16) = range_utf16 {
19489                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19490                Some(this.selection_replacement_ranges(range_utf16, cx))
19491            } else {
19492                None
19493            };
19494
19495            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19496                let newest_selection_id = this.selections.newest_anchor().id;
19497                this.selections
19498                    .all::<OffsetUtf16>(cx)
19499                    .iter()
19500                    .zip(ranges_to_replace.iter())
19501                    .find_map(|(selection, range)| {
19502                        if selection.id == newest_selection_id {
19503                            Some(
19504                                (range.start.0 as isize - selection.head().0 as isize)
19505                                    ..(range.end.0 as isize - selection.head().0 as isize),
19506                            )
19507                        } else {
19508                            None
19509                        }
19510                    })
19511            });
19512
19513            cx.emit(EditorEvent::InputHandled {
19514                utf16_range_to_replace: range_to_replace,
19515                text: text.into(),
19516            });
19517
19518            if let Some(ranges) = ranges_to_replace {
19519                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19520            }
19521
19522            let marked_ranges = {
19523                let snapshot = this.buffer.read(cx).read(cx);
19524                this.selections
19525                    .disjoint_anchors()
19526                    .iter()
19527                    .map(|selection| {
19528                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19529                    })
19530                    .collect::<Vec<_>>()
19531            };
19532
19533            if text.is_empty() {
19534                this.unmark_text(window, cx);
19535            } else {
19536                this.highlight_text::<InputComposition>(
19537                    marked_ranges.clone(),
19538                    HighlightStyle {
19539                        underline: Some(UnderlineStyle {
19540                            thickness: px(1.),
19541                            color: None,
19542                            wavy: false,
19543                        }),
19544                        ..Default::default()
19545                    },
19546                    cx,
19547                );
19548            }
19549
19550            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19551            let use_autoclose = this.use_autoclose;
19552            let use_auto_surround = this.use_auto_surround;
19553            this.set_use_autoclose(false);
19554            this.set_use_auto_surround(false);
19555            this.handle_input(text, window, cx);
19556            this.set_use_autoclose(use_autoclose);
19557            this.set_use_auto_surround(use_auto_surround);
19558
19559            if let Some(new_selected_range) = new_selected_range_utf16 {
19560                let snapshot = this.buffer.read(cx).read(cx);
19561                let new_selected_ranges = marked_ranges
19562                    .into_iter()
19563                    .map(|marked_range| {
19564                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19565                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19566                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19567                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19568                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19569                    })
19570                    .collect::<Vec<_>>();
19571
19572                drop(snapshot);
19573                this.change_selections(None, window, cx, |selections| {
19574                    selections.select_ranges(new_selected_ranges)
19575                });
19576            }
19577        });
19578
19579        self.ime_transaction = self.ime_transaction.or(transaction);
19580        if let Some(transaction) = self.ime_transaction {
19581            self.buffer.update(cx, |buffer, cx| {
19582                buffer.group_until_transaction(transaction, cx);
19583            });
19584        }
19585
19586        if self.text_highlights::<InputComposition>(cx).is_none() {
19587            self.ime_transaction.take();
19588        }
19589    }
19590
19591    fn bounds_for_range(
19592        &mut self,
19593        range_utf16: Range<usize>,
19594        element_bounds: gpui::Bounds<Pixels>,
19595        window: &mut Window,
19596        cx: &mut Context<Self>,
19597    ) -> Option<gpui::Bounds<Pixels>> {
19598        let text_layout_details = self.text_layout_details(window);
19599        let gpui::Size {
19600            width: em_width,
19601            height: line_height,
19602        } = self.character_size(window);
19603
19604        let snapshot = self.snapshot(window, cx);
19605        let scroll_position = snapshot.scroll_position();
19606        let scroll_left = scroll_position.x * em_width;
19607
19608        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19609        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19610            + self.gutter_dimensions.width
19611            + self.gutter_dimensions.margin;
19612        let y = line_height * (start.row().as_f32() - scroll_position.y);
19613
19614        Some(Bounds {
19615            origin: element_bounds.origin + point(x, y),
19616            size: size(em_width, line_height),
19617        })
19618    }
19619
19620    fn character_index_for_point(
19621        &mut self,
19622        point: gpui::Point<Pixels>,
19623        _window: &mut Window,
19624        _cx: &mut Context<Self>,
19625    ) -> Option<usize> {
19626        let position_map = self.last_position_map.as_ref()?;
19627        if !position_map.text_hitbox.contains(&point) {
19628            return None;
19629        }
19630        let display_point = position_map.point_for_position(point).previous_valid;
19631        let anchor = position_map
19632            .snapshot
19633            .display_point_to_anchor(display_point, Bias::Left);
19634        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19635        Some(utf16_offset.0)
19636    }
19637}
19638
19639trait SelectionExt {
19640    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19641    fn spanned_rows(
19642        &self,
19643        include_end_if_at_line_start: bool,
19644        map: &DisplaySnapshot,
19645    ) -> Range<MultiBufferRow>;
19646}
19647
19648impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19649    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19650        let start = self
19651            .start
19652            .to_point(&map.buffer_snapshot)
19653            .to_display_point(map);
19654        let end = self
19655            .end
19656            .to_point(&map.buffer_snapshot)
19657            .to_display_point(map);
19658        if self.reversed {
19659            end..start
19660        } else {
19661            start..end
19662        }
19663    }
19664
19665    fn spanned_rows(
19666        &self,
19667        include_end_if_at_line_start: bool,
19668        map: &DisplaySnapshot,
19669    ) -> Range<MultiBufferRow> {
19670        let start = self.start.to_point(&map.buffer_snapshot);
19671        let mut end = self.end.to_point(&map.buffer_snapshot);
19672        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19673            end.row -= 1;
19674        }
19675
19676        let buffer_start = map.prev_line_boundary(start).0;
19677        let buffer_end = map.next_line_boundary(end).0;
19678        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19679    }
19680}
19681
19682impl<T: InvalidationRegion> InvalidationStack<T> {
19683    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19684    where
19685        S: Clone + ToOffset,
19686    {
19687        while let Some(region) = self.last() {
19688            let all_selections_inside_invalidation_ranges =
19689                if selections.len() == region.ranges().len() {
19690                    selections
19691                        .iter()
19692                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19693                        .all(|(selection, invalidation_range)| {
19694                            let head = selection.head().to_offset(buffer);
19695                            invalidation_range.start <= head && invalidation_range.end >= head
19696                        })
19697                } else {
19698                    false
19699                };
19700
19701            if all_selections_inside_invalidation_ranges {
19702                break;
19703            } else {
19704                self.pop();
19705            }
19706        }
19707    }
19708}
19709
19710impl<T> Default for InvalidationStack<T> {
19711    fn default() -> Self {
19712        Self(Default::default())
19713    }
19714}
19715
19716impl<T> Deref for InvalidationStack<T> {
19717    type Target = Vec<T>;
19718
19719    fn deref(&self) -> &Self::Target {
19720        &self.0
19721    }
19722}
19723
19724impl<T> DerefMut for InvalidationStack<T> {
19725    fn deref_mut(&mut self) -> &mut Self::Target {
19726        &mut self.0
19727    }
19728}
19729
19730impl InvalidationRegion for SnippetState {
19731    fn ranges(&self) -> &[Range<Anchor>] {
19732        &self.ranges[self.active_index]
19733    }
19734}
19735
19736pub fn diagnostic_block_renderer(
19737    diagnostic: Diagnostic,
19738    max_message_rows: Option<u8>,
19739    allow_closing: bool,
19740) -> RenderBlock {
19741    let (text_without_backticks, code_ranges) =
19742        highlight_diagnostic_message(&diagnostic, max_message_rows);
19743
19744    Arc::new(move |cx: &mut BlockContext| {
19745        let group_id: SharedString = cx.block_id.to_string().into();
19746
19747        let mut text_style = cx.window.text_style().clone();
19748        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19749        let theme_settings = ThemeSettings::get_global(cx);
19750        text_style.font_family = theme_settings.buffer_font.family.clone();
19751        text_style.font_style = theme_settings.buffer_font.style;
19752        text_style.font_features = theme_settings.buffer_font.features.clone();
19753        text_style.font_weight = theme_settings.buffer_font.weight;
19754
19755        let multi_line_diagnostic = diagnostic.message.contains('\n');
19756
19757        let buttons = |diagnostic: &Diagnostic| {
19758            if multi_line_diagnostic {
19759                v_flex()
19760            } else {
19761                h_flex()
19762            }
19763            .when(allow_closing, |div| {
19764                div.children(diagnostic.is_primary.then(|| {
19765                    IconButton::new("close-block", IconName::XCircle)
19766                        .icon_color(Color::Muted)
19767                        .size(ButtonSize::Compact)
19768                        .style(ButtonStyle::Transparent)
19769                        .visible_on_hover(group_id.clone())
19770                        .on_click(move |_click, window, cx| {
19771                            window.dispatch_action(Box::new(Cancel), cx)
19772                        })
19773                        .tooltip(|window, cx| {
19774                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19775                        })
19776                }))
19777            })
19778            .child(
19779                IconButton::new("copy-block", IconName::Copy)
19780                    .icon_color(Color::Muted)
19781                    .size(ButtonSize::Compact)
19782                    .style(ButtonStyle::Transparent)
19783                    .visible_on_hover(group_id.clone())
19784                    .on_click({
19785                        let message = diagnostic.message.clone();
19786                        move |_click, _, cx| {
19787                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19788                        }
19789                    })
19790                    .tooltip(Tooltip::text("Copy diagnostic message")),
19791            )
19792        };
19793
19794        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19795            AvailableSpace::min_size(),
19796            cx.window,
19797            cx.app,
19798        );
19799
19800        h_flex()
19801            .id(cx.block_id)
19802            .group(group_id.clone())
19803            .relative()
19804            .size_full()
19805            .block_mouse_down()
19806            .pl(cx.gutter_dimensions.width)
19807            .w(cx.max_width - cx.gutter_dimensions.full_width())
19808            .child(
19809                div()
19810                    .flex()
19811                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19812                    .flex_shrink(),
19813            )
19814            .child(buttons(&diagnostic))
19815            .child(div().flex().flex_shrink_0().child(
19816                StyledText::new(text_without_backticks.clone()).with_default_highlights(
19817                    &text_style,
19818                    code_ranges.iter().map(|range| {
19819                        (
19820                            range.clone(),
19821                            HighlightStyle {
19822                                font_weight: Some(FontWeight::BOLD),
19823                                ..Default::default()
19824                            },
19825                        )
19826                    }),
19827                ),
19828            ))
19829            .into_any_element()
19830    })
19831}
19832
19833fn inline_completion_edit_text(
19834    current_snapshot: &BufferSnapshot,
19835    edits: &[(Range<Anchor>, String)],
19836    edit_preview: &EditPreview,
19837    include_deletions: bool,
19838    cx: &App,
19839) -> HighlightedText {
19840    let edits = edits
19841        .iter()
19842        .map(|(anchor, text)| {
19843            (
19844                anchor.start.text_anchor..anchor.end.text_anchor,
19845                text.clone(),
19846            )
19847        })
19848        .collect::<Vec<_>>();
19849
19850    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19851}
19852
19853pub fn highlight_diagnostic_message(
19854    diagnostic: &Diagnostic,
19855    mut max_message_rows: Option<u8>,
19856) -> (SharedString, Vec<Range<usize>>) {
19857    let mut text_without_backticks = String::new();
19858    let mut code_ranges = Vec::new();
19859
19860    if let Some(source) = &diagnostic.source {
19861        text_without_backticks.push_str(source);
19862        code_ranges.push(0..source.len());
19863        text_without_backticks.push_str(": ");
19864    }
19865
19866    let mut prev_offset = 0;
19867    let mut in_code_block = false;
19868    let has_row_limit = max_message_rows.is_some();
19869    let mut newline_indices = diagnostic
19870        .message
19871        .match_indices('\n')
19872        .filter(|_| has_row_limit)
19873        .map(|(ix, _)| ix)
19874        .fuse()
19875        .peekable();
19876
19877    for (quote_ix, _) in diagnostic
19878        .message
19879        .match_indices('`')
19880        .chain([(diagnostic.message.len(), "")])
19881    {
19882        let mut first_newline_ix = None;
19883        let mut last_newline_ix = None;
19884        while let Some(newline_ix) = newline_indices.peek() {
19885            if *newline_ix < quote_ix {
19886                if first_newline_ix.is_none() {
19887                    first_newline_ix = Some(*newline_ix);
19888                }
19889                last_newline_ix = Some(*newline_ix);
19890
19891                if let Some(rows_left) = &mut max_message_rows {
19892                    if *rows_left == 0 {
19893                        break;
19894                    } else {
19895                        *rows_left -= 1;
19896                    }
19897                }
19898                let _ = newline_indices.next();
19899            } else {
19900                break;
19901            }
19902        }
19903        let prev_len = text_without_backticks.len();
19904        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19905        text_without_backticks.push_str(new_text);
19906        if in_code_block {
19907            code_ranges.push(prev_len..text_without_backticks.len());
19908        }
19909        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19910        in_code_block = !in_code_block;
19911        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19912            text_without_backticks.push_str("...");
19913            break;
19914        }
19915    }
19916
19917    (text_without_backticks.into(), code_ranges)
19918}
19919
19920fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19921    match severity {
19922        DiagnosticSeverity::ERROR => colors.error,
19923        DiagnosticSeverity::WARNING => colors.warning,
19924        DiagnosticSeverity::INFORMATION => colors.info,
19925        DiagnosticSeverity::HINT => colors.info,
19926        _ => colors.ignored,
19927    }
19928}
19929
19930pub fn styled_runs_for_code_label<'a>(
19931    label: &'a CodeLabel,
19932    syntax_theme: &'a theme::SyntaxTheme,
19933) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19934    let fade_out = HighlightStyle {
19935        fade_out: Some(0.35),
19936        ..Default::default()
19937    };
19938
19939    let mut prev_end = label.filter_range.end;
19940    label
19941        .runs
19942        .iter()
19943        .enumerate()
19944        .flat_map(move |(ix, (range, highlight_id))| {
19945            let style = if let Some(style) = highlight_id.style(syntax_theme) {
19946                style
19947            } else {
19948                return Default::default();
19949            };
19950            let mut muted_style = style;
19951            muted_style.highlight(fade_out);
19952
19953            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19954            if range.start >= label.filter_range.end {
19955                if range.start > prev_end {
19956                    runs.push((prev_end..range.start, fade_out));
19957                }
19958                runs.push((range.clone(), muted_style));
19959            } else if range.end <= label.filter_range.end {
19960                runs.push((range.clone(), style));
19961            } else {
19962                runs.push((range.start..label.filter_range.end, style));
19963                runs.push((label.filter_range.end..range.end, muted_style));
19964            }
19965            prev_end = cmp::max(prev_end, range.end);
19966
19967            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19968                runs.push((prev_end..label.text.len(), fade_out));
19969            }
19970
19971            runs
19972        })
19973}
19974
19975pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19976    let mut prev_index = 0;
19977    let mut prev_codepoint: Option<char> = None;
19978    text.char_indices()
19979        .chain([(text.len(), '\0')])
19980        .filter_map(move |(index, codepoint)| {
19981            let prev_codepoint = prev_codepoint.replace(codepoint)?;
19982            let is_boundary = index == text.len()
19983                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19984                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19985            if is_boundary {
19986                let chunk = &text[prev_index..index];
19987                prev_index = index;
19988                Some(chunk)
19989            } else {
19990                None
19991            }
19992        })
19993}
19994
19995pub trait RangeToAnchorExt: Sized {
19996    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19997
19998    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19999        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20000        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20001    }
20002}
20003
20004impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20005    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20006        let start_offset = self.start.to_offset(snapshot);
20007        let end_offset = self.end.to_offset(snapshot);
20008        if start_offset == end_offset {
20009            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20010        } else {
20011            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20012        }
20013    }
20014}
20015
20016pub trait RowExt {
20017    fn as_f32(&self) -> f32;
20018
20019    fn next_row(&self) -> Self;
20020
20021    fn previous_row(&self) -> Self;
20022
20023    fn minus(&self, other: Self) -> u32;
20024}
20025
20026impl RowExt for DisplayRow {
20027    fn as_f32(&self) -> f32 {
20028        self.0 as f32
20029    }
20030
20031    fn next_row(&self) -> Self {
20032        Self(self.0 + 1)
20033    }
20034
20035    fn previous_row(&self) -> Self {
20036        Self(self.0.saturating_sub(1))
20037    }
20038
20039    fn minus(&self, other: Self) -> u32 {
20040        self.0 - other.0
20041    }
20042}
20043
20044impl RowExt for MultiBufferRow {
20045    fn as_f32(&self) -> f32 {
20046        self.0 as f32
20047    }
20048
20049    fn next_row(&self) -> Self {
20050        Self(self.0 + 1)
20051    }
20052
20053    fn previous_row(&self) -> Self {
20054        Self(self.0.saturating_sub(1))
20055    }
20056
20057    fn minus(&self, other: Self) -> u32 {
20058        self.0 - other.0
20059    }
20060}
20061
20062trait RowRangeExt {
20063    type Row;
20064
20065    fn len(&self) -> usize;
20066
20067    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20068}
20069
20070impl RowRangeExt for Range<MultiBufferRow> {
20071    type Row = MultiBufferRow;
20072
20073    fn len(&self) -> usize {
20074        (self.end.0 - self.start.0) as usize
20075    }
20076
20077    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20078        (self.start.0..self.end.0).map(MultiBufferRow)
20079    }
20080}
20081
20082impl RowRangeExt for Range<DisplayRow> {
20083    type Row = DisplayRow;
20084
20085    fn len(&self) -> usize {
20086        (self.end.0 - self.start.0) as usize
20087    }
20088
20089    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20090        (self.start.0..self.end.0).map(DisplayRow)
20091    }
20092}
20093
20094/// If select range has more than one line, we
20095/// just point the cursor to range.start.
20096fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20097    if range.start.row == range.end.row {
20098        range
20099    } else {
20100        range.start..range.start
20101    }
20102}
20103pub struct KillRing(ClipboardItem);
20104impl Global for KillRing {}
20105
20106const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20107
20108enum BreakpointPromptEditAction {
20109    Log,
20110    Condition,
20111    HitCondition,
20112}
20113
20114struct BreakpointPromptEditor {
20115    pub(crate) prompt: Entity<Editor>,
20116    editor: WeakEntity<Editor>,
20117    breakpoint_anchor: Anchor,
20118    breakpoint: Breakpoint,
20119    edit_action: BreakpointPromptEditAction,
20120    block_ids: HashSet<CustomBlockId>,
20121    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20122    _subscriptions: Vec<Subscription>,
20123}
20124
20125impl BreakpointPromptEditor {
20126    const MAX_LINES: u8 = 4;
20127
20128    fn new(
20129        editor: WeakEntity<Editor>,
20130        breakpoint_anchor: Anchor,
20131        breakpoint: Breakpoint,
20132        edit_action: BreakpointPromptEditAction,
20133        window: &mut Window,
20134        cx: &mut Context<Self>,
20135    ) -> Self {
20136        let base_text = match edit_action {
20137            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20138            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20139            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20140        }
20141        .map(|msg| msg.to_string())
20142        .unwrap_or_default();
20143
20144        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20145        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20146
20147        let prompt = cx.new(|cx| {
20148            let mut prompt = Editor::new(
20149                EditorMode::AutoHeight {
20150                    max_lines: Self::MAX_LINES as usize,
20151                },
20152                buffer,
20153                None,
20154                window,
20155                cx,
20156            );
20157            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20158            prompt.set_show_cursor_when_unfocused(false, cx);
20159            prompt.set_placeholder_text(
20160                match edit_action {
20161                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20162                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20163                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20164                },
20165                cx,
20166            );
20167
20168            prompt
20169        });
20170
20171        Self {
20172            prompt,
20173            editor,
20174            breakpoint_anchor,
20175            breakpoint,
20176            edit_action,
20177            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20178            block_ids: Default::default(),
20179            _subscriptions: vec![],
20180        }
20181    }
20182
20183    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20184        self.block_ids.extend(block_ids)
20185    }
20186
20187    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20188        if let Some(editor) = self.editor.upgrade() {
20189            let message = self
20190                .prompt
20191                .read(cx)
20192                .buffer
20193                .read(cx)
20194                .as_singleton()
20195                .expect("A multi buffer in breakpoint prompt isn't possible")
20196                .read(cx)
20197                .as_rope()
20198                .to_string();
20199
20200            editor.update(cx, |editor, cx| {
20201                editor.edit_breakpoint_at_anchor(
20202                    self.breakpoint_anchor,
20203                    self.breakpoint.clone(),
20204                    match self.edit_action {
20205                        BreakpointPromptEditAction::Log => {
20206                            BreakpointEditAction::EditLogMessage(message.into())
20207                        }
20208                        BreakpointPromptEditAction::Condition => {
20209                            BreakpointEditAction::EditCondition(message.into())
20210                        }
20211                        BreakpointPromptEditAction::HitCondition => {
20212                            BreakpointEditAction::EditHitCondition(message.into())
20213                        }
20214                    },
20215                    cx,
20216                );
20217
20218                editor.remove_blocks(self.block_ids.clone(), None, cx);
20219                cx.focus_self(window);
20220            });
20221        }
20222    }
20223
20224    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20225        self.editor
20226            .update(cx, |editor, cx| {
20227                editor.remove_blocks(self.block_ids.clone(), None, cx);
20228                window.focus(&editor.focus_handle);
20229            })
20230            .log_err();
20231    }
20232
20233    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20234        let settings = ThemeSettings::get_global(cx);
20235        let text_style = TextStyle {
20236            color: if self.prompt.read(cx).read_only(cx) {
20237                cx.theme().colors().text_disabled
20238            } else {
20239                cx.theme().colors().text
20240            },
20241            font_family: settings.buffer_font.family.clone(),
20242            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20243            font_size: settings.buffer_font_size(cx).into(),
20244            font_weight: settings.buffer_font.weight,
20245            line_height: relative(settings.buffer_line_height.value()),
20246            ..Default::default()
20247        };
20248        EditorElement::new(
20249            &self.prompt,
20250            EditorStyle {
20251                background: cx.theme().colors().editor_background,
20252                local_player: cx.theme().players().local(),
20253                text: text_style,
20254                ..Default::default()
20255            },
20256        )
20257    }
20258}
20259
20260impl Render for BreakpointPromptEditor {
20261    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20262        let gutter_dimensions = *self.gutter_dimensions.lock();
20263        h_flex()
20264            .key_context("Editor")
20265            .bg(cx.theme().colors().editor_background)
20266            .border_y_1()
20267            .border_color(cx.theme().status().info_border)
20268            .size_full()
20269            .py(window.line_height() / 2.5)
20270            .on_action(cx.listener(Self::confirm))
20271            .on_action(cx.listener(Self::cancel))
20272            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20273            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20274    }
20275}
20276
20277impl Focusable for BreakpointPromptEditor {
20278    fn focus_handle(&self, cx: &App) -> FocusHandle {
20279        self.prompt.focus_handle(cx)
20280    }
20281}
20282
20283fn all_edits_insertions_or_deletions(
20284    edits: &Vec<(Range<Anchor>, String)>,
20285    snapshot: &MultiBufferSnapshot,
20286) -> bool {
20287    let mut all_insertions = true;
20288    let mut all_deletions = true;
20289
20290    for (range, new_text) in edits.iter() {
20291        let range_is_empty = range.to_offset(&snapshot).is_empty();
20292        let text_is_empty = new_text.is_empty();
20293
20294        if range_is_empty != text_is_empty {
20295            if range_is_empty {
20296                all_deletions = false;
20297            } else {
20298                all_insertions = false;
20299            }
20300        } else {
20301            return false;
20302        }
20303
20304        if !all_insertions && !all_deletions {
20305            return false;
20306        }
20307    }
20308    all_insertions || all_deletions
20309}
20310
20311struct MissingEditPredictionKeybindingTooltip;
20312
20313impl Render for MissingEditPredictionKeybindingTooltip {
20314    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20315        ui::tooltip_container(window, cx, |container, _, cx| {
20316            container
20317                .flex_shrink_0()
20318                .max_w_80()
20319                .min_h(rems_from_px(124.))
20320                .justify_between()
20321                .child(
20322                    v_flex()
20323                        .flex_1()
20324                        .text_ui_sm(cx)
20325                        .child(Label::new("Conflict with Accept Keybinding"))
20326                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20327                )
20328                .child(
20329                    h_flex()
20330                        .pb_1()
20331                        .gap_1()
20332                        .items_end()
20333                        .w_full()
20334                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20335                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20336                        }))
20337                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20338                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20339                        })),
20340                )
20341        })
20342    }
20343}
20344
20345#[derive(Debug, Clone, Copy, PartialEq)]
20346pub struct LineHighlight {
20347    pub background: Background,
20348    pub border: Option<gpui::Hsla>,
20349}
20350
20351impl From<Hsla> for LineHighlight {
20352    fn from(hsla: Hsla) -> Self {
20353        Self {
20354            background: hsla.into(),
20355            border: None,
20356        }
20357    }
20358}
20359
20360impl From<Background> for LineHighlight {
20361    fn from(background: Background) -> Self {
20362        Self {
20363            background,
20364            border: None,
20365        }
20366    }
20367}
20368
20369fn render_diff_hunk_controls(
20370    row: u32,
20371    status: &DiffHunkStatus,
20372    hunk_range: Range<Anchor>,
20373    is_created_file: bool,
20374    line_height: Pixels,
20375    editor: &Entity<Editor>,
20376    _window: &mut Window,
20377    cx: &mut App,
20378) -> AnyElement {
20379    h_flex()
20380        .h(line_height)
20381        .mr_1()
20382        .gap_1()
20383        .px_0p5()
20384        .pb_1()
20385        .border_x_1()
20386        .border_b_1()
20387        .border_color(cx.theme().colors().border_variant)
20388        .rounded_b_lg()
20389        .bg(cx.theme().colors().editor_background)
20390        .gap_1()
20391        .occlude()
20392        .shadow_md()
20393        .child(if status.has_secondary_hunk() {
20394            Button::new(("stage", row as u64), "Stage")
20395                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20396                .tooltip({
20397                    let focus_handle = editor.focus_handle(cx);
20398                    move |window, cx| {
20399                        Tooltip::for_action_in(
20400                            "Stage Hunk",
20401                            &::git::ToggleStaged,
20402                            &focus_handle,
20403                            window,
20404                            cx,
20405                        )
20406                    }
20407                })
20408                .on_click({
20409                    let editor = editor.clone();
20410                    move |_event, _window, cx| {
20411                        editor.update(cx, |editor, cx| {
20412                            editor.stage_or_unstage_diff_hunks(
20413                                true,
20414                                vec![hunk_range.start..hunk_range.start],
20415                                cx,
20416                            );
20417                        });
20418                    }
20419                })
20420        } else {
20421            Button::new(("unstage", row as u64), "Unstage")
20422                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20423                .tooltip({
20424                    let focus_handle = editor.focus_handle(cx);
20425                    move |window, cx| {
20426                        Tooltip::for_action_in(
20427                            "Unstage Hunk",
20428                            &::git::ToggleStaged,
20429                            &focus_handle,
20430                            window,
20431                            cx,
20432                        )
20433                    }
20434                })
20435                .on_click({
20436                    let editor = editor.clone();
20437                    move |_event, _window, cx| {
20438                        editor.update(cx, |editor, cx| {
20439                            editor.stage_or_unstage_diff_hunks(
20440                                false,
20441                                vec![hunk_range.start..hunk_range.start],
20442                                cx,
20443                            );
20444                        });
20445                    }
20446                })
20447        })
20448        .child(
20449            Button::new(("restore", row as u64), "Restore")
20450                .tooltip({
20451                    let focus_handle = editor.focus_handle(cx);
20452                    move |window, cx| {
20453                        Tooltip::for_action_in(
20454                            "Restore Hunk",
20455                            &::git::Restore,
20456                            &focus_handle,
20457                            window,
20458                            cx,
20459                        )
20460                    }
20461                })
20462                .on_click({
20463                    let editor = editor.clone();
20464                    move |_event, window, cx| {
20465                        editor.update(cx, |editor, cx| {
20466                            let snapshot = editor.snapshot(window, cx);
20467                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20468                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20469                        });
20470                    }
20471                })
20472                .disabled(is_created_file),
20473        )
20474        .when(
20475            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20476            |el| {
20477                el.child(
20478                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20479                        .shape(IconButtonShape::Square)
20480                        .icon_size(IconSize::Small)
20481                        // .disabled(!has_multiple_hunks)
20482                        .tooltip({
20483                            let focus_handle = editor.focus_handle(cx);
20484                            move |window, cx| {
20485                                Tooltip::for_action_in(
20486                                    "Next Hunk",
20487                                    &GoToHunk,
20488                                    &focus_handle,
20489                                    window,
20490                                    cx,
20491                                )
20492                            }
20493                        })
20494                        .on_click({
20495                            let editor = editor.clone();
20496                            move |_event, window, cx| {
20497                                editor.update(cx, |editor, cx| {
20498                                    let snapshot = editor.snapshot(window, cx);
20499                                    let position =
20500                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20501                                    editor.go_to_hunk_before_or_after_position(
20502                                        &snapshot,
20503                                        position,
20504                                        Direction::Next,
20505                                        window,
20506                                        cx,
20507                                    );
20508                                    editor.expand_selected_diff_hunks(cx);
20509                                });
20510                            }
20511                        }),
20512                )
20513                .child(
20514                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20515                        .shape(IconButtonShape::Square)
20516                        .icon_size(IconSize::Small)
20517                        // .disabled(!has_multiple_hunks)
20518                        .tooltip({
20519                            let focus_handle = editor.focus_handle(cx);
20520                            move |window, cx| {
20521                                Tooltip::for_action_in(
20522                                    "Previous Hunk",
20523                                    &GoToPreviousHunk,
20524                                    &focus_handle,
20525                                    window,
20526                                    cx,
20527                                )
20528                            }
20529                        })
20530                        .on_click({
20531                            let editor = editor.clone();
20532                            move |_event, window, cx| {
20533                                editor.update(cx, |editor, cx| {
20534                                    let snapshot = editor.snapshot(window, cx);
20535                                    let point =
20536                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20537                                    editor.go_to_hunk_before_or_after_position(
20538                                        &snapshot,
20539                                        point,
20540                                        Direction::Prev,
20541                                        window,
20542                                        cx,
20543                                    );
20544                                    editor.expand_selected_diff_hunks(cx);
20545                                });
20546                            }
20547                        }),
20548                )
20549            },
20550        )
20551        .into_any_element()
20552}