editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26pub mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{Context as _, Result, anyhow};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   62use editor_settings::GoToDefinitionFallback;
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   65    ShowScrollbar,
   66};
   67pub use editor_settings_controls::*;
   68use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   69pub use element::{
   70    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   71};
   72use feature_flags::{Debugger, FeatureFlagAppExt};
   73use futures::{
   74    FutureExt,
   75    future::{self, Shared, join},
   76};
   77use fuzzy::StringMatchCandidate;
   78
   79use ::git::Restore;
   80use code_context_menus::{
   81    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   82    CompletionsMenu, ContextMenuOrigin,
   83};
   84use git::blame::{GitBlame, GlobalBlameRenderer};
   85use gpui::{
   86    Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
   87    AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
   88    ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
   89    FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
   90    KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
   91    SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
   92    UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   93    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
   94};
   95use highlight_matching_bracket::refresh_matching_bracket_highlights;
   96use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
   97pub use hover_popover::hover_markdown_style;
   98use hover_popover::{HoverState, hide_hover};
   99use indent_guides::ActiveIndentGuidesState;
  100use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  101pub use inline_completion::Direction;
  102use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  103pub use items::MAX_TAB_TITLE_LEN;
  104use itertools::Itertools;
  105use language::{
  106    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  107    CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  108    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  109    TransactionId, TreeSitterOptions, WordsQuery,
  110    language_settings::{
  111        self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
  112        all_language_settings, language_settings,
  113    },
  114    point_from_lsp, text_diff_with_options,
  115};
  116use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  117use linked_editing_ranges::refresh_linked_ranges;
  118use mouse_context_menu::MouseContextMenu;
  119use persistence::DB;
  120use project::{
  121    ProjectPath,
  122    debugger::breakpoint_store::{
  123        BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  124    },
  125};
  126
  127pub use git::blame::BlameRenderer;
  128pub use proposed_changes_editor::{
  129    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  130};
  131use smallvec::smallvec;
  132use std::{cell::OnceCell, iter::Peekable};
  133use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
  134
  135pub use lsp::CompletionContext;
  136use lsp::{
  137    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  138    InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
  139};
  140
  141use language::BufferSnapshot;
  142pub use lsp_ext::lsp_tasks;
  143use movement::TextLayoutDetails;
  144pub use multi_buffer::{
  145    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
  146    RowInfo, ToOffset, ToPoint,
  147};
  148use multi_buffer::{
  149    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  150    MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
  151};
  152use parking_lot::Mutex;
  153use project::{
  154    CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
  155    Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
  156    TaskSourceKind,
  157    debugger::breakpoint_store::Breakpoint,
  158    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  159    project_settings::{GitGutterSetting, ProjectSettings},
  160};
  161use rand::prelude::*;
  162use rpc::{ErrorExt, proto::*};
  163use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  164use selections_collection::{
  165    MutableSelectionsCollection, SelectionsCollection, resolve_selections,
  166};
  167use serde::{Deserialize, Serialize};
  168use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
  169use smallvec::SmallVec;
  170use snippet::Snippet;
  171use std::sync::Arc;
  172use std::{
  173    any::TypeId,
  174    borrow::Cow,
  175    cell::RefCell,
  176    cmp::{self, Ordering, Reverse},
  177    mem,
  178    num::NonZeroU32,
  179    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  180    path::{Path, PathBuf},
  181    rc::Rc,
  182    time::{Duration, Instant},
  183};
  184pub use sum_tree::Bias;
  185use sum_tree::TreeMap;
  186use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
  187use theme::{
  188    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  189    observe_buffer_font_size_adjustment,
  190};
  191use ui::{
  192    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  193    IconSize, Key, Tooltip, h_flex, prelude::*,
  194};
  195use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  196use workspace::{
  197    Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  198    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  199    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  200    item::{ItemHandle, PreviewTabsSettings},
  201    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  202    searchable::SearchEvent,
  203};
  204
  205use crate::hover_links::{find_url, find_url_from_range};
  206use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  207
  208pub const FILE_HEADER_HEIGHT: u32 = 2;
  209pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  210pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  211const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  212const MAX_LINE_LEN: usize = 1024;
  213const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  214const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  215pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  216#[doc(hidden)]
  217pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  218const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  219
  220pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  221pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  222pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  223
  224pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  225pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  226pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  227
  228pub type RenderDiffHunkControlsFn = Arc<
  229    dyn Fn(
  230        u32,
  231        &DiffHunkStatus,
  232        Range<Anchor>,
  233        bool,
  234        Pixels,
  235        &Entity<Editor>,
  236        &mut Window,
  237        &mut App,
  238    ) -> AnyElement,
  239>;
  240
  241const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  242    alt: true,
  243    shift: true,
  244    control: false,
  245    platform: false,
  246    function: false,
  247};
  248
  249#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  250pub enum InlayId {
  251    InlineCompletion(usize),
  252    Hint(usize),
  253}
  254
  255impl InlayId {
  256    fn id(&self) -> usize {
  257        match self {
  258            Self::InlineCompletion(id) => *id,
  259            Self::Hint(id) => *id,
  260        }
  261    }
  262}
  263
  264pub enum DebugCurrentRowHighlight {}
  265enum DocumentHighlightRead {}
  266enum DocumentHighlightWrite {}
  267enum InputComposition {}
  268enum SelectedTextHighlight {}
  269
  270#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  271pub enum Navigated {
  272    Yes,
  273    No,
  274}
  275
  276impl Navigated {
  277    pub fn from_bool(yes: bool) -> Navigated {
  278        if yes { Navigated::Yes } else { Navigated::No }
  279    }
  280}
  281
  282#[derive(Debug, Clone, PartialEq, Eq)]
  283enum DisplayDiffHunk {
  284    Folded {
  285        display_row: DisplayRow,
  286    },
  287    Unfolded {
  288        is_created_file: bool,
  289        diff_base_byte_range: Range<usize>,
  290        display_row_range: Range<DisplayRow>,
  291        multi_buffer_range: Range<Anchor>,
  292        status: DiffHunkStatus,
  293    },
  294}
  295
  296pub enum HideMouseCursorOrigin {
  297    TypingAction,
  298    MovementAction,
  299}
  300
  301pub fn init_settings(cx: &mut App) {
  302    EditorSettings::register(cx);
  303}
  304
  305pub fn init(cx: &mut App) {
  306    init_settings(cx);
  307
  308    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  309
  310    workspace::register_project_item::<Editor>(cx);
  311    workspace::FollowableViewRegistry::register::<Editor>(cx);
  312    workspace::register_serializable_item::<Editor>(cx);
  313
  314    cx.observe_new(
  315        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  316            workspace.register_action(Editor::new_file);
  317            workspace.register_action(Editor::new_file_vertical);
  318            workspace.register_action(Editor::new_file_horizontal);
  319            workspace.register_action(Editor::cancel_language_server_work);
  320        },
  321    )
  322    .detach();
  323
  324    cx.on_action(move |_: &workspace::NewFile, cx| {
  325        let app_state = workspace::AppState::global(cx);
  326        if let Some(app_state) = app_state.upgrade() {
  327            workspace::open_new(
  328                Default::default(),
  329                app_state,
  330                cx,
  331                |workspace, window, cx| {
  332                    Editor::new_file(workspace, &Default::default(), window, cx)
  333                },
  334            )
  335            .detach();
  336        }
  337    });
  338    cx.on_action(move |_: &workspace::NewWindow, cx| {
  339        let app_state = workspace::AppState::global(cx);
  340        if let Some(app_state) = app_state.upgrade() {
  341            workspace::open_new(
  342                Default::default(),
  343                app_state,
  344                cx,
  345                |workspace, window, cx| {
  346                    cx.activate(true);
  347                    Editor::new_file(workspace, &Default::default(), window, cx)
  348                },
  349            )
  350            .detach();
  351        }
  352    });
  353}
  354
  355pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  356    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  357}
  358
  359pub trait DiagnosticRenderer {
  360    fn render_group(
  361        &self,
  362        diagnostic_group: Vec<DiagnosticEntry<Point>>,
  363        buffer_id: BufferId,
  364        snapshot: EditorSnapshot,
  365        editor: WeakEntity<Editor>,
  366        cx: &mut App,
  367    ) -> Vec<BlockProperties<Anchor>>;
  368}
  369
  370pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
  371
  372impl gpui::Global for GlobalDiagnosticRenderer {}
  373pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
  374    cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
  375}
  376
  377pub struct SearchWithinRange;
  378
  379trait InvalidationRegion {
  380    fn ranges(&self) -> &[Range<Anchor>];
  381}
  382
  383#[derive(Clone, Debug, PartialEq)]
  384pub enum SelectPhase {
  385    Begin {
  386        position: DisplayPoint,
  387        add: bool,
  388        click_count: usize,
  389    },
  390    BeginColumnar {
  391        position: DisplayPoint,
  392        reset: bool,
  393        goal_column: u32,
  394    },
  395    Extend {
  396        position: DisplayPoint,
  397        click_count: usize,
  398    },
  399    Update {
  400        position: DisplayPoint,
  401        goal_column: u32,
  402        scroll_delta: gpui::Point<f32>,
  403    },
  404    End,
  405}
  406
  407#[derive(Clone, Debug)]
  408pub enum SelectMode {
  409    Character,
  410    Word(Range<Anchor>),
  411    Line(Range<Anchor>),
  412    All,
  413}
  414
  415#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  416pub enum EditorMode {
  417    SingleLine {
  418        auto_width: bool,
  419    },
  420    AutoHeight {
  421        max_lines: usize,
  422    },
  423    Full {
  424        /// When set to `true`, the editor will scale its UI elements with the buffer font size.
  425        scale_ui_elements_with_buffer_font_size: bool,
  426        /// When set to `true`, the editor will render a background for the active line.
  427        show_active_line_background: bool,
  428    },
  429}
  430
  431impl EditorMode {
  432    pub fn full() -> Self {
  433        Self::Full {
  434            scale_ui_elements_with_buffer_font_size: true,
  435            show_active_line_background: true,
  436        }
  437    }
  438
  439    pub fn is_full(&self) -> bool {
  440        matches!(self, Self::Full { .. })
  441    }
  442}
  443
  444#[derive(Copy, Clone, Debug)]
  445pub enum SoftWrap {
  446    /// Prefer not to wrap at all.
  447    ///
  448    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  449    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  450    GitDiff,
  451    /// Prefer a single line generally, unless an overly long line is encountered.
  452    None,
  453    /// Soft wrap lines that exceed the editor width.
  454    EditorWidth,
  455    /// Soft wrap lines at the preferred line length.
  456    Column(u32),
  457    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  458    Bounded(u32),
  459}
  460
  461#[derive(Clone)]
  462pub struct EditorStyle {
  463    pub background: Hsla,
  464    pub local_player: PlayerColor,
  465    pub text: TextStyle,
  466    pub scrollbar_width: Pixels,
  467    pub syntax: Arc<SyntaxTheme>,
  468    pub status: StatusColors,
  469    pub inlay_hints_style: HighlightStyle,
  470    pub inline_completion_styles: InlineCompletionStyles,
  471    pub unnecessary_code_fade: f32,
  472}
  473
  474impl Default for EditorStyle {
  475    fn default() -> Self {
  476        Self {
  477            background: Hsla::default(),
  478            local_player: PlayerColor::default(),
  479            text: TextStyle::default(),
  480            scrollbar_width: Pixels::default(),
  481            syntax: Default::default(),
  482            // HACK: Status colors don't have a real default.
  483            // We should look into removing the status colors from the editor
  484            // style and retrieve them directly from the theme.
  485            status: StatusColors::dark(),
  486            inlay_hints_style: HighlightStyle::default(),
  487            inline_completion_styles: InlineCompletionStyles {
  488                insertion: HighlightStyle::default(),
  489                whitespace: HighlightStyle::default(),
  490            },
  491            unnecessary_code_fade: Default::default(),
  492        }
  493    }
  494}
  495
  496pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  497    let show_background = language_settings::language_settings(None, None, cx)
  498        .inlay_hints
  499        .show_background;
  500
  501    HighlightStyle {
  502        color: Some(cx.theme().status().hint),
  503        background_color: show_background.then(|| cx.theme().status().hint_background),
  504        ..HighlightStyle::default()
  505    }
  506}
  507
  508pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  509    InlineCompletionStyles {
  510        insertion: HighlightStyle {
  511            color: Some(cx.theme().status().predictive),
  512            ..HighlightStyle::default()
  513        },
  514        whitespace: HighlightStyle {
  515            background_color: Some(cx.theme().status().created_background),
  516            ..HighlightStyle::default()
  517        },
  518    }
  519}
  520
  521type CompletionId = usize;
  522
  523pub(crate) enum EditDisplayMode {
  524    TabAccept,
  525    DiffPopover,
  526    Inline,
  527}
  528
  529enum InlineCompletion {
  530    Edit {
  531        edits: Vec<(Range<Anchor>, String)>,
  532        edit_preview: Option<EditPreview>,
  533        display_mode: EditDisplayMode,
  534        snapshot: BufferSnapshot,
  535    },
  536    Move {
  537        target: Anchor,
  538        snapshot: BufferSnapshot,
  539    },
  540}
  541
  542struct InlineCompletionState {
  543    inlay_ids: Vec<InlayId>,
  544    completion: InlineCompletion,
  545    completion_id: Option<SharedString>,
  546    invalidation_range: Range<Anchor>,
  547}
  548
  549enum EditPredictionSettings {
  550    Disabled,
  551    Enabled {
  552        show_in_menu: bool,
  553        preview_requires_modifier: bool,
  554    },
  555}
  556
  557enum InlineCompletionHighlight {}
  558
  559#[derive(Debug, Clone)]
  560struct InlineDiagnostic {
  561    message: SharedString,
  562    group_id: usize,
  563    is_primary: bool,
  564    start: Point,
  565    severity: DiagnosticSeverity,
  566}
  567
  568pub enum MenuInlineCompletionsPolicy {
  569    Never,
  570    ByProvider,
  571}
  572
  573pub enum EditPredictionPreview {
  574    /// Modifier is not pressed
  575    Inactive { released_too_fast: bool },
  576    /// Modifier pressed
  577    Active {
  578        since: Instant,
  579        previous_scroll_position: Option<ScrollAnchor>,
  580    },
  581}
  582
  583impl EditPredictionPreview {
  584    pub fn released_too_fast(&self) -> bool {
  585        match self {
  586            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  587            EditPredictionPreview::Active { .. } => false,
  588        }
  589    }
  590
  591    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  592        if let EditPredictionPreview::Active {
  593            previous_scroll_position,
  594            ..
  595        } = self
  596        {
  597            *previous_scroll_position = scroll_position;
  598        }
  599    }
  600}
  601
  602pub struct ContextMenuOptions {
  603    pub min_entries_visible: usize,
  604    pub max_entries_visible: usize,
  605    pub placement: Option<ContextMenuPlacement>,
  606}
  607
  608#[derive(Debug, Clone, PartialEq, Eq)]
  609pub enum ContextMenuPlacement {
  610    Above,
  611    Below,
  612}
  613
  614#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  615struct EditorActionId(usize);
  616
  617impl EditorActionId {
  618    pub fn post_inc(&mut self) -> Self {
  619        let answer = self.0;
  620
  621        *self = Self(answer + 1);
  622
  623        Self(answer)
  624    }
  625}
  626
  627// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  628// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  629
  630type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  631type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  632
  633#[derive(Default)]
  634struct ScrollbarMarkerState {
  635    scrollbar_size: Size<Pixels>,
  636    dirty: bool,
  637    markers: Arc<[PaintQuad]>,
  638    pending_refresh: Option<Task<Result<()>>>,
  639}
  640
  641impl ScrollbarMarkerState {
  642    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  643        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  644    }
  645}
  646
  647#[derive(Clone, Debug)]
  648struct RunnableTasks {
  649    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  650    offset: multi_buffer::Anchor,
  651    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  652    column: u32,
  653    // Values of all named captures, including those starting with '_'
  654    extra_variables: HashMap<String, String>,
  655    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  656    context_range: Range<BufferOffset>,
  657}
  658
  659impl RunnableTasks {
  660    fn resolve<'a>(
  661        &'a self,
  662        cx: &'a task::TaskContext,
  663    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  664        self.templates.iter().filter_map(|(kind, template)| {
  665            template
  666                .resolve_task(&kind.to_id_base(), cx)
  667                .map(|task| (kind.clone(), task))
  668        })
  669    }
  670}
  671
  672#[derive(Clone)]
  673struct ResolvedTasks {
  674    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  675    position: Anchor,
  676}
  677
  678#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  679struct BufferOffset(usize);
  680
  681// Addons allow storing per-editor state in other crates (e.g. Vim)
  682pub trait Addon: 'static {
  683    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  684
  685    fn render_buffer_header_controls(
  686        &self,
  687        _: &ExcerptInfo,
  688        _: &Window,
  689        _: &App,
  690    ) -> Option<AnyElement> {
  691        None
  692    }
  693
  694    fn to_any(&self) -> &dyn std::any::Any;
  695}
  696
  697/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  698///
  699/// See the [module level documentation](self) for more information.
  700pub struct Editor {
  701    focus_handle: FocusHandle,
  702    last_focused_descendant: Option<WeakFocusHandle>,
  703    /// The text buffer being edited
  704    buffer: Entity<MultiBuffer>,
  705    /// Map of how text in the buffer should be displayed.
  706    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  707    pub display_map: Entity<DisplayMap>,
  708    pub selections: SelectionsCollection,
  709    pub scroll_manager: ScrollManager,
  710    /// When inline assist editors are linked, they all render cursors because
  711    /// typing enters text into each of them, even the ones that aren't focused.
  712    pub(crate) show_cursor_when_unfocused: bool,
  713    columnar_selection_tail: Option<Anchor>,
  714    add_selections_state: Option<AddSelectionsState>,
  715    select_next_state: Option<SelectNextState>,
  716    select_prev_state: Option<SelectNextState>,
  717    selection_history: SelectionHistory,
  718    autoclose_regions: Vec<AutocloseRegion>,
  719    snippet_stack: InvalidationStack<SnippetState>,
  720    select_syntax_node_history: SelectSyntaxNodeHistory,
  721    ime_transaction: Option<TransactionId>,
  722    active_diagnostics: ActiveDiagnostic,
  723    show_inline_diagnostics: bool,
  724    inline_diagnostics_update: Task<()>,
  725    inline_diagnostics_enabled: bool,
  726    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  727    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  728    hard_wrap: Option<usize>,
  729
  730    // TODO: make this a access method
  731    pub project: Option<Entity<Project>>,
  732    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  733    completion_provider: Option<Box<dyn CompletionProvider>>,
  734    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  735    blink_manager: Entity<BlinkManager>,
  736    show_cursor_names: bool,
  737    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  738    pub show_local_selections: bool,
  739    mode: EditorMode,
  740    show_breadcrumbs: bool,
  741    show_gutter: bool,
  742    show_scrollbars: bool,
  743    show_line_numbers: Option<bool>,
  744    use_relative_line_numbers: Option<bool>,
  745    show_git_diff_gutter: Option<bool>,
  746    show_code_actions: Option<bool>,
  747    show_runnables: Option<bool>,
  748    show_breakpoints: Option<bool>,
  749    show_wrap_guides: Option<bool>,
  750    show_indent_guides: Option<bool>,
  751    placeholder_text: Option<Arc<str>>,
  752    highlight_order: usize,
  753    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  754    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  755    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  756    scrollbar_marker_state: ScrollbarMarkerState,
  757    active_indent_guides_state: ActiveIndentGuidesState,
  758    nav_history: Option<ItemNavHistory>,
  759    context_menu: RefCell<Option<CodeContextMenu>>,
  760    context_menu_options: Option<ContextMenuOptions>,
  761    mouse_context_menu: Option<MouseContextMenu>,
  762    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  763    signature_help_state: SignatureHelpState,
  764    auto_signature_help: Option<bool>,
  765    find_all_references_task_sources: Vec<Anchor>,
  766    next_completion_id: CompletionId,
  767    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  768    code_actions_task: Option<Task<Result<()>>>,
  769    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  770    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  771    document_highlights_task: Option<Task<()>>,
  772    linked_editing_range_task: Option<Task<Option<()>>>,
  773    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  774    pending_rename: Option<RenameState>,
  775    searchable: bool,
  776    cursor_shape: CursorShape,
  777    current_line_highlight: Option<CurrentLineHighlight>,
  778    collapse_matches: bool,
  779    autoindent_mode: Option<AutoindentMode>,
  780    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  781    input_enabled: bool,
  782    use_modal_editing: bool,
  783    read_only: bool,
  784    leader_peer_id: Option<PeerId>,
  785    remote_id: Option<ViewId>,
  786    hover_state: HoverState,
  787    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  788    gutter_hovered: bool,
  789    hovered_link_state: Option<HoveredLinkState>,
  790    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  791    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  792    active_inline_completion: Option<InlineCompletionState>,
  793    /// Used to prevent flickering as the user types while the menu is open
  794    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  795    edit_prediction_settings: EditPredictionSettings,
  796    inline_completions_hidden_for_vim_mode: bool,
  797    show_inline_completions_override: Option<bool>,
  798    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  799    edit_prediction_preview: EditPredictionPreview,
  800    edit_prediction_indent_conflict: bool,
  801    edit_prediction_requires_modifier_in_indent_conflict: bool,
  802    inlay_hint_cache: InlayHintCache,
  803    next_inlay_id: usize,
  804    _subscriptions: Vec<Subscription>,
  805    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  806    gutter_dimensions: GutterDimensions,
  807    style: Option<EditorStyle>,
  808    text_style_refinement: Option<TextStyleRefinement>,
  809    next_editor_action_id: EditorActionId,
  810    editor_actions:
  811        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  812    use_autoclose: bool,
  813    use_auto_surround: bool,
  814    auto_replace_emoji_shortcode: bool,
  815    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  816    show_git_blame_gutter: bool,
  817    show_git_blame_inline: bool,
  818    show_git_blame_inline_delay_task: Option<Task<()>>,
  819    pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
  820    git_blame_inline_enabled: bool,
  821    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  822    serialize_dirty_buffers: bool,
  823    show_selection_menu: Option<bool>,
  824    blame: Option<Entity<GitBlame>>,
  825    blame_subscription: Option<Subscription>,
  826    custom_context_menu: Option<
  827        Box<
  828            dyn 'static
  829                + Fn(
  830                    &mut Self,
  831                    DisplayPoint,
  832                    &mut Window,
  833                    &mut Context<Self>,
  834                ) -> Option<Entity<ui::ContextMenu>>,
  835        >,
  836    >,
  837    last_bounds: Option<Bounds<Pixels>>,
  838    last_position_map: Option<Rc<PositionMap>>,
  839    expect_bounds_change: Option<Bounds<Pixels>>,
  840    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  841    tasks_update_task: Option<Task<()>>,
  842    breakpoint_store: Option<Entity<BreakpointStore>>,
  843    /// Allow's a user to create a breakpoint by selecting this indicator
  844    /// It should be None while a user is not hovering over the gutter
  845    /// Otherwise it represents the point that the breakpoint will be shown
  846    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  847    in_project_search: bool,
  848    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  849    breadcrumb_header: Option<String>,
  850    focused_block: Option<FocusedBlock>,
  851    next_scroll_position: NextScrollCursorCenterTopBottom,
  852    addons: HashMap<TypeId, Box<dyn Addon>>,
  853    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  854    load_diff_task: Option<Shared<Task<()>>>,
  855    selection_mark_mode: bool,
  856    toggle_fold_multiple_buffers: Task<()>,
  857    _scroll_cursor_center_top_bottom_task: Task<()>,
  858    serialize_selections: Task<()>,
  859    serialize_folds: Task<()>,
  860    mouse_cursor_hidden: bool,
  861    hide_mouse_mode: HideMouseMode,
  862}
  863
  864#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  865enum NextScrollCursorCenterTopBottom {
  866    #[default]
  867    Center,
  868    Top,
  869    Bottom,
  870}
  871
  872impl NextScrollCursorCenterTopBottom {
  873    fn next(&self) -> Self {
  874        match self {
  875            Self::Center => Self::Top,
  876            Self::Top => Self::Bottom,
  877            Self::Bottom => Self::Center,
  878        }
  879    }
  880}
  881
  882#[derive(Clone)]
  883pub struct EditorSnapshot {
  884    pub mode: EditorMode,
  885    show_gutter: bool,
  886    show_line_numbers: Option<bool>,
  887    show_git_diff_gutter: Option<bool>,
  888    show_code_actions: Option<bool>,
  889    show_runnables: Option<bool>,
  890    show_breakpoints: Option<bool>,
  891    git_blame_gutter_max_author_length: Option<usize>,
  892    pub display_snapshot: DisplaySnapshot,
  893    pub placeholder_text: Option<Arc<str>>,
  894    is_focused: bool,
  895    scroll_anchor: ScrollAnchor,
  896    ongoing_scroll: OngoingScroll,
  897    current_line_highlight: CurrentLineHighlight,
  898    gutter_hovered: bool,
  899}
  900
  901#[derive(Default, Debug, Clone, Copy)]
  902pub struct GutterDimensions {
  903    pub left_padding: Pixels,
  904    pub right_padding: Pixels,
  905    pub width: Pixels,
  906    pub margin: Pixels,
  907    pub git_blame_entries_width: Option<Pixels>,
  908}
  909
  910impl GutterDimensions {
  911    /// The full width of the space taken up by the gutter.
  912    pub fn full_width(&self) -> Pixels {
  913        self.margin + self.width
  914    }
  915
  916    /// The width of the space reserved for the fold indicators,
  917    /// use alongside 'justify_end' and `gutter_width` to
  918    /// right align content with the line numbers
  919    pub fn fold_area_width(&self) -> Pixels {
  920        self.margin + self.right_padding
  921    }
  922}
  923
  924#[derive(Debug)]
  925pub struct RemoteSelection {
  926    pub replica_id: ReplicaId,
  927    pub selection: Selection<Anchor>,
  928    pub cursor_shape: CursorShape,
  929    pub peer_id: PeerId,
  930    pub line_mode: bool,
  931    pub participant_index: Option<ParticipantIndex>,
  932    pub user_name: Option<SharedString>,
  933}
  934
  935#[derive(Clone, Debug)]
  936struct SelectionHistoryEntry {
  937    selections: Arc<[Selection<Anchor>]>,
  938    select_next_state: Option<SelectNextState>,
  939    select_prev_state: Option<SelectNextState>,
  940    add_selections_state: Option<AddSelectionsState>,
  941}
  942
  943enum SelectionHistoryMode {
  944    Normal,
  945    Undoing,
  946    Redoing,
  947}
  948
  949#[derive(Clone, PartialEq, Eq, Hash)]
  950struct HoveredCursor {
  951    replica_id: u16,
  952    selection_id: usize,
  953}
  954
  955impl Default for SelectionHistoryMode {
  956    fn default() -> Self {
  957        Self::Normal
  958    }
  959}
  960
  961#[derive(Default)]
  962struct SelectionHistory {
  963    #[allow(clippy::type_complexity)]
  964    selections_by_transaction:
  965        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  966    mode: SelectionHistoryMode,
  967    undo_stack: VecDeque<SelectionHistoryEntry>,
  968    redo_stack: VecDeque<SelectionHistoryEntry>,
  969}
  970
  971impl SelectionHistory {
  972    fn insert_transaction(
  973        &mut self,
  974        transaction_id: TransactionId,
  975        selections: Arc<[Selection<Anchor>]>,
  976    ) {
  977        self.selections_by_transaction
  978            .insert(transaction_id, (selections, None));
  979    }
  980
  981    #[allow(clippy::type_complexity)]
  982    fn transaction(
  983        &self,
  984        transaction_id: TransactionId,
  985    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  986        self.selections_by_transaction.get(&transaction_id)
  987    }
  988
  989    #[allow(clippy::type_complexity)]
  990    fn transaction_mut(
  991        &mut self,
  992        transaction_id: TransactionId,
  993    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  994        self.selections_by_transaction.get_mut(&transaction_id)
  995    }
  996
  997    fn push(&mut self, entry: SelectionHistoryEntry) {
  998        if !entry.selections.is_empty() {
  999            match self.mode {
 1000                SelectionHistoryMode::Normal => {
 1001                    self.push_undo(entry);
 1002                    self.redo_stack.clear();
 1003                }
 1004                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1005                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1006            }
 1007        }
 1008    }
 1009
 1010    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1011        if self
 1012            .undo_stack
 1013            .back()
 1014            .map_or(true, |e| e.selections != entry.selections)
 1015        {
 1016            self.undo_stack.push_back(entry);
 1017            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1018                self.undo_stack.pop_front();
 1019            }
 1020        }
 1021    }
 1022
 1023    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1024        if self
 1025            .redo_stack
 1026            .back()
 1027            .map_or(true, |e| e.selections != entry.selections)
 1028        {
 1029            self.redo_stack.push_back(entry);
 1030            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1031                self.redo_stack.pop_front();
 1032            }
 1033        }
 1034    }
 1035}
 1036
 1037struct RowHighlight {
 1038    index: usize,
 1039    range: Range<Anchor>,
 1040    color: Hsla,
 1041    should_autoscroll: bool,
 1042}
 1043
 1044#[derive(Clone, Debug)]
 1045struct AddSelectionsState {
 1046    above: bool,
 1047    stack: Vec<usize>,
 1048}
 1049
 1050#[derive(Clone)]
 1051struct SelectNextState {
 1052    query: AhoCorasick,
 1053    wordwise: bool,
 1054    done: bool,
 1055}
 1056
 1057impl std::fmt::Debug for SelectNextState {
 1058    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1059        f.debug_struct(std::any::type_name::<Self>())
 1060            .field("wordwise", &self.wordwise)
 1061            .field("done", &self.done)
 1062            .finish()
 1063    }
 1064}
 1065
 1066#[derive(Debug)]
 1067struct AutocloseRegion {
 1068    selection_id: usize,
 1069    range: Range<Anchor>,
 1070    pair: BracketPair,
 1071}
 1072
 1073#[derive(Debug)]
 1074struct SnippetState {
 1075    ranges: Vec<Vec<Range<Anchor>>>,
 1076    active_index: usize,
 1077    choices: Vec<Option<Vec<String>>>,
 1078}
 1079
 1080#[doc(hidden)]
 1081pub struct RenameState {
 1082    pub range: Range<Anchor>,
 1083    pub old_name: Arc<str>,
 1084    pub editor: Entity<Editor>,
 1085    block_id: CustomBlockId,
 1086}
 1087
 1088struct InvalidationStack<T>(Vec<T>);
 1089
 1090struct RegisteredInlineCompletionProvider {
 1091    provider: Arc<dyn InlineCompletionProviderHandle>,
 1092    _subscription: Subscription,
 1093}
 1094
 1095#[derive(Debug, PartialEq, Eq)]
 1096pub struct ActiveDiagnosticGroup {
 1097    pub active_range: Range<Anchor>,
 1098    pub active_message: String,
 1099    pub group_id: usize,
 1100    pub blocks: HashSet<CustomBlockId>,
 1101}
 1102
 1103#[derive(Debug, PartialEq, Eq)]
 1104#[allow(clippy::large_enum_variant)]
 1105pub(crate) enum ActiveDiagnostic {
 1106    None,
 1107    All,
 1108    Group(ActiveDiagnosticGroup),
 1109}
 1110
 1111#[derive(Serialize, Deserialize, Clone, Debug)]
 1112pub struct ClipboardSelection {
 1113    /// The number of bytes in this selection.
 1114    pub len: usize,
 1115    /// Whether this was a full-line selection.
 1116    pub is_entire_line: bool,
 1117    /// The indentation of the first line when this content was originally copied.
 1118    pub first_line_indent: u32,
 1119}
 1120
 1121// selections, scroll behavior, was newest selection reversed
 1122type SelectSyntaxNodeHistoryState = (
 1123    Box<[Selection<usize>]>,
 1124    SelectSyntaxNodeScrollBehavior,
 1125    bool,
 1126);
 1127
 1128#[derive(Default)]
 1129struct SelectSyntaxNodeHistory {
 1130    stack: Vec<SelectSyntaxNodeHistoryState>,
 1131    // disable temporarily to allow changing selections without losing the stack
 1132    pub disable_clearing: bool,
 1133}
 1134
 1135impl SelectSyntaxNodeHistory {
 1136    pub fn try_clear(&mut self) {
 1137        if !self.disable_clearing {
 1138            self.stack.clear();
 1139        }
 1140    }
 1141
 1142    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1143        self.stack.push(selection);
 1144    }
 1145
 1146    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1147        self.stack.pop()
 1148    }
 1149}
 1150
 1151enum SelectSyntaxNodeScrollBehavior {
 1152    CursorTop,
 1153    FitSelection,
 1154    CursorBottom,
 1155}
 1156
 1157#[derive(Debug)]
 1158pub(crate) struct NavigationData {
 1159    cursor_anchor: Anchor,
 1160    cursor_position: Point,
 1161    scroll_anchor: ScrollAnchor,
 1162    scroll_top_row: u32,
 1163}
 1164
 1165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1166pub enum GotoDefinitionKind {
 1167    Symbol,
 1168    Declaration,
 1169    Type,
 1170    Implementation,
 1171}
 1172
 1173#[derive(Debug, Clone)]
 1174enum InlayHintRefreshReason {
 1175    ModifiersChanged(bool),
 1176    Toggle(bool),
 1177    SettingsChange(InlayHintSettings),
 1178    NewLinesShown,
 1179    BufferEdited(HashSet<Arc<Language>>),
 1180    RefreshRequested,
 1181    ExcerptsRemoved(Vec<ExcerptId>),
 1182}
 1183
 1184impl InlayHintRefreshReason {
 1185    fn description(&self) -> &'static str {
 1186        match self {
 1187            Self::ModifiersChanged(_) => "modifiers changed",
 1188            Self::Toggle(_) => "toggle",
 1189            Self::SettingsChange(_) => "settings change",
 1190            Self::NewLinesShown => "new lines shown",
 1191            Self::BufferEdited(_) => "buffer edited",
 1192            Self::RefreshRequested => "refresh requested",
 1193            Self::ExcerptsRemoved(_) => "excerpts removed",
 1194        }
 1195    }
 1196}
 1197
 1198pub enum FormatTarget {
 1199    Buffers,
 1200    Ranges(Vec<Range<MultiBufferPoint>>),
 1201}
 1202
 1203pub(crate) struct FocusedBlock {
 1204    id: BlockId,
 1205    focus_handle: WeakFocusHandle,
 1206}
 1207
 1208#[derive(Clone)]
 1209enum JumpData {
 1210    MultiBufferRow {
 1211        row: MultiBufferRow,
 1212        line_offset_from_top: u32,
 1213    },
 1214    MultiBufferPoint {
 1215        excerpt_id: ExcerptId,
 1216        position: Point,
 1217        anchor: text::Anchor,
 1218        line_offset_from_top: u32,
 1219    },
 1220}
 1221
 1222pub enum MultibufferSelectionMode {
 1223    First,
 1224    All,
 1225}
 1226
 1227#[derive(Clone, Copy, Debug, Default)]
 1228pub struct RewrapOptions {
 1229    pub override_language_settings: bool,
 1230    pub preserve_existing_whitespace: bool,
 1231}
 1232
 1233impl Editor {
 1234    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1235        let buffer = cx.new(|cx| Buffer::local("", cx));
 1236        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1237        Self::new(
 1238            EditorMode::SingleLine { auto_width: false },
 1239            buffer,
 1240            None,
 1241            window,
 1242            cx,
 1243        )
 1244    }
 1245
 1246    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1247        let buffer = cx.new(|cx| Buffer::local("", cx));
 1248        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1249        Self::new(EditorMode::full(), buffer, None, window, cx)
 1250    }
 1251
 1252    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1253        let buffer = cx.new(|cx| Buffer::local("", cx));
 1254        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1255        Self::new(
 1256            EditorMode::SingleLine { auto_width: true },
 1257            buffer,
 1258            None,
 1259            window,
 1260            cx,
 1261        )
 1262    }
 1263
 1264    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1265        let buffer = cx.new(|cx| Buffer::local("", cx));
 1266        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1267        Self::new(
 1268            EditorMode::AutoHeight { max_lines },
 1269            buffer,
 1270            None,
 1271            window,
 1272            cx,
 1273        )
 1274    }
 1275
 1276    pub fn for_buffer(
 1277        buffer: Entity<Buffer>,
 1278        project: Option<Entity<Project>>,
 1279        window: &mut Window,
 1280        cx: &mut Context<Self>,
 1281    ) -> Self {
 1282        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1283        Self::new(EditorMode::full(), buffer, project, window, cx)
 1284    }
 1285
 1286    pub fn for_multibuffer(
 1287        buffer: Entity<MultiBuffer>,
 1288        project: Option<Entity<Project>>,
 1289        window: &mut Window,
 1290        cx: &mut Context<Self>,
 1291    ) -> Self {
 1292        Self::new(EditorMode::full(), buffer, project, window, cx)
 1293    }
 1294
 1295    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1296        let mut clone = Self::new(
 1297            self.mode,
 1298            self.buffer.clone(),
 1299            self.project.clone(),
 1300            window,
 1301            cx,
 1302        );
 1303        self.display_map.update(cx, |display_map, cx| {
 1304            let snapshot = display_map.snapshot(cx);
 1305            clone.display_map.update(cx, |display_map, cx| {
 1306                display_map.set_state(&snapshot, cx);
 1307            });
 1308        });
 1309        clone.folds_did_change(cx);
 1310        clone.selections.clone_state(&self.selections);
 1311        clone.scroll_manager.clone_state(&self.scroll_manager);
 1312        clone.searchable = self.searchable;
 1313        clone.read_only = self.read_only;
 1314        clone
 1315    }
 1316
 1317    pub fn new(
 1318        mode: EditorMode,
 1319        buffer: Entity<MultiBuffer>,
 1320        project: Option<Entity<Project>>,
 1321        window: &mut Window,
 1322        cx: &mut Context<Self>,
 1323    ) -> Self {
 1324        let style = window.text_style();
 1325        let font_size = style.font_size.to_pixels(window.rem_size());
 1326        let editor = cx.entity().downgrade();
 1327        let fold_placeholder = FoldPlaceholder {
 1328            constrain_width: true,
 1329            render: Arc::new(move |fold_id, fold_range, cx| {
 1330                let editor = editor.clone();
 1331                div()
 1332                    .id(fold_id)
 1333                    .bg(cx.theme().colors().ghost_element_background)
 1334                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1335                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1336                    .rounded_xs()
 1337                    .size_full()
 1338                    .cursor_pointer()
 1339                    .child("")
 1340                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1341                    .on_click(move |_, _window, cx| {
 1342                        editor
 1343                            .update(cx, |editor, cx| {
 1344                                editor.unfold_ranges(
 1345                                    &[fold_range.start..fold_range.end],
 1346                                    true,
 1347                                    false,
 1348                                    cx,
 1349                                );
 1350                                cx.stop_propagation();
 1351                            })
 1352                            .ok();
 1353                    })
 1354                    .into_any()
 1355            }),
 1356            merge_adjacent: true,
 1357            ..Default::default()
 1358        };
 1359        let display_map = cx.new(|cx| {
 1360            DisplayMap::new(
 1361                buffer.clone(),
 1362                style.font(),
 1363                font_size,
 1364                None,
 1365                FILE_HEADER_HEIGHT,
 1366                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1367                fold_placeholder,
 1368                cx,
 1369            )
 1370        });
 1371
 1372        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1373
 1374        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1375
 1376        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1377            .then(|| language_settings::SoftWrap::None);
 1378
 1379        let mut project_subscriptions = Vec::new();
 1380        if mode.is_full() {
 1381            if let Some(project) = project.as_ref() {
 1382                project_subscriptions.push(cx.subscribe_in(
 1383                    project,
 1384                    window,
 1385                    |editor, _, event, window, cx| match event {
 1386                        project::Event::RefreshCodeLens => {
 1387                            // we always query lens with actions, without storing them, always refreshing them
 1388                        }
 1389                        project::Event::RefreshInlayHints => {
 1390                            editor
 1391                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1392                        }
 1393                        project::Event::SnippetEdit(id, snippet_edits) => {
 1394                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1395                                let focus_handle = editor.focus_handle(cx);
 1396                                if focus_handle.is_focused(window) {
 1397                                    let snapshot = buffer.read(cx).snapshot();
 1398                                    for (range, snippet) in snippet_edits {
 1399                                        let editor_range =
 1400                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1401                                        editor
 1402                                            .insert_snippet(
 1403                                                &[editor_range],
 1404                                                snippet.clone(),
 1405                                                window,
 1406                                                cx,
 1407                                            )
 1408                                            .ok();
 1409                                    }
 1410                                }
 1411                            }
 1412                        }
 1413                        _ => {}
 1414                    },
 1415                ));
 1416                if let Some(task_inventory) = project
 1417                    .read(cx)
 1418                    .task_store()
 1419                    .read(cx)
 1420                    .task_inventory()
 1421                    .cloned()
 1422                {
 1423                    project_subscriptions.push(cx.observe_in(
 1424                        &task_inventory,
 1425                        window,
 1426                        |editor, _, window, cx| {
 1427                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1428                        },
 1429                    ));
 1430                };
 1431
 1432                project_subscriptions.push(cx.subscribe_in(
 1433                    &project.read(cx).breakpoint_store(),
 1434                    window,
 1435                    |editor, _, event, window, cx| match event {
 1436                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1437                            if editor.go_to_active_debug_line(window, cx) {
 1438                                cx.stop_propagation();
 1439                            }
 1440                        }
 1441                        _ => {}
 1442                    },
 1443                ));
 1444            }
 1445        }
 1446
 1447        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1448
 1449        let inlay_hint_settings =
 1450            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1451        let focus_handle = cx.focus_handle();
 1452        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1453            .detach();
 1454        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1455            .detach();
 1456        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1457            .detach();
 1458        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1459            .detach();
 1460
 1461        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1462            Some(false)
 1463        } else {
 1464            None
 1465        };
 1466
 1467        let breakpoint_store = match (mode, project.as_ref()) {
 1468            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1469            _ => None,
 1470        };
 1471
 1472        let mut code_action_providers = Vec::new();
 1473        let mut load_uncommitted_diff = None;
 1474        if let Some(project) = project.clone() {
 1475            load_uncommitted_diff = Some(
 1476                get_uncommitted_diff_for_buffer(
 1477                    &project,
 1478                    buffer.read(cx).all_buffers(),
 1479                    buffer.clone(),
 1480                    cx,
 1481                )
 1482                .shared(),
 1483            );
 1484            code_action_providers.push(Rc::new(project) as Rc<_>);
 1485        }
 1486
 1487        let mut this = Self {
 1488            focus_handle,
 1489            show_cursor_when_unfocused: false,
 1490            last_focused_descendant: None,
 1491            buffer: buffer.clone(),
 1492            display_map: display_map.clone(),
 1493            selections,
 1494            scroll_manager: ScrollManager::new(cx),
 1495            columnar_selection_tail: None,
 1496            add_selections_state: None,
 1497            select_next_state: None,
 1498            select_prev_state: None,
 1499            selection_history: Default::default(),
 1500            autoclose_regions: Default::default(),
 1501            snippet_stack: Default::default(),
 1502            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1503            ime_transaction: Default::default(),
 1504            active_diagnostics: ActiveDiagnostic::None,
 1505            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1506            inline_diagnostics_update: Task::ready(()),
 1507            inline_diagnostics: Vec::new(),
 1508            soft_wrap_mode_override,
 1509            hard_wrap: None,
 1510            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1511            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1512            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1513            project,
 1514            blink_manager: blink_manager.clone(),
 1515            show_local_selections: true,
 1516            show_scrollbars: true,
 1517            mode,
 1518            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1519            show_gutter: mode.is_full(),
 1520            show_line_numbers: None,
 1521            use_relative_line_numbers: None,
 1522            show_git_diff_gutter: None,
 1523            show_code_actions: None,
 1524            show_runnables: None,
 1525            show_breakpoints: None,
 1526            show_wrap_guides: None,
 1527            show_indent_guides,
 1528            placeholder_text: None,
 1529            highlight_order: 0,
 1530            highlighted_rows: HashMap::default(),
 1531            background_highlights: Default::default(),
 1532            gutter_highlights: TreeMap::default(),
 1533            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1534            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1535            nav_history: None,
 1536            context_menu: RefCell::new(None),
 1537            context_menu_options: None,
 1538            mouse_context_menu: None,
 1539            completion_tasks: Default::default(),
 1540            signature_help_state: SignatureHelpState::default(),
 1541            auto_signature_help: None,
 1542            find_all_references_task_sources: Vec::new(),
 1543            next_completion_id: 0,
 1544            next_inlay_id: 0,
 1545            code_action_providers,
 1546            available_code_actions: Default::default(),
 1547            code_actions_task: Default::default(),
 1548            quick_selection_highlight_task: Default::default(),
 1549            debounced_selection_highlight_task: Default::default(),
 1550            document_highlights_task: Default::default(),
 1551            linked_editing_range_task: Default::default(),
 1552            pending_rename: Default::default(),
 1553            searchable: true,
 1554            cursor_shape: EditorSettings::get_global(cx)
 1555                .cursor_shape
 1556                .unwrap_or_default(),
 1557            current_line_highlight: None,
 1558            autoindent_mode: Some(AutoindentMode::EachLine),
 1559            collapse_matches: false,
 1560            workspace: None,
 1561            input_enabled: true,
 1562            use_modal_editing: mode.is_full(),
 1563            read_only: false,
 1564            use_autoclose: true,
 1565            use_auto_surround: true,
 1566            auto_replace_emoji_shortcode: false,
 1567            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1568            leader_peer_id: None,
 1569            remote_id: None,
 1570            hover_state: Default::default(),
 1571            pending_mouse_down: None,
 1572            hovered_link_state: Default::default(),
 1573            edit_prediction_provider: None,
 1574            active_inline_completion: None,
 1575            stale_inline_completion_in_menu: None,
 1576            edit_prediction_preview: EditPredictionPreview::Inactive {
 1577                released_too_fast: false,
 1578            },
 1579            inline_diagnostics_enabled: mode.is_full(),
 1580            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1581
 1582            gutter_hovered: false,
 1583            pixel_position_of_newest_cursor: None,
 1584            last_bounds: None,
 1585            last_position_map: None,
 1586            expect_bounds_change: None,
 1587            gutter_dimensions: GutterDimensions::default(),
 1588            style: None,
 1589            show_cursor_names: false,
 1590            hovered_cursors: Default::default(),
 1591            next_editor_action_id: EditorActionId::default(),
 1592            editor_actions: Rc::default(),
 1593            inline_completions_hidden_for_vim_mode: false,
 1594            show_inline_completions_override: None,
 1595            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1596            edit_prediction_settings: EditPredictionSettings::Disabled,
 1597            edit_prediction_indent_conflict: false,
 1598            edit_prediction_requires_modifier_in_indent_conflict: true,
 1599            custom_context_menu: None,
 1600            show_git_blame_gutter: false,
 1601            show_git_blame_inline: false,
 1602            show_selection_menu: None,
 1603            show_git_blame_inline_delay_task: None,
 1604            git_blame_inline_tooltip: None,
 1605            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1606            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1607            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1608                .session
 1609                .restore_unsaved_buffers,
 1610            blame: None,
 1611            blame_subscription: None,
 1612            tasks: Default::default(),
 1613
 1614            breakpoint_store,
 1615            gutter_breakpoint_indicator: (None, None),
 1616            _subscriptions: vec![
 1617                cx.observe(&buffer, Self::on_buffer_changed),
 1618                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1619                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1620                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1621                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1622                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1623                cx.observe_window_activation(window, |editor, window, cx| {
 1624                    let active = window.is_window_active();
 1625                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1626                        if active {
 1627                            blink_manager.enable(cx);
 1628                        } else {
 1629                            blink_manager.disable(cx);
 1630                        }
 1631                    });
 1632                }),
 1633            ],
 1634            tasks_update_task: None,
 1635            linked_edit_ranges: Default::default(),
 1636            in_project_search: false,
 1637            previous_search_ranges: None,
 1638            breadcrumb_header: None,
 1639            focused_block: None,
 1640            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1641            addons: HashMap::default(),
 1642            registered_buffers: HashMap::default(),
 1643            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1644            selection_mark_mode: false,
 1645            toggle_fold_multiple_buffers: Task::ready(()),
 1646            serialize_selections: Task::ready(()),
 1647            serialize_folds: Task::ready(()),
 1648            text_style_refinement: None,
 1649            load_diff_task: load_uncommitted_diff,
 1650            mouse_cursor_hidden: false,
 1651            hide_mouse_mode: EditorSettings::get_global(cx)
 1652                .hide_mouse
 1653                .unwrap_or_default(),
 1654        };
 1655        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1656            this._subscriptions
 1657                .push(cx.observe(breakpoints, |_, _, cx| {
 1658                    cx.notify();
 1659                }));
 1660        }
 1661        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1662        this._subscriptions.extend(project_subscriptions);
 1663
 1664        this._subscriptions.push(cx.subscribe_in(
 1665            &cx.entity(),
 1666            window,
 1667            |editor, _, e: &EditorEvent, window, cx| {
 1668                if let EditorEvent::SelectionsChanged { local } = e {
 1669                    if *local {
 1670                        let new_anchor = editor.scroll_manager.anchor();
 1671                        let snapshot = editor.snapshot(window, cx);
 1672                        editor.update_restoration_data(cx, move |data| {
 1673                            data.scroll_position = (
 1674                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1675                                new_anchor.offset,
 1676                            );
 1677                        });
 1678                    }
 1679                }
 1680            },
 1681        ));
 1682
 1683        this.end_selection(window, cx);
 1684        this.scroll_manager.show_scrollbars(window, cx);
 1685        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1686
 1687        if mode.is_full() {
 1688            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1689            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1690
 1691            if this.git_blame_inline_enabled {
 1692                this.git_blame_inline_enabled = true;
 1693                this.start_git_blame_inline(false, window, cx);
 1694            }
 1695
 1696            this.go_to_active_debug_line(window, cx);
 1697
 1698            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1699                if let Some(project) = this.project.as_ref() {
 1700                    let handle = project.update(cx, |project, cx| {
 1701                        project.register_buffer_with_language_servers(&buffer, cx)
 1702                    });
 1703                    this.registered_buffers
 1704                        .insert(buffer.read(cx).remote_id(), handle);
 1705                }
 1706            }
 1707        }
 1708
 1709        this.report_editor_event("Editor Opened", None, cx);
 1710        this
 1711    }
 1712
 1713    pub fn deploy_mouse_context_menu(
 1714        &mut self,
 1715        position: gpui::Point<Pixels>,
 1716        context_menu: Entity<ContextMenu>,
 1717        window: &mut Window,
 1718        cx: &mut Context<Self>,
 1719    ) {
 1720        self.mouse_context_menu = Some(MouseContextMenu::new(
 1721            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1722            context_menu,
 1723            None,
 1724            window,
 1725            cx,
 1726        ));
 1727    }
 1728
 1729    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1730        self.mouse_context_menu
 1731            .as_ref()
 1732            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1733    }
 1734
 1735    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1736        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1737    }
 1738
 1739    fn key_context_internal(
 1740        &self,
 1741        has_active_edit_prediction: bool,
 1742        window: &Window,
 1743        cx: &App,
 1744    ) -> KeyContext {
 1745        let mut key_context = KeyContext::new_with_defaults();
 1746        key_context.add("Editor");
 1747        let mode = match self.mode {
 1748            EditorMode::SingleLine { .. } => "single_line",
 1749            EditorMode::AutoHeight { .. } => "auto_height",
 1750            EditorMode::Full { .. } => "full",
 1751        };
 1752
 1753        if EditorSettings::jupyter_enabled(cx) {
 1754            key_context.add("jupyter");
 1755        }
 1756
 1757        key_context.set("mode", mode);
 1758        if self.pending_rename.is_some() {
 1759            key_context.add("renaming");
 1760        }
 1761
 1762        match self.context_menu.borrow().as_ref() {
 1763            Some(CodeContextMenu::Completions(_)) => {
 1764                key_context.add("menu");
 1765                key_context.add("showing_completions");
 1766            }
 1767            Some(CodeContextMenu::CodeActions(_)) => {
 1768                key_context.add("menu");
 1769                key_context.add("showing_code_actions")
 1770            }
 1771            None => {}
 1772        }
 1773
 1774        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1775        if !self.focus_handle(cx).contains_focused(window, cx)
 1776            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1777        {
 1778            for addon in self.addons.values() {
 1779                addon.extend_key_context(&mut key_context, cx)
 1780            }
 1781        }
 1782
 1783        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1784            if let Some(extension) = singleton_buffer
 1785                .read(cx)
 1786                .file()
 1787                .and_then(|file| file.path().extension()?.to_str())
 1788            {
 1789                key_context.set("extension", extension.to_string());
 1790            }
 1791        } else {
 1792            key_context.add("multibuffer");
 1793        }
 1794
 1795        if has_active_edit_prediction {
 1796            if self.edit_prediction_in_conflict() {
 1797                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1798            } else {
 1799                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1800                key_context.add("copilot_suggestion");
 1801            }
 1802        }
 1803
 1804        if self.selection_mark_mode {
 1805            key_context.add("selection_mode");
 1806        }
 1807
 1808        key_context
 1809    }
 1810
 1811    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 1812        self.mouse_cursor_hidden = match origin {
 1813            HideMouseCursorOrigin::TypingAction => {
 1814                matches!(
 1815                    self.hide_mouse_mode,
 1816                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 1817                )
 1818            }
 1819            HideMouseCursorOrigin::MovementAction => {
 1820                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 1821            }
 1822        };
 1823    }
 1824
 1825    pub fn edit_prediction_in_conflict(&self) -> bool {
 1826        if !self.show_edit_predictions_in_menu() {
 1827            return false;
 1828        }
 1829
 1830        let showing_completions = self
 1831            .context_menu
 1832            .borrow()
 1833            .as_ref()
 1834            .map_or(false, |context| {
 1835                matches!(context, CodeContextMenu::Completions(_))
 1836            });
 1837
 1838        showing_completions
 1839            || self.edit_prediction_requires_modifier()
 1840            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1841            // bindings to insert tab characters.
 1842            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1843    }
 1844
 1845    pub fn accept_edit_prediction_keybind(
 1846        &self,
 1847        window: &Window,
 1848        cx: &App,
 1849    ) -> AcceptEditPredictionBinding {
 1850        let key_context = self.key_context_internal(true, window, cx);
 1851        let in_conflict = self.edit_prediction_in_conflict();
 1852
 1853        AcceptEditPredictionBinding(
 1854            window
 1855                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1856                .into_iter()
 1857                .filter(|binding| {
 1858                    !in_conflict
 1859                        || binding
 1860                            .keystrokes()
 1861                            .first()
 1862                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1863                })
 1864                .rev()
 1865                .min_by_key(|binding| {
 1866                    binding
 1867                        .keystrokes()
 1868                        .first()
 1869                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1870                }),
 1871        )
 1872    }
 1873
 1874    pub fn new_file(
 1875        workspace: &mut Workspace,
 1876        _: &workspace::NewFile,
 1877        window: &mut Window,
 1878        cx: &mut Context<Workspace>,
 1879    ) {
 1880        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1881            "Failed to create buffer",
 1882            window,
 1883            cx,
 1884            |e, _, _| match e.error_code() {
 1885                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1886                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1887                e.error_tag("required").unwrap_or("the latest version")
 1888            )),
 1889                _ => None,
 1890            },
 1891        );
 1892    }
 1893
 1894    pub fn new_in_workspace(
 1895        workspace: &mut Workspace,
 1896        window: &mut Window,
 1897        cx: &mut Context<Workspace>,
 1898    ) -> Task<Result<Entity<Editor>>> {
 1899        let project = workspace.project().clone();
 1900        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1901
 1902        cx.spawn_in(window, async move |workspace, cx| {
 1903            let buffer = create.await?;
 1904            workspace.update_in(cx, |workspace, window, cx| {
 1905                let editor =
 1906                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1907                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1908                editor
 1909            })
 1910        })
 1911    }
 1912
 1913    fn new_file_vertical(
 1914        workspace: &mut Workspace,
 1915        _: &workspace::NewFileSplitVertical,
 1916        window: &mut Window,
 1917        cx: &mut Context<Workspace>,
 1918    ) {
 1919        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1920    }
 1921
 1922    fn new_file_horizontal(
 1923        workspace: &mut Workspace,
 1924        _: &workspace::NewFileSplitHorizontal,
 1925        window: &mut Window,
 1926        cx: &mut Context<Workspace>,
 1927    ) {
 1928        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1929    }
 1930
 1931    fn new_file_in_direction(
 1932        workspace: &mut Workspace,
 1933        direction: SplitDirection,
 1934        window: &mut Window,
 1935        cx: &mut Context<Workspace>,
 1936    ) {
 1937        let project = workspace.project().clone();
 1938        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1939
 1940        cx.spawn_in(window, async move |workspace, cx| {
 1941            let buffer = create.await?;
 1942            workspace.update_in(cx, move |workspace, window, cx| {
 1943                workspace.split_item(
 1944                    direction,
 1945                    Box::new(
 1946                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1947                    ),
 1948                    window,
 1949                    cx,
 1950                )
 1951            })?;
 1952            anyhow::Ok(())
 1953        })
 1954        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1955            match e.error_code() {
 1956                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1957                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1958                e.error_tag("required").unwrap_or("the latest version")
 1959            )),
 1960                _ => None,
 1961            }
 1962        });
 1963    }
 1964
 1965    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1966        self.leader_peer_id
 1967    }
 1968
 1969    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1970        &self.buffer
 1971    }
 1972
 1973    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1974        self.workspace.as_ref()?.0.upgrade()
 1975    }
 1976
 1977    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1978        self.buffer().read(cx).title(cx)
 1979    }
 1980
 1981    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1982        let git_blame_gutter_max_author_length = self
 1983            .render_git_blame_gutter(cx)
 1984            .then(|| {
 1985                if let Some(blame) = self.blame.as_ref() {
 1986                    let max_author_length =
 1987                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1988                    Some(max_author_length)
 1989                } else {
 1990                    None
 1991                }
 1992            })
 1993            .flatten();
 1994
 1995        EditorSnapshot {
 1996            mode: self.mode,
 1997            show_gutter: self.show_gutter,
 1998            show_line_numbers: self.show_line_numbers,
 1999            show_git_diff_gutter: self.show_git_diff_gutter,
 2000            show_code_actions: self.show_code_actions,
 2001            show_runnables: self.show_runnables,
 2002            show_breakpoints: self.show_breakpoints,
 2003            git_blame_gutter_max_author_length,
 2004            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2005            scroll_anchor: self.scroll_manager.anchor(),
 2006            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2007            placeholder_text: self.placeholder_text.clone(),
 2008            is_focused: self.focus_handle.is_focused(window),
 2009            current_line_highlight: self
 2010                .current_line_highlight
 2011                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2012            gutter_hovered: self.gutter_hovered,
 2013        }
 2014    }
 2015
 2016    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2017        self.buffer.read(cx).language_at(point, cx)
 2018    }
 2019
 2020    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2021        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2022    }
 2023
 2024    pub fn active_excerpt(
 2025        &self,
 2026        cx: &App,
 2027    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2028        self.buffer
 2029            .read(cx)
 2030            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2031    }
 2032
 2033    pub fn mode(&self) -> EditorMode {
 2034        self.mode
 2035    }
 2036
 2037    pub fn set_mode(&mut self, mode: EditorMode) {
 2038        self.mode = mode;
 2039    }
 2040
 2041    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2042        self.collaboration_hub.as_deref()
 2043    }
 2044
 2045    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2046        self.collaboration_hub = Some(hub);
 2047    }
 2048
 2049    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2050        self.in_project_search = in_project_search;
 2051    }
 2052
 2053    pub fn set_custom_context_menu(
 2054        &mut self,
 2055        f: impl 'static
 2056        + Fn(
 2057            &mut Self,
 2058            DisplayPoint,
 2059            &mut Window,
 2060            &mut Context<Self>,
 2061        ) -> Option<Entity<ui::ContextMenu>>,
 2062    ) {
 2063        self.custom_context_menu = Some(Box::new(f))
 2064    }
 2065
 2066    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2067        self.completion_provider = provider;
 2068    }
 2069
 2070    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2071        self.semantics_provider.clone()
 2072    }
 2073
 2074    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2075        self.semantics_provider = provider;
 2076    }
 2077
 2078    pub fn set_edit_prediction_provider<T>(
 2079        &mut self,
 2080        provider: Option<Entity<T>>,
 2081        window: &mut Window,
 2082        cx: &mut Context<Self>,
 2083    ) where
 2084        T: EditPredictionProvider,
 2085    {
 2086        self.edit_prediction_provider =
 2087            provider.map(|provider| RegisteredInlineCompletionProvider {
 2088                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2089                    if this.focus_handle.is_focused(window) {
 2090                        this.update_visible_inline_completion(window, cx);
 2091                    }
 2092                }),
 2093                provider: Arc::new(provider),
 2094            });
 2095        self.update_edit_prediction_settings(cx);
 2096        self.refresh_inline_completion(false, false, window, cx);
 2097    }
 2098
 2099    pub fn placeholder_text(&self) -> Option<&str> {
 2100        self.placeholder_text.as_deref()
 2101    }
 2102
 2103    pub fn set_placeholder_text(
 2104        &mut self,
 2105        placeholder_text: impl Into<Arc<str>>,
 2106        cx: &mut Context<Self>,
 2107    ) {
 2108        let placeholder_text = Some(placeholder_text.into());
 2109        if self.placeholder_text != placeholder_text {
 2110            self.placeholder_text = placeholder_text;
 2111            cx.notify();
 2112        }
 2113    }
 2114
 2115    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2116        self.cursor_shape = cursor_shape;
 2117
 2118        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2119        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2120
 2121        cx.notify();
 2122    }
 2123
 2124    pub fn set_current_line_highlight(
 2125        &mut self,
 2126        current_line_highlight: Option<CurrentLineHighlight>,
 2127    ) {
 2128        self.current_line_highlight = current_line_highlight;
 2129    }
 2130
 2131    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2132        self.collapse_matches = collapse_matches;
 2133    }
 2134
 2135    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2136        let buffers = self.buffer.read(cx).all_buffers();
 2137        let Some(project) = self.project.as_ref() else {
 2138            return;
 2139        };
 2140        project.update(cx, |project, cx| {
 2141            for buffer in buffers {
 2142                self.registered_buffers
 2143                    .entry(buffer.read(cx).remote_id())
 2144                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2145            }
 2146        })
 2147    }
 2148
 2149    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2150        if self.collapse_matches {
 2151            return range.start..range.start;
 2152        }
 2153        range.clone()
 2154    }
 2155
 2156    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2157        if self.display_map.read(cx).clip_at_line_ends != clip {
 2158            self.display_map
 2159                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2160        }
 2161    }
 2162
 2163    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2164        self.input_enabled = input_enabled;
 2165    }
 2166
 2167    pub fn set_inline_completions_hidden_for_vim_mode(
 2168        &mut self,
 2169        hidden: bool,
 2170        window: &mut Window,
 2171        cx: &mut Context<Self>,
 2172    ) {
 2173        if hidden != self.inline_completions_hidden_for_vim_mode {
 2174            self.inline_completions_hidden_for_vim_mode = hidden;
 2175            if hidden {
 2176                self.update_visible_inline_completion(window, cx);
 2177            } else {
 2178                self.refresh_inline_completion(true, false, window, cx);
 2179            }
 2180        }
 2181    }
 2182
 2183    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2184        self.menu_inline_completions_policy = value;
 2185    }
 2186
 2187    pub fn set_autoindent(&mut self, autoindent: bool) {
 2188        if autoindent {
 2189            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2190        } else {
 2191            self.autoindent_mode = None;
 2192        }
 2193    }
 2194
 2195    pub fn read_only(&self, cx: &App) -> bool {
 2196        self.read_only || self.buffer.read(cx).read_only()
 2197    }
 2198
 2199    pub fn set_read_only(&mut self, read_only: bool) {
 2200        self.read_only = read_only;
 2201    }
 2202
 2203    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2204        self.use_autoclose = autoclose;
 2205    }
 2206
 2207    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2208        self.use_auto_surround = auto_surround;
 2209    }
 2210
 2211    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2212        self.auto_replace_emoji_shortcode = auto_replace;
 2213    }
 2214
 2215    pub fn toggle_edit_predictions(
 2216        &mut self,
 2217        _: &ToggleEditPrediction,
 2218        window: &mut Window,
 2219        cx: &mut Context<Self>,
 2220    ) {
 2221        if self.show_inline_completions_override.is_some() {
 2222            self.set_show_edit_predictions(None, window, cx);
 2223        } else {
 2224            let show_edit_predictions = !self.edit_predictions_enabled();
 2225            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2226        }
 2227    }
 2228
 2229    pub fn set_show_edit_predictions(
 2230        &mut self,
 2231        show_edit_predictions: Option<bool>,
 2232        window: &mut Window,
 2233        cx: &mut Context<Self>,
 2234    ) {
 2235        self.show_inline_completions_override = show_edit_predictions;
 2236        self.update_edit_prediction_settings(cx);
 2237
 2238        if let Some(false) = show_edit_predictions {
 2239            self.discard_inline_completion(false, cx);
 2240        } else {
 2241            self.refresh_inline_completion(false, true, window, cx);
 2242        }
 2243    }
 2244
 2245    fn inline_completions_disabled_in_scope(
 2246        &self,
 2247        buffer: &Entity<Buffer>,
 2248        buffer_position: language::Anchor,
 2249        cx: &App,
 2250    ) -> bool {
 2251        let snapshot = buffer.read(cx).snapshot();
 2252        let settings = snapshot.settings_at(buffer_position, cx);
 2253
 2254        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2255            return false;
 2256        };
 2257
 2258        scope.override_name().map_or(false, |scope_name| {
 2259            settings
 2260                .edit_predictions_disabled_in
 2261                .iter()
 2262                .any(|s| s == scope_name)
 2263        })
 2264    }
 2265
 2266    pub fn set_use_modal_editing(&mut self, to: bool) {
 2267        self.use_modal_editing = to;
 2268    }
 2269
 2270    pub fn use_modal_editing(&self) -> bool {
 2271        self.use_modal_editing
 2272    }
 2273
 2274    fn selections_did_change(
 2275        &mut self,
 2276        local: bool,
 2277        old_cursor_position: &Anchor,
 2278        show_completions: bool,
 2279        window: &mut Window,
 2280        cx: &mut Context<Self>,
 2281    ) {
 2282        window.invalidate_character_coordinates();
 2283
 2284        // Copy selections to primary selection buffer
 2285        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2286        if local {
 2287            let selections = self.selections.all::<usize>(cx);
 2288            let buffer_handle = self.buffer.read(cx).read(cx);
 2289
 2290            let mut text = String::new();
 2291            for (index, selection) in selections.iter().enumerate() {
 2292                let text_for_selection = buffer_handle
 2293                    .text_for_range(selection.start..selection.end)
 2294                    .collect::<String>();
 2295
 2296                text.push_str(&text_for_selection);
 2297                if index != selections.len() - 1 {
 2298                    text.push('\n');
 2299                }
 2300            }
 2301
 2302            if !text.is_empty() {
 2303                cx.write_to_primary(ClipboardItem::new_string(text));
 2304            }
 2305        }
 2306
 2307        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2308            self.buffer.update(cx, |buffer, cx| {
 2309                buffer.set_active_selections(
 2310                    &self.selections.disjoint_anchors(),
 2311                    self.selections.line_mode,
 2312                    self.cursor_shape,
 2313                    cx,
 2314                )
 2315            });
 2316        }
 2317        let display_map = self
 2318            .display_map
 2319            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2320        let buffer = &display_map.buffer_snapshot;
 2321        self.add_selections_state = None;
 2322        self.select_next_state = None;
 2323        self.select_prev_state = None;
 2324        self.select_syntax_node_history.try_clear();
 2325        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2326        self.snippet_stack
 2327            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2328        self.take_rename(false, window, cx);
 2329
 2330        let new_cursor_position = self.selections.newest_anchor().head();
 2331
 2332        self.push_to_nav_history(
 2333            *old_cursor_position,
 2334            Some(new_cursor_position.to_point(buffer)),
 2335            false,
 2336            cx,
 2337        );
 2338
 2339        if local {
 2340            let new_cursor_position = self.selections.newest_anchor().head();
 2341            let mut context_menu = self.context_menu.borrow_mut();
 2342            let completion_menu = match context_menu.as_ref() {
 2343                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2344                _ => {
 2345                    *context_menu = None;
 2346                    None
 2347                }
 2348            };
 2349            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2350                if !self.registered_buffers.contains_key(&buffer_id) {
 2351                    if let Some(project) = self.project.as_ref() {
 2352                        project.update(cx, |project, cx| {
 2353                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2354                                return;
 2355                            };
 2356                            self.registered_buffers.insert(
 2357                                buffer_id,
 2358                                project.register_buffer_with_language_servers(&buffer, cx),
 2359                            );
 2360                        })
 2361                    }
 2362                }
 2363            }
 2364
 2365            if let Some(completion_menu) = completion_menu {
 2366                let cursor_position = new_cursor_position.to_offset(buffer);
 2367                let (word_range, kind) =
 2368                    buffer.surrounding_word(completion_menu.initial_position, true);
 2369                if kind == Some(CharKind::Word)
 2370                    && word_range.to_inclusive().contains(&cursor_position)
 2371                {
 2372                    let mut completion_menu = completion_menu.clone();
 2373                    drop(context_menu);
 2374
 2375                    let query = Self::completion_query(buffer, cursor_position);
 2376                    cx.spawn(async move |this, cx| {
 2377                        completion_menu
 2378                            .filter(query.as_deref(), cx.background_executor().clone())
 2379                            .await;
 2380
 2381                        this.update(cx, |this, cx| {
 2382                            let mut context_menu = this.context_menu.borrow_mut();
 2383                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2384                            else {
 2385                                return;
 2386                            };
 2387
 2388                            if menu.id > completion_menu.id {
 2389                                return;
 2390                            }
 2391
 2392                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2393                            drop(context_menu);
 2394                            cx.notify();
 2395                        })
 2396                    })
 2397                    .detach();
 2398
 2399                    if show_completions {
 2400                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2401                    }
 2402                } else {
 2403                    drop(context_menu);
 2404                    self.hide_context_menu(window, cx);
 2405                }
 2406            } else {
 2407                drop(context_menu);
 2408            }
 2409
 2410            hide_hover(self, cx);
 2411
 2412            if old_cursor_position.to_display_point(&display_map).row()
 2413                != new_cursor_position.to_display_point(&display_map).row()
 2414            {
 2415                self.available_code_actions.take();
 2416            }
 2417            self.refresh_code_actions(window, cx);
 2418            self.refresh_document_highlights(cx);
 2419            self.refresh_selected_text_highlights(window, cx);
 2420            refresh_matching_bracket_highlights(self, window, cx);
 2421            self.update_visible_inline_completion(window, cx);
 2422            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2423            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2424            if self.git_blame_inline_enabled {
 2425                self.start_inline_blame_timer(window, cx);
 2426            }
 2427        }
 2428
 2429        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2430        cx.emit(EditorEvent::SelectionsChanged { local });
 2431
 2432        let selections = &self.selections.disjoint;
 2433        if selections.len() == 1 {
 2434            cx.emit(SearchEvent::ActiveMatchChanged)
 2435        }
 2436        if local {
 2437            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2438                let inmemory_selections = selections
 2439                    .iter()
 2440                    .map(|s| {
 2441                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2442                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2443                    })
 2444                    .collect();
 2445                self.update_restoration_data(cx, |data| {
 2446                    data.selections = inmemory_selections;
 2447                });
 2448
 2449                if WorkspaceSettings::get(None, cx).restore_on_startup
 2450                    != RestoreOnStartupBehavior::None
 2451                {
 2452                    if let Some(workspace_id) =
 2453                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2454                    {
 2455                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2456                        let selections = selections.clone();
 2457                        let background_executor = cx.background_executor().clone();
 2458                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2459                        self.serialize_selections = cx.background_spawn(async move {
 2460                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2461                    let db_selections = selections
 2462                        .iter()
 2463                        .map(|selection| {
 2464                            (
 2465                                selection.start.to_offset(&snapshot),
 2466                                selection.end.to_offset(&snapshot),
 2467                            )
 2468                        })
 2469                        .collect();
 2470
 2471                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2472                        .await
 2473                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2474                        .log_err();
 2475                });
 2476                    }
 2477                }
 2478            }
 2479        }
 2480
 2481        cx.notify();
 2482    }
 2483
 2484    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2485        use text::ToOffset as _;
 2486        use text::ToPoint as _;
 2487
 2488        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2489            return;
 2490        }
 2491
 2492        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2493            return;
 2494        };
 2495
 2496        let snapshot = singleton.read(cx).snapshot();
 2497        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2498            let display_snapshot = display_map.snapshot(cx);
 2499
 2500            display_snapshot
 2501                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2502                .map(|fold| {
 2503                    fold.range.start.text_anchor.to_point(&snapshot)
 2504                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2505                })
 2506                .collect()
 2507        });
 2508        self.update_restoration_data(cx, |data| {
 2509            data.folds = inmemory_folds;
 2510        });
 2511
 2512        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2513            return;
 2514        };
 2515        let background_executor = cx.background_executor().clone();
 2516        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2517        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2518            display_map
 2519                .snapshot(cx)
 2520                .folds_in_range(0..snapshot.len())
 2521                .map(|fold| {
 2522                    (
 2523                        fold.range.start.text_anchor.to_offset(&snapshot),
 2524                        fold.range.end.text_anchor.to_offset(&snapshot),
 2525                    )
 2526                })
 2527                .collect()
 2528        });
 2529        self.serialize_folds = cx.background_spawn(async move {
 2530            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2531            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2532                .await
 2533                .with_context(|| {
 2534                    format!(
 2535                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2536                    )
 2537                })
 2538                .log_err();
 2539        });
 2540    }
 2541
 2542    pub fn sync_selections(
 2543        &mut self,
 2544        other: Entity<Editor>,
 2545        cx: &mut Context<Self>,
 2546    ) -> gpui::Subscription {
 2547        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2548        self.selections.change_with(cx, |selections| {
 2549            selections.select_anchors(other_selections);
 2550        });
 2551
 2552        let other_subscription =
 2553            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2554                EditorEvent::SelectionsChanged { local: true } => {
 2555                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2556                    if other_selections.is_empty() {
 2557                        return;
 2558                    }
 2559                    this.selections.change_with(cx, |selections| {
 2560                        selections.select_anchors(other_selections);
 2561                    });
 2562                }
 2563                _ => {}
 2564            });
 2565
 2566        let this_subscription =
 2567            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2568                EditorEvent::SelectionsChanged { local: true } => {
 2569                    let these_selections = this.selections.disjoint.to_vec();
 2570                    if these_selections.is_empty() {
 2571                        return;
 2572                    }
 2573                    other.update(cx, |other_editor, cx| {
 2574                        other_editor.selections.change_with(cx, |selections| {
 2575                            selections.select_anchors(these_selections);
 2576                        })
 2577                    });
 2578                }
 2579                _ => {}
 2580            });
 2581
 2582        Subscription::join(other_subscription, this_subscription)
 2583    }
 2584
 2585    pub fn change_selections<R>(
 2586        &mut self,
 2587        autoscroll: Option<Autoscroll>,
 2588        window: &mut Window,
 2589        cx: &mut Context<Self>,
 2590        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2591    ) -> R {
 2592        self.change_selections_inner(autoscroll, true, window, cx, change)
 2593    }
 2594
 2595    fn change_selections_inner<R>(
 2596        &mut self,
 2597        autoscroll: Option<Autoscroll>,
 2598        request_completions: bool,
 2599        window: &mut Window,
 2600        cx: &mut Context<Self>,
 2601        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2602    ) -> R {
 2603        let old_cursor_position = self.selections.newest_anchor().head();
 2604        self.push_to_selection_history();
 2605
 2606        let (changed, result) = self.selections.change_with(cx, change);
 2607
 2608        if changed {
 2609            if let Some(autoscroll) = autoscroll {
 2610                self.request_autoscroll(autoscroll, cx);
 2611            }
 2612            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2613
 2614            if self.should_open_signature_help_automatically(
 2615                &old_cursor_position,
 2616                self.signature_help_state.backspace_pressed(),
 2617                cx,
 2618            ) {
 2619                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2620            }
 2621            self.signature_help_state.set_backspace_pressed(false);
 2622        }
 2623
 2624        result
 2625    }
 2626
 2627    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2628    where
 2629        I: IntoIterator<Item = (Range<S>, T)>,
 2630        S: ToOffset,
 2631        T: Into<Arc<str>>,
 2632    {
 2633        if self.read_only(cx) {
 2634            return;
 2635        }
 2636
 2637        self.buffer
 2638            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2639    }
 2640
 2641    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2642    where
 2643        I: IntoIterator<Item = (Range<S>, T)>,
 2644        S: ToOffset,
 2645        T: Into<Arc<str>>,
 2646    {
 2647        if self.read_only(cx) {
 2648            return;
 2649        }
 2650
 2651        self.buffer.update(cx, |buffer, cx| {
 2652            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2653        });
 2654    }
 2655
 2656    pub fn edit_with_block_indent<I, S, T>(
 2657        &mut self,
 2658        edits: I,
 2659        original_indent_columns: Vec<Option<u32>>,
 2660        cx: &mut Context<Self>,
 2661    ) where
 2662        I: IntoIterator<Item = (Range<S>, T)>,
 2663        S: ToOffset,
 2664        T: Into<Arc<str>>,
 2665    {
 2666        if self.read_only(cx) {
 2667            return;
 2668        }
 2669
 2670        self.buffer.update(cx, |buffer, cx| {
 2671            buffer.edit(
 2672                edits,
 2673                Some(AutoindentMode::Block {
 2674                    original_indent_columns,
 2675                }),
 2676                cx,
 2677            )
 2678        });
 2679    }
 2680
 2681    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2682        self.hide_context_menu(window, cx);
 2683
 2684        match phase {
 2685            SelectPhase::Begin {
 2686                position,
 2687                add,
 2688                click_count,
 2689            } => self.begin_selection(position, add, click_count, window, cx),
 2690            SelectPhase::BeginColumnar {
 2691                position,
 2692                goal_column,
 2693                reset,
 2694            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2695            SelectPhase::Extend {
 2696                position,
 2697                click_count,
 2698            } => self.extend_selection(position, click_count, window, cx),
 2699            SelectPhase::Update {
 2700                position,
 2701                goal_column,
 2702                scroll_delta,
 2703            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2704            SelectPhase::End => self.end_selection(window, cx),
 2705        }
 2706    }
 2707
 2708    fn extend_selection(
 2709        &mut self,
 2710        position: DisplayPoint,
 2711        click_count: usize,
 2712        window: &mut Window,
 2713        cx: &mut Context<Self>,
 2714    ) {
 2715        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2716        let tail = self.selections.newest::<usize>(cx).tail();
 2717        self.begin_selection(position, false, click_count, window, cx);
 2718
 2719        let position = position.to_offset(&display_map, Bias::Left);
 2720        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2721
 2722        let mut pending_selection = self
 2723            .selections
 2724            .pending_anchor()
 2725            .expect("extend_selection not called with pending selection");
 2726        if position >= tail {
 2727            pending_selection.start = tail_anchor;
 2728        } else {
 2729            pending_selection.end = tail_anchor;
 2730            pending_selection.reversed = true;
 2731        }
 2732
 2733        let mut pending_mode = self.selections.pending_mode().unwrap();
 2734        match &mut pending_mode {
 2735            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2736            _ => {}
 2737        }
 2738
 2739        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2740            s.set_pending(pending_selection, pending_mode)
 2741        });
 2742    }
 2743
 2744    fn begin_selection(
 2745        &mut self,
 2746        position: DisplayPoint,
 2747        add: bool,
 2748        click_count: usize,
 2749        window: &mut Window,
 2750        cx: &mut Context<Self>,
 2751    ) {
 2752        if !self.focus_handle.is_focused(window) {
 2753            self.last_focused_descendant = None;
 2754            window.focus(&self.focus_handle);
 2755        }
 2756
 2757        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2758        let buffer = &display_map.buffer_snapshot;
 2759        let newest_selection = self.selections.newest_anchor().clone();
 2760        let position = display_map.clip_point(position, Bias::Left);
 2761
 2762        let start;
 2763        let end;
 2764        let mode;
 2765        let mut auto_scroll;
 2766        match click_count {
 2767            1 => {
 2768                start = buffer.anchor_before(position.to_point(&display_map));
 2769                end = start;
 2770                mode = SelectMode::Character;
 2771                auto_scroll = true;
 2772            }
 2773            2 => {
 2774                let range = movement::surrounding_word(&display_map, position);
 2775                start = buffer.anchor_before(range.start.to_point(&display_map));
 2776                end = buffer.anchor_before(range.end.to_point(&display_map));
 2777                mode = SelectMode::Word(start..end);
 2778                auto_scroll = true;
 2779            }
 2780            3 => {
 2781                let position = display_map
 2782                    .clip_point(position, Bias::Left)
 2783                    .to_point(&display_map);
 2784                let line_start = display_map.prev_line_boundary(position).0;
 2785                let next_line_start = buffer.clip_point(
 2786                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2787                    Bias::Left,
 2788                );
 2789                start = buffer.anchor_before(line_start);
 2790                end = buffer.anchor_before(next_line_start);
 2791                mode = SelectMode::Line(start..end);
 2792                auto_scroll = true;
 2793            }
 2794            _ => {
 2795                start = buffer.anchor_before(0);
 2796                end = buffer.anchor_before(buffer.len());
 2797                mode = SelectMode::All;
 2798                auto_scroll = false;
 2799            }
 2800        }
 2801        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2802
 2803        let point_to_delete: Option<usize> = {
 2804            let selected_points: Vec<Selection<Point>> =
 2805                self.selections.disjoint_in_range(start..end, cx);
 2806
 2807            if !add || click_count > 1 {
 2808                None
 2809            } else if !selected_points.is_empty() {
 2810                Some(selected_points[0].id)
 2811            } else {
 2812                let clicked_point_already_selected =
 2813                    self.selections.disjoint.iter().find(|selection| {
 2814                        selection.start.to_point(buffer) == start.to_point(buffer)
 2815                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2816                    });
 2817
 2818                clicked_point_already_selected.map(|selection| selection.id)
 2819            }
 2820        };
 2821
 2822        let selections_count = self.selections.count();
 2823
 2824        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2825            if let Some(point_to_delete) = point_to_delete {
 2826                s.delete(point_to_delete);
 2827
 2828                if selections_count == 1 {
 2829                    s.set_pending_anchor_range(start..end, mode);
 2830                }
 2831            } else {
 2832                if !add {
 2833                    s.clear_disjoint();
 2834                } else if click_count > 1 {
 2835                    s.delete(newest_selection.id)
 2836                }
 2837
 2838                s.set_pending_anchor_range(start..end, mode);
 2839            }
 2840        });
 2841    }
 2842
 2843    fn begin_columnar_selection(
 2844        &mut self,
 2845        position: DisplayPoint,
 2846        goal_column: u32,
 2847        reset: bool,
 2848        window: &mut Window,
 2849        cx: &mut Context<Self>,
 2850    ) {
 2851        if !self.focus_handle.is_focused(window) {
 2852            self.last_focused_descendant = None;
 2853            window.focus(&self.focus_handle);
 2854        }
 2855
 2856        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2857
 2858        if reset {
 2859            let pointer_position = display_map
 2860                .buffer_snapshot
 2861                .anchor_before(position.to_point(&display_map));
 2862
 2863            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2864                s.clear_disjoint();
 2865                s.set_pending_anchor_range(
 2866                    pointer_position..pointer_position,
 2867                    SelectMode::Character,
 2868                );
 2869            });
 2870        }
 2871
 2872        let tail = self.selections.newest::<Point>(cx).tail();
 2873        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2874
 2875        if !reset {
 2876            self.select_columns(
 2877                tail.to_display_point(&display_map),
 2878                position,
 2879                goal_column,
 2880                &display_map,
 2881                window,
 2882                cx,
 2883            );
 2884        }
 2885    }
 2886
 2887    fn update_selection(
 2888        &mut self,
 2889        position: DisplayPoint,
 2890        goal_column: u32,
 2891        scroll_delta: gpui::Point<f32>,
 2892        window: &mut Window,
 2893        cx: &mut Context<Self>,
 2894    ) {
 2895        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2896
 2897        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2898            let tail = tail.to_display_point(&display_map);
 2899            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2900        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2901            let buffer = self.buffer.read(cx).snapshot(cx);
 2902            let head;
 2903            let tail;
 2904            let mode = self.selections.pending_mode().unwrap();
 2905            match &mode {
 2906                SelectMode::Character => {
 2907                    head = position.to_point(&display_map);
 2908                    tail = pending.tail().to_point(&buffer);
 2909                }
 2910                SelectMode::Word(original_range) => {
 2911                    let original_display_range = original_range.start.to_display_point(&display_map)
 2912                        ..original_range.end.to_display_point(&display_map);
 2913                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2914                        ..original_display_range.end.to_point(&display_map);
 2915                    if movement::is_inside_word(&display_map, position)
 2916                        || original_display_range.contains(&position)
 2917                    {
 2918                        let word_range = movement::surrounding_word(&display_map, position);
 2919                        if word_range.start < original_display_range.start {
 2920                            head = word_range.start.to_point(&display_map);
 2921                        } else {
 2922                            head = word_range.end.to_point(&display_map);
 2923                        }
 2924                    } else {
 2925                        head = position.to_point(&display_map);
 2926                    }
 2927
 2928                    if head <= original_buffer_range.start {
 2929                        tail = original_buffer_range.end;
 2930                    } else {
 2931                        tail = original_buffer_range.start;
 2932                    }
 2933                }
 2934                SelectMode::Line(original_range) => {
 2935                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2936
 2937                    let position = display_map
 2938                        .clip_point(position, Bias::Left)
 2939                        .to_point(&display_map);
 2940                    let line_start = display_map.prev_line_boundary(position).0;
 2941                    let next_line_start = buffer.clip_point(
 2942                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2943                        Bias::Left,
 2944                    );
 2945
 2946                    if line_start < original_range.start {
 2947                        head = line_start
 2948                    } else {
 2949                        head = next_line_start
 2950                    }
 2951
 2952                    if head <= original_range.start {
 2953                        tail = original_range.end;
 2954                    } else {
 2955                        tail = original_range.start;
 2956                    }
 2957                }
 2958                SelectMode::All => {
 2959                    return;
 2960                }
 2961            };
 2962
 2963            if head < tail {
 2964                pending.start = buffer.anchor_before(head);
 2965                pending.end = buffer.anchor_before(tail);
 2966                pending.reversed = true;
 2967            } else {
 2968                pending.start = buffer.anchor_before(tail);
 2969                pending.end = buffer.anchor_before(head);
 2970                pending.reversed = false;
 2971            }
 2972
 2973            self.change_selections(None, window, cx, |s| {
 2974                s.set_pending(pending, mode);
 2975            });
 2976        } else {
 2977            log::error!("update_selection dispatched with no pending selection");
 2978            return;
 2979        }
 2980
 2981        self.apply_scroll_delta(scroll_delta, window, cx);
 2982        cx.notify();
 2983    }
 2984
 2985    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2986        self.columnar_selection_tail.take();
 2987        if self.selections.pending_anchor().is_some() {
 2988            let selections = self.selections.all::<usize>(cx);
 2989            self.change_selections(None, window, cx, |s| {
 2990                s.select(selections);
 2991                s.clear_pending();
 2992            });
 2993        }
 2994    }
 2995
 2996    fn select_columns(
 2997        &mut self,
 2998        tail: DisplayPoint,
 2999        head: DisplayPoint,
 3000        goal_column: u32,
 3001        display_map: &DisplaySnapshot,
 3002        window: &mut Window,
 3003        cx: &mut Context<Self>,
 3004    ) {
 3005        let start_row = cmp::min(tail.row(), head.row());
 3006        let end_row = cmp::max(tail.row(), head.row());
 3007        let start_column = cmp::min(tail.column(), goal_column);
 3008        let end_column = cmp::max(tail.column(), goal_column);
 3009        let reversed = start_column < tail.column();
 3010
 3011        let selection_ranges = (start_row.0..=end_row.0)
 3012            .map(DisplayRow)
 3013            .filter_map(|row| {
 3014                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3015                    let start = display_map
 3016                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3017                        .to_point(display_map);
 3018                    let end = display_map
 3019                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3020                        .to_point(display_map);
 3021                    if reversed {
 3022                        Some(end..start)
 3023                    } else {
 3024                        Some(start..end)
 3025                    }
 3026                } else {
 3027                    None
 3028                }
 3029            })
 3030            .collect::<Vec<_>>();
 3031
 3032        self.change_selections(None, window, cx, |s| {
 3033            s.select_ranges(selection_ranges);
 3034        });
 3035        cx.notify();
 3036    }
 3037
 3038    pub fn has_pending_nonempty_selection(&self) -> bool {
 3039        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3040            Some(Selection { start, end, .. }) => start != end,
 3041            None => false,
 3042        };
 3043
 3044        pending_nonempty_selection
 3045            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3046    }
 3047
 3048    pub fn has_pending_selection(&self) -> bool {
 3049        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3050    }
 3051
 3052    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3053        self.selection_mark_mode = false;
 3054
 3055        if self.clear_expanded_diff_hunks(cx) {
 3056            cx.notify();
 3057            return;
 3058        }
 3059        if self.dismiss_menus_and_popups(true, window, cx) {
 3060            return;
 3061        }
 3062
 3063        if self.mode.is_full()
 3064            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3065        {
 3066            return;
 3067        }
 3068
 3069        cx.propagate();
 3070    }
 3071
 3072    pub fn dismiss_menus_and_popups(
 3073        &mut self,
 3074        is_user_requested: bool,
 3075        window: &mut Window,
 3076        cx: &mut Context<Self>,
 3077    ) -> bool {
 3078        if self.take_rename(false, window, cx).is_some() {
 3079            return true;
 3080        }
 3081
 3082        if hide_hover(self, cx) {
 3083            return true;
 3084        }
 3085
 3086        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3087            return true;
 3088        }
 3089
 3090        if self.hide_context_menu(window, cx).is_some() {
 3091            return true;
 3092        }
 3093
 3094        if self.mouse_context_menu.take().is_some() {
 3095            return true;
 3096        }
 3097
 3098        if is_user_requested && self.discard_inline_completion(true, cx) {
 3099            return true;
 3100        }
 3101
 3102        if self.snippet_stack.pop().is_some() {
 3103            return true;
 3104        }
 3105
 3106        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3107            self.dismiss_diagnostics(cx);
 3108            return true;
 3109        }
 3110
 3111        false
 3112    }
 3113
 3114    fn linked_editing_ranges_for(
 3115        &self,
 3116        selection: Range<text::Anchor>,
 3117        cx: &App,
 3118    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3119        if self.linked_edit_ranges.is_empty() {
 3120            return None;
 3121        }
 3122        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3123            selection.end.buffer_id.and_then(|end_buffer_id| {
 3124                if selection.start.buffer_id != Some(end_buffer_id) {
 3125                    return None;
 3126                }
 3127                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3128                let snapshot = buffer.read(cx).snapshot();
 3129                self.linked_edit_ranges
 3130                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3131                    .map(|ranges| (ranges, snapshot, buffer))
 3132            })?;
 3133        use text::ToOffset as TO;
 3134        // find offset from the start of current range to current cursor position
 3135        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3136
 3137        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3138        let start_difference = start_offset - start_byte_offset;
 3139        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3140        let end_difference = end_offset - start_byte_offset;
 3141        // Current range has associated linked ranges.
 3142        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3143        for range in linked_ranges.iter() {
 3144            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3145            let end_offset = start_offset + end_difference;
 3146            let start_offset = start_offset + start_difference;
 3147            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3148                continue;
 3149            }
 3150            if self.selections.disjoint_anchor_ranges().any(|s| {
 3151                if s.start.buffer_id != selection.start.buffer_id
 3152                    || s.end.buffer_id != selection.end.buffer_id
 3153                {
 3154                    return false;
 3155                }
 3156                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3157                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3158            }) {
 3159                continue;
 3160            }
 3161            let start = buffer_snapshot.anchor_after(start_offset);
 3162            let end = buffer_snapshot.anchor_after(end_offset);
 3163            linked_edits
 3164                .entry(buffer.clone())
 3165                .or_default()
 3166                .push(start..end);
 3167        }
 3168        Some(linked_edits)
 3169    }
 3170
 3171    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3172        let text: Arc<str> = text.into();
 3173
 3174        if self.read_only(cx) {
 3175            return;
 3176        }
 3177
 3178        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3179
 3180        let selections = self.selections.all_adjusted(cx);
 3181        let mut bracket_inserted = false;
 3182        let mut edits = Vec::new();
 3183        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3184        let mut new_selections = Vec::with_capacity(selections.len());
 3185        let mut new_autoclose_regions = Vec::new();
 3186        let snapshot = self.buffer.read(cx).read(cx);
 3187        let mut clear_linked_edit_ranges = false;
 3188
 3189        for (selection, autoclose_region) in
 3190            self.selections_with_autoclose_regions(selections, &snapshot)
 3191        {
 3192            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3193                // Determine if the inserted text matches the opening or closing
 3194                // bracket of any of this language's bracket pairs.
 3195                let mut bracket_pair = None;
 3196                let mut is_bracket_pair_start = false;
 3197                let mut is_bracket_pair_end = false;
 3198                if !text.is_empty() {
 3199                    let mut bracket_pair_matching_end = None;
 3200                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3201                    //  and they are removing the character that triggered IME popup.
 3202                    for (pair, enabled) in scope.brackets() {
 3203                        if !pair.close && !pair.surround {
 3204                            continue;
 3205                        }
 3206
 3207                        if enabled && pair.start.ends_with(text.as_ref()) {
 3208                            let prefix_len = pair.start.len() - text.len();
 3209                            let preceding_text_matches_prefix = prefix_len == 0
 3210                                || (selection.start.column >= (prefix_len as u32)
 3211                                    && snapshot.contains_str_at(
 3212                                        Point::new(
 3213                                            selection.start.row,
 3214                                            selection.start.column - (prefix_len as u32),
 3215                                        ),
 3216                                        &pair.start[..prefix_len],
 3217                                    ));
 3218                            if preceding_text_matches_prefix {
 3219                                bracket_pair = Some(pair.clone());
 3220                                is_bracket_pair_start = true;
 3221                                break;
 3222                            }
 3223                        }
 3224                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3225                        {
 3226                            // take first bracket pair matching end, but don't break in case a later bracket
 3227                            // pair matches start
 3228                            bracket_pair_matching_end = Some(pair.clone());
 3229                        }
 3230                    }
 3231                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3232                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3233                        is_bracket_pair_end = true;
 3234                    }
 3235                }
 3236
 3237                if let Some(bracket_pair) = bracket_pair {
 3238                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3239                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3240                    let auto_surround =
 3241                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3242                    if selection.is_empty() {
 3243                        if is_bracket_pair_start {
 3244                            // If the inserted text is a suffix of an opening bracket and the
 3245                            // selection is preceded by the rest of the opening bracket, then
 3246                            // insert the closing bracket.
 3247                            let following_text_allows_autoclose = snapshot
 3248                                .chars_at(selection.start)
 3249                                .next()
 3250                                .map_or(true, |c| scope.should_autoclose_before(c));
 3251
 3252                            let preceding_text_allows_autoclose = selection.start.column == 0
 3253                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3254                                    true,
 3255                                    |c| {
 3256                                        bracket_pair.start != bracket_pair.end
 3257                                            || !snapshot
 3258                                                .char_classifier_at(selection.start)
 3259                                                .is_word(c)
 3260                                    },
 3261                                );
 3262
 3263                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3264                                && bracket_pair.start.len() == 1
 3265                            {
 3266                                let target = bracket_pair.start.chars().next().unwrap();
 3267                                let current_line_count = snapshot
 3268                                    .reversed_chars_at(selection.start)
 3269                                    .take_while(|&c| c != '\n')
 3270                                    .filter(|&c| c == target)
 3271                                    .count();
 3272                                current_line_count % 2 == 1
 3273                            } else {
 3274                                false
 3275                            };
 3276
 3277                            if autoclose
 3278                                && bracket_pair.close
 3279                                && following_text_allows_autoclose
 3280                                && preceding_text_allows_autoclose
 3281                                && !is_closing_quote
 3282                            {
 3283                                let anchor = snapshot.anchor_before(selection.end);
 3284                                new_selections.push((selection.map(|_| anchor), text.len()));
 3285                                new_autoclose_regions.push((
 3286                                    anchor,
 3287                                    text.len(),
 3288                                    selection.id,
 3289                                    bracket_pair.clone(),
 3290                                ));
 3291                                edits.push((
 3292                                    selection.range(),
 3293                                    format!("{}{}", text, bracket_pair.end).into(),
 3294                                ));
 3295                                bracket_inserted = true;
 3296                                continue;
 3297                            }
 3298                        }
 3299
 3300                        if let Some(region) = autoclose_region {
 3301                            // If the selection is followed by an auto-inserted closing bracket,
 3302                            // then don't insert that closing bracket again; just move the selection
 3303                            // past the closing bracket.
 3304                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3305                                && text.as_ref() == region.pair.end.as_str();
 3306                            if should_skip {
 3307                                let anchor = snapshot.anchor_after(selection.end);
 3308                                new_selections
 3309                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3310                                continue;
 3311                            }
 3312                        }
 3313
 3314                        let always_treat_brackets_as_autoclosed = snapshot
 3315                            .language_settings_at(selection.start, cx)
 3316                            .always_treat_brackets_as_autoclosed;
 3317                        if always_treat_brackets_as_autoclosed
 3318                            && is_bracket_pair_end
 3319                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3320                        {
 3321                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3322                            // and the inserted text is a closing bracket and the selection is followed
 3323                            // by the closing bracket then move the selection past the closing bracket.
 3324                            let anchor = snapshot.anchor_after(selection.end);
 3325                            new_selections.push((selection.map(|_| anchor), text.len()));
 3326                            continue;
 3327                        }
 3328                    }
 3329                    // If an opening bracket is 1 character long and is typed while
 3330                    // text is selected, then surround that text with the bracket pair.
 3331                    else if auto_surround
 3332                        && bracket_pair.surround
 3333                        && is_bracket_pair_start
 3334                        && bracket_pair.start.chars().count() == 1
 3335                    {
 3336                        edits.push((selection.start..selection.start, text.clone()));
 3337                        edits.push((
 3338                            selection.end..selection.end,
 3339                            bracket_pair.end.as_str().into(),
 3340                        ));
 3341                        bracket_inserted = true;
 3342                        new_selections.push((
 3343                            Selection {
 3344                                id: selection.id,
 3345                                start: snapshot.anchor_after(selection.start),
 3346                                end: snapshot.anchor_before(selection.end),
 3347                                reversed: selection.reversed,
 3348                                goal: selection.goal,
 3349                            },
 3350                            0,
 3351                        ));
 3352                        continue;
 3353                    }
 3354                }
 3355            }
 3356
 3357            if self.auto_replace_emoji_shortcode
 3358                && selection.is_empty()
 3359                && text.as_ref().ends_with(':')
 3360            {
 3361                if let Some(possible_emoji_short_code) =
 3362                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3363                {
 3364                    if !possible_emoji_short_code.is_empty() {
 3365                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3366                            let emoji_shortcode_start = Point::new(
 3367                                selection.start.row,
 3368                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3369                            );
 3370
 3371                            // Remove shortcode from buffer
 3372                            edits.push((
 3373                                emoji_shortcode_start..selection.start,
 3374                                "".to_string().into(),
 3375                            ));
 3376                            new_selections.push((
 3377                                Selection {
 3378                                    id: selection.id,
 3379                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3380                                    end: snapshot.anchor_before(selection.start),
 3381                                    reversed: selection.reversed,
 3382                                    goal: selection.goal,
 3383                                },
 3384                                0,
 3385                            ));
 3386
 3387                            // Insert emoji
 3388                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3389                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3390                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3391
 3392                            continue;
 3393                        }
 3394                    }
 3395                }
 3396            }
 3397
 3398            // If not handling any auto-close operation, then just replace the selected
 3399            // text with the given input and move the selection to the end of the
 3400            // newly inserted text.
 3401            let anchor = snapshot.anchor_after(selection.end);
 3402            if !self.linked_edit_ranges.is_empty() {
 3403                let start_anchor = snapshot.anchor_before(selection.start);
 3404
 3405                let is_word_char = text.chars().next().map_or(true, |char| {
 3406                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3407                    classifier.is_word(char)
 3408                });
 3409
 3410                if is_word_char {
 3411                    if let Some(ranges) = self
 3412                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3413                    {
 3414                        for (buffer, edits) in ranges {
 3415                            linked_edits
 3416                                .entry(buffer.clone())
 3417                                .or_default()
 3418                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3419                        }
 3420                    }
 3421                } else {
 3422                    clear_linked_edit_ranges = true;
 3423                }
 3424            }
 3425
 3426            new_selections.push((selection.map(|_| anchor), 0));
 3427            edits.push((selection.start..selection.end, text.clone()));
 3428        }
 3429
 3430        drop(snapshot);
 3431
 3432        self.transact(window, cx, |this, window, cx| {
 3433            if clear_linked_edit_ranges {
 3434                this.linked_edit_ranges.clear();
 3435            }
 3436            let initial_buffer_versions =
 3437                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3438
 3439            this.buffer.update(cx, |buffer, cx| {
 3440                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3441            });
 3442            for (buffer, edits) in linked_edits {
 3443                buffer.update(cx, |buffer, cx| {
 3444                    let snapshot = buffer.snapshot();
 3445                    let edits = edits
 3446                        .into_iter()
 3447                        .map(|(range, text)| {
 3448                            use text::ToPoint as TP;
 3449                            let end_point = TP::to_point(&range.end, &snapshot);
 3450                            let start_point = TP::to_point(&range.start, &snapshot);
 3451                            (start_point..end_point, text)
 3452                        })
 3453                        .sorted_by_key(|(range, _)| range.start);
 3454                    buffer.edit(edits, None, cx);
 3455                })
 3456            }
 3457            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3458            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3459            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3460            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3461                .zip(new_selection_deltas)
 3462                .map(|(selection, delta)| Selection {
 3463                    id: selection.id,
 3464                    start: selection.start + delta,
 3465                    end: selection.end + delta,
 3466                    reversed: selection.reversed,
 3467                    goal: SelectionGoal::None,
 3468                })
 3469                .collect::<Vec<_>>();
 3470
 3471            let mut i = 0;
 3472            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3473                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3474                let start = map.buffer_snapshot.anchor_before(position);
 3475                let end = map.buffer_snapshot.anchor_after(position);
 3476                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3477                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3478                        Ordering::Less => i += 1,
 3479                        Ordering::Greater => break,
 3480                        Ordering::Equal => {
 3481                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3482                                Ordering::Less => i += 1,
 3483                                Ordering::Equal => break,
 3484                                Ordering::Greater => break,
 3485                            }
 3486                        }
 3487                    }
 3488                }
 3489                this.autoclose_regions.insert(
 3490                    i,
 3491                    AutocloseRegion {
 3492                        selection_id,
 3493                        range: start..end,
 3494                        pair,
 3495                    },
 3496                );
 3497            }
 3498
 3499            let had_active_inline_completion = this.has_active_inline_completion();
 3500            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3501                s.select(new_selections)
 3502            });
 3503
 3504            if !bracket_inserted {
 3505                if let Some(on_type_format_task) =
 3506                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3507                {
 3508                    on_type_format_task.detach_and_log_err(cx);
 3509                }
 3510            }
 3511
 3512            let editor_settings = EditorSettings::get_global(cx);
 3513            if bracket_inserted
 3514                && (editor_settings.auto_signature_help
 3515                    || editor_settings.show_signature_help_after_edits)
 3516            {
 3517                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3518            }
 3519
 3520            let trigger_in_words =
 3521                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3522            if this.hard_wrap.is_some() {
 3523                let latest: Range<Point> = this.selections.newest(cx).range();
 3524                if latest.is_empty()
 3525                    && this
 3526                        .buffer()
 3527                        .read(cx)
 3528                        .snapshot(cx)
 3529                        .line_len(MultiBufferRow(latest.start.row))
 3530                        == latest.start.column
 3531                {
 3532                    this.rewrap_impl(
 3533                        RewrapOptions {
 3534                            override_language_settings: true,
 3535                            preserve_existing_whitespace: true,
 3536                        },
 3537                        cx,
 3538                    )
 3539                }
 3540            }
 3541            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3542            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3543            this.refresh_inline_completion(true, false, window, cx);
 3544            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3545        });
 3546    }
 3547
 3548    fn find_possible_emoji_shortcode_at_position(
 3549        snapshot: &MultiBufferSnapshot,
 3550        position: Point,
 3551    ) -> Option<String> {
 3552        let mut chars = Vec::new();
 3553        let mut found_colon = false;
 3554        for char in snapshot.reversed_chars_at(position).take(100) {
 3555            // Found a possible emoji shortcode in the middle of the buffer
 3556            if found_colon {
 3557                if char.is_whitespace() {
 3558                    chars.reverse();
 3559                    return Some(chars.iter().collect());
 3560                }
 3561                // If the previous character is not a whitespace, we are in the middle of a word
 3562                // and we only want to complete the shortcode if the word is made up of other emojis
 3563                let mut containing_word = String::new();
 3564                for ch in snapshot
 3565                    .reversed_chars_at(position)
 3566                    .skip(chars.len() + 1)
 3567                    .take(100)
 3568                {
 3569                    if ch.is_whitespace() {
 3570                        break;
 3571                    }
 3572                    containing_word.push(ch);
 3573                }
 3574                let containing_word = containing_word.chars().rev().collect::<String>();
 3575                if util::word_consists_of_emojis(containing_word.as_str()) {
 3576                    chars.reverse();
 3577                    return Some(chars.iter().collect());
 3578                }
 3579            }
 3580
 3581            if char.is_whitespace() || !char.is_ascii() {
 3582                return None;
 3583            }
 3584            if char == ':' {
 3585                found_colon = true;
 3586            } else {
 3587                chars.push(char);
 3588            }
 3589        }
 3590        // Found a possible emoji shortcode at the beginning of the buffer
 3591        chars.reverse();
 3592        Some(chars.iter().collect())
 3593    }
 3594
 3595    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3596        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3597        self.transact(window, cx, |this, window, cx| {
 3598            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3599                let selections = this.selections.all::<usize>(cx);
 3600                let multi_buffer = this.buffer.read(cx);
 3601                let buffer = multi_buffer.snapshot(cx);
 3602                selections
 3603                    .iter()
 3604                    .map(|selection| {
 3605                        let start_point = selection.start.to_point(&buffer);
 3606                        let mut indent =
 3607                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3608                        indent.len = cmp::min(indent.len, start_point.column);
 3609                        let start = selection.start;
 3610                        let end = selection.end;
 3611                        let selection_is_empty = start == end;
 3612                        let language_scope = buffer.language_scope_at(start);
 3613                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3614                            &language_scope
 3615                        {
 3616                            let insert_extra_newline =
 3617                                insert_extra_newline_brackets(&buffer, start..end, language)
 3618                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3619
 3620                            // Comment extension on newline is allowed only for cursor selections
 3621                            let comment_delimiter = maybe!({
 3622                                if !selection_is_empty {
 3623                                    return None;
 3624                                }
 3625
 3626                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3627                                    return None;
 3628                                }
 3629
 3630                                let delimiters = language.line_comment_prefixes();
 3631                                let max_len_of_delimiter =
 3632                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3633                                let (snapshot, range) =
 3634                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3635
 3636                                let mut index_of_first_non_whitespace = 0;
 3637                                let comment_candidate = snapshot
 3638                                    .chars_for_range(range)
 3639                                    .skip_while(|c| {
 3640                                        let should_skip = c.is_whitespace();
 3641                                        if should_skip {
 3642                                            index_of_first_non_whitespace += 1;
 3643                                        }
 3644                                        should_skip
 3645                                    })
 3646                                    .take(max_len_of_delimiter)
 3647                                    .collect::<String>();
 3648                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3649                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3650                                })?;
 3651                                let cursor_is_placed_after_comment_marker =
 3652                                    index_of_first_non_whitespace + comment_prefix.len()
 3653                                        <= start_point.column as usize;
 3654                                if cursor_is_placed_after_comment_marker {
 3655                                    Some(comment_prefix.clone())
 3656                                } else {
 3657                                    None
 3658                                }
 3659                            });
 3660                            (comment_delimiter, insert_extra_newline)
 3661                        } else {
 3662                            (None, false)
 3663                        };
 3664
 3665                        let capacity_for_delimiter = comment_delimiter
 3666                            .as_deref()
 3667                            .map(str::len)
 3668                            .unwrap_or_default();
 3669                        let mut new_text =
 3670                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3671                        new_text.push('\n');
 3672                        new_text.extend(indent.chars());
 3673                        if let Some(delimiter) = &comment_delimiter {
 3674                            new_text.push_str(delimiter);
 3675                        }
 3676                        if insert_extra_newline {
 3677                            new_text = new_text.repeat(2);
 3678                        }
 3679
 3680                        let anchor = buffer.anchor_after(end);
 3681                        let new_selection = selection.map(|_| anchor);
 3682                        (
 3683                            (start..end, new_text),
 3684                            (insert_extra_newline, new_selection),
 3685                        )
 3686                    })
 3687                    .unzip()
 3688            };
 3689
 3690            this.edit_with_autoindent(edits, cx);
 3691            let buffer = this.buffer.read(cx).snapshot(cx);
 3692            let new_selections = selection_fixup_info
 3693                .into_iter()
 3694                .map(|(extra_newline_inserted, new_selection)| {
 3695                    let mut cursor = new_selection.end.to_point(&buffer);
 3696                    if extra_newline_inserted {
 3697                        cursor.row -= 1;
 3698                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3699                    }
 3700                    new_selection.map(|_| cursor)
 3701                })
 3702                .collect();
 3703
 3704            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3705                s.select(new_selections)
 3706            });
 3707            this.refresh_inline_completion(true, false, window, cx);
 3708        });
 3709    }
 3710
 3711    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3712        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3713
 3714        let buffer = self.buffer.read(cx);
 3715        let snapshot = buffer.snapshot(cx);
 3716
 3717        let mut edits = Vec::new();
 3718        let mut rows = Vec::new();
 3719
 3720        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3721            let cursor = selection.head();
 3722            let row = cursor.row;
 3723
 3724            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3725
 3726            let newline = "\n".to_string();
 3727            edits.push((start_of_line..start_of_line, newline));
 3728
 3729            rows.push(row + rows_inserted as u32);
 3730        }
 3731
 3732        self.transact(window, cx, |editor, window, cx| {
 3733            editor.edit(edits, cx);
 3734
 3735            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3736                let mut index = 0;
 3737                s.move_cursors_with(|map, _, _| {
 3738                    let row = rows[index];
 3739                    index += 1;
 3740
 3741                    let point = Point::new(row, 0);
 3742                    let boundary = map.next_line_boundary(point).1;
 3743                    let clipped = map.clip_point(boundary, Bias::Left);
 3744
 3745                    (clipped, SelectionGoal::None)
 3746                });
 3747            });
 3748
 3749            let mut indent_edits = Vec::new();
 3750            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3751            for row in rows {
 3752                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3753                for (row, indent) in indents {
 3754                    if indent.len == 0 {
 3755                        continue;
 3756                    }
 3757
 3758                    let text = match indent.kind {
 3759                        IndentKind::Space => " ".repeat(indent.len as usize),
 3760                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3761                    };
 3762                    let point = Point::new(row.0, 0);
 3763                    indent_edits.push((point..point, text));
 3764                }
 3765            }
 3766            editor.edit(indent_edits, cx);
 3767        });
 3768    }
 3769
 3770    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3771        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3772
 3773        let buffer = self.buffer.read(cx);
 3774        let snapshot = buffer.snapshot(cx);
 3775
 3776        let mut edits = Vec::new();
 3777        let mut rows = Vec::new();
 3778        let mut rows_inserted = 0;
 3779
 3780        for selection in self.selections.all_adjusted(cx) {
 3781            let cursor = selection.head();
 3782            let row = cursor.row;
 3783
 3784            let point = Point::new(row + 1, 0);
 3785            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3786
 3787            let newline = "\n".to_string();
 3788            edits.push((start_of_line..start_of_line, newline));
 3789
 3790            rows_inserted += 1;
 3791            rows.push(row + rows_inserted);
 3792        }
 3793
 3794        self.transact(window, cx, |editor, window, cx| {
 3795            editor.edit(edits, cx);
 3796
 3797            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3798                let mut index = 0;
 3799                s.move_cursors_with(|map, _, _| {
 3800                    let row = rows[index];
 3801                    index += 1;
 3802
 3803                    let point = Point::new(row, 0);
 3804                    let boundary = map.next_line_boundary(point).1;
 3805                    let clipped = map.clip_point(boundary, Bias::Left);
 3806
 3807                    (clipped, SelectionGoal::None)
 3808                });
 3809            });
 3810
 3811            let mut indent_edits = Vec::new();
 3812            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3813            for row in rows {
 3814                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3815                for (row, indent) in indents {
 3816                    if indent.len == 0 {
 3817                        continue;
 3818                    }
 3819
 3820                    let text = match indent.kind {
 3821                        IndentKind::Space => " ".repeat(indent.len as usize),
 3822                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3823                    };
 3824                    let point = Point::new(row.0, 0);
 3825                    indent_edits.push((point..point, text));
 3826                }
 3827            }
 3828            editor.edit(indent_edits, cx);
 3829        });
 3830    }
 3831
 3832    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3833        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3834            original_indent_columns: Vec::new(),
 3835        });
 3836        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3837    }
 3838
 3839    fn insert_with_autoindent_mode(
 3840        &mut self,
 3841        text: &str,
 3842        autoindent_mode: Option<AutoindentMode>,
 3843        window: &mut Window,
 3844        cx: &mut Context<Self>,
 3845    ) {
 3846        if self.read_only(cx) {
 3847            return;
 3848        }
 3849
 3850        let text: Arc<str> = text.into();
 3851        self.transact(window, cx, |this, window, cx| {
 3852            let old_selections = this.selections.all_adjusted(cx);
 3853            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3854                let anchors = {
 3855                    let snapshot = buffer.read(cx);
 3856                    old_selections
 3857                        .iter()
 3858                        .map(|s| {
 3859                            let anchor = snapshot.anchor_after(s.head());
 3860                            s.map(|_| anchor)
 3861                        })
 3862                        .collect::<Vec<_>>()
 3863                };
 3864                buffer.edit(
 3865                    old_selections
 3866                        .iter()
 3867                        .map(|s| (s.start..s.end, text.clone())),
 3868                    autoindent_mode,
 3869                    cx,
 3870                );
 3871                anchors
 3872            });
 3873
 3874            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3875                s.select_anchors(selection_anchors);
 3876            });
 3877
 3878            cx.notify();
 3879        });
 3880    }
 3881
 3882    fn trigger_completion_on_input(
 3883        &mut self,
 3884        text: &str,
 3885        trigger_in_words: bool,
 3886        window: &mut Window,
 3887        cx: &mut Context<Self>,
 3888    ) {
 3889        let ignore_completion_provider = self
 3890            .context_menu
 3891            .borrow()
 3892            .as_ref()
 3893            .map(|menu| match menu {
 3894                CodeContextMenu::Completions(completions_menu) => {
 3895                    completions_menu.ignore_completion_provider
 3896                }
 3897                CodeContextMenu::CodeActions(_) => false,
 3898            })
 3899            .unwrap_or(false);
 3900
 3901        if ignore_completion_provider {
 3902            self.show_word_completions(&ShowWordCompletions, window, cx);
 3903        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3904            self.show_completions(
 3905                &ShowCompletions {
 3906                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3907                },
 3908                window,
 3909                cx,
 3910            );
 3911        } else {
 3912            self.hide_context_menu(window, cx);
 3913        }
 3914    }
 3915
 3916    fn is_completion_trigger(
 3917        &self,
 3918        text: &str,
 3919        trigger_in_words: bool,
 3920        cx: &mut Context<Self>,
 3921    ) -> bool {
 3922        let position = self.selections.newest_anchor().head();
 3923        let multibuffer = self.buffer.read(cx);
 3924        let Some(buffer) = position
 3925            .buffer_id
 3926            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3927        else {
 3928            return false;
 3929        };
 3930
 3931        if let Some(completion_provider) = &self.completion_provider {
 3932            completion_provider.is_completion_trigger(
 3933                &buffer,
 3934                position.text_anchor,
 3935                text,
 3936                trigger_in_words,
 3937                cx,
 3938            )
 3939        } else {
 3940            false
 3941        }
 3942    }
 3943
 3944    /// If any empty selections is touching the start of its innermost containing autoclose
 3945    /// region, expand it to select the brackets.
 3946    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3947        let selections = self.selections.all::<usize>(cx);
 3948        let buffer = self.buffer.read(cx).read(cx);
 3949        let new_selections = self
 3950            .selections_with_autoclose_regions(selections, &buffer)
 3951            .map(|(mut selection, region)| {
 3952                if !selection.is_empty() {
 3953                    return selection;
 3954                }
 3955
 3956                if let Some(region) = region {
 3957                    let mut range = region.range.to_offset(&buffer);
 3958                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3959                        range.start -= region.pair.start.len();
 3960                        if buffer.contains_str_at(range.start, &region.pair.start)
 3961                            && buffer.contains_str_at(range.end, &region.pair.end)
 3962                        {
 3963                            range.end += region.pair.end.len();
 3964                            selection.start = range.start;
 3965                            selection.end = range.end;
 3966
 3967                            return selection;
 3968                        }
 3969                    }
 3970                }
 3971
 3972                let always_treat_brackets_as_autoclosed = buffer
 3973                    .language_settings_at(selection.start, cx)
 3974                    .always_treat_brackets_as_autoclosed;
 3975
 3976                if !always_treat_brackets_as_autoclosed {
 3977                    return selection;
 3978                }
 3979
 3980                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3981                    for (pair, enabled) in scope.brackets() {
 3982                        if !enabled || !pair.close {
 3983                            continue;
 3984                        }
 3985
 3986                        if buffer.contains_str_at(selection.start, &pair.end) {
 3987                            let pair_start_len = pair.start.len();
 3988                            if buffer.contains_str_at(
 3989                                selection.start.saturating_sub(pair_start_len),
 3990                                &pair.start,
 3991                            ) {
 3992                                selection.start -= pair_start_len;
 3993                                selection.end += pair.end.len();
 3994
 3995                                return selection;
 3996                            }
 3997                        }
 3998                    }
 3999                }
 4000
 4001                selection
 4002            })
 4003            .collect();
 4004
 4005        drop(buffer);
 4006        self.change_selections(None, window, cx, |selections| {
 4007            selections.select(new_selections)
 4008        });
 4009    }
 4010
 4011    /// Iterate the given selections, and for each one, find the smallest surrounding
 4012    /// autoclose region. This uses the ordering of the selections and the autoclose
 4013    /// regions to avoid repeated comparisons.
 4014    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4015        &'a self,
 4016        selections: impl IntoIterator<Item = Selection<D>>,
 4017        buffer: &'a MultiBufferSnapshot,
 4018    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4019        let mut i = 0;
 4020        let mut regions = self.autoclose_regions.as_slice();
 4021        selections.into_iter().map(move |selection| {
 4022            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4023
 4024            let mut enclosing = None;
 4025            while let Some(pair_state) = regions.get(i) {
 4026                if pair_state.range.end.to_offset(buffer) < range.start {
 4027                    regions = &regions[i + 1..];
 4028                    i = 0;
 4029                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4030                    break;
 4031                } else {
 4032                    if pair_state.selection_id == selection.id {
 4033                        enclosing = Some(pair_state);
 4034                    }
 4035                    i += 1;
 4036                }
 4037            }
 4038
 4039            (selection, enclosing)
 4040        })
 4041    }
 4042
 4043    /// Remove any autoclose regions that no longer contain their selection.
 4044    fn invalidate_autoclose_regions(
 4045        &mut self,
 4046        mut selections: &[Selection<Anchor>],
 4047        buffer: &MultiBufferSnapshot,
 4048    ) {
 4049        self.autoclose_regions.retain(|state| {
 4050            let mut i = 0;
 4051            while let Some(selection) = selections.get(i) {
 4052                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4053                    selections = &selections[1..];
 4054                    continue;
 4055                }
 4056                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4057                    break;
 4058                }
 4059                if selection.id == state.selection_id {
 4060                    return true;
 4061                } else {
 4062                    i += 1;
 4063                }
 4064            }
 4065            false
 4066        });
 4067    }
 4068
 4069    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4070        let offset = position.to_offset(buffer);
 4071        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4072        if offset > word_range.start && kind == Some(CharKind::Word) {
 4073            Some(
 4074                buffer
 4075                    .text_for_range(word_range.start..offset)
 4076                    .collect::<String>(),
 4077            )
 4078        } else {
 4079            None
 4080        }
 4081    }
 4082
 4083    pub fn toggle_inlay_hints(
 4084        &mut self,
 4085        _: &ToggleInlayHints,
 4086        _: &mut Window,
 4087        cx: &mut Context<Self>,
 4088    ) {
 4089        self.refresh_inlay_hints(
 4090            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4091            cx,
 4092        );
 4093    }
 4094
 4095    pub fn inlay_hints_enabled(&self) -> bool {
 4096        self.inlay_hint_cache.enabled
 4097    }
 4098
 4099    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4100        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4101            return;
 4102        }
 4103
 4104        let reason_description = reason.description();
 4105        let ignore_debounce = matches!(
 4106            reason,
 4107            InlayHintRefreshReason::SettingsChange(_)
 4108                | InlayHintRefreshReason::Toggle(_)
 4109                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4110                | InlayHintRefreshReason::ModifiersChanged(_)
 4111        );
 4112        let (invalidate_cache, required_languages) = match reason {
 4113            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4114                match self.inlay_hint_cache.modifiers_override(enabled) {
 4115                    Some(enabled) => {
 4116                        if enabled {
 4117                            (InvalidationStrategy::RefreshRequested, None)
 4118                        } else {
 4119                            self.splice_inlays(
 4120                                &self
 4121                                    .visible_inlay_hints(cx)
 4122                                    .iter()
 4123                                    .map(|inlay| inlay.id)
 4124                                    .collect::<Vec<InlayId>>(),
 4125                                Vec::new(),
 4126                                cx,
 4127                            );
 4128                            return;
 4129                        }
 4130                    }
 4131                    None => return,
 4132                }
 4133            }
 4134            InlayHintRefreshReason::Toggle(enabled) => {
 4135                if self.inlay_hint_cache.toggle(enabled) {
 4136                    if enabled {
 4137                        (InvalidationStrategy::RefreshRequested, None)
 4138                    } else {
 4139                        self.splice_inlays(
 4140                            &self
 4141                                .visible_inlay_hints(cx)
 4142                                .iter()
 4143                                .map(|inlay| inlay.id)
 4144                                .collect::<Vec<InlayId>>(),
 4145                            Vec::new(),
 4146                            cx,
 4147                        );
 4148                        return;
 4149                    }
 4150                } else {
 4151                    return;
 4152                }
 4153            }
 4154            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4155                match self.inlay_hint_cache.update_settings(
 4156                    &self.buffer,
 4157                    new_settings,
 4158                    self.visible_inlay_hints(cx),
 4159                    cx,
 4160                ) {
 4161                    ControlFlow::Break(Some(InlaySplice {
 4162                        to_remove,
 4163                        to_insert,
 4164                    })) => {
 4165                        self.splice_inlays(&to_remove, to_insert, cx);
 4166                        return;
 4167                    }
 4168                    ControlFlow::Break(None) => return,
 4169                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4170                }
 4171            }
 4172            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4173                if let Some(InlaySplice {
 4174                    to_remove,
 4175                    to_insert,
 4176                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4177                {
 4178                    self.splice_inlays(&to_remove, to_insert, cx);
 4179                }
 4180                self.display_map.update(cx, |display_map, _| {
 4181                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4182                });
 4183                return;
 4184            }
 4185            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4186            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4187                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4188            }
 4189            InlayHintRefreshReason::RefreshRequested => {
 4190                (InvalidationStrategy::RefreshRequested, None)
 4191            }
 4192        };
 4193
 4194        if let Some(InlaySplice {
 4195            to_remove,
 4196            to_insert,
 4197        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4198            reason_description,
 4199            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4200            invalidate_cache,
 4201            ignore_debounce,
 4202            cx,
 4203        ) {
 4204            self.splice_inlays(&to_remove, to_insert, cx);
 4205        }
 4206    }
 4207
 4208    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4209        self.display_map
 4210            .read(cx)
 4211            .current_inlays()
 4212            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4213            .cloned()
 4214            .collect()
 4215    }
 4216
 4217    pub fn excerpts_for_inlay_hints_query(
 4218        &self,
 4219        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4220        cx: &mut Context<Editor>,
 4221    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4222        let Some(project) = self.project.as_ref() else {
 4223            return HashMap::default();
 4224        };
 4225        let project = project.read(cx);
 4226        let multi_buffer = self.buffer().read(cx);
 4227        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4228        let multi_buffer_visible_start = self
 4229            .scroll_manager
 4230            .anchor()
 4231            .anchor
 4232            .to_point(&multi_buffer_snapshot);
 4233        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4234            multi_buffer_visible_start
 4235                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4236            Bias::Left,
 4237        );
 4238        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4239        multi_buffer_snapshot
 4240            .range_to_buffer_ranges(multi_buffer_visible_range)
 4241            .into_iter()
 4242            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4243            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4244                let buffer_file = project::File::from_dyn(buffer.file())?;
 4245                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4246                let worktree_entry = buffer_worktree
 4247                    .read(cx)
 4248                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4249                if worktree_entry.is_ignored {
 4250                    return None;
 4251                }
 4252
 4253                let language = buffer.language()?;
 4254                if let Some(restrict_to_languages) = restrict_to_languages {
 4255                    if !restrict_to_languages.contains(language) {
 4256                        return None;
 4257                    }
 4258                }
 4259                Some((
 4260                    excerpt_id,
 4261                    (
 4262                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4263                        buffer.version().clone(),
 4264                        excerpt_visible_range,
 4265                    ),
 4266                ))
 4267            })
 4268            .collect()
 4269    }
 4270
 4271    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4272        TextLayoutDetails {
 4273            text_system: window.text_system().clone(),
 4274            editor_style: self.style.clone().unwrap(),
 4275            rem_size: window.rem_size(),
 4276            scroll_anchor: self.scroll_manager.anchor(),
 4277            visible_rows: self.visible_line_count(),
 4278            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4279        }
 4280    }
 4281
 4282    pub fn splice_inlays(
 4283        &self,
 4284        to_remove: &[InlayId],
 4285        to_insert: Vec<Inlay>,
 4286        cx: &mut Context<Self>,
 4287    ) {
 4288        self.display_map.update(cx, |display_map, cx| {
 4289            display_map.splice_inlays(to_remove, to_insert, cx)
 4290        });
 4291        cx.notify();
 4292    }
 4293
 4294    fn trigger_on_type_formatting(
 4295        &self,
 4296        input: String,
 4297        window: &mut Window,
 4298        cx: &mut Context<Self>,
 4299    ) -> Option<Task<Result<()>>> {
 4300        if input.len() != 1 {
 4301            return None;
 4302        }
 4303
 4304        let project = self.project.as_ref()?;
 4305        let position = self.selections.newest_anchor().head();
 4306        let (buffer, buffer_position) = self
 4307            .buffer
 4308            .read(cx)
 4309            .text_anchor_for_position(position, cx)?;
 4310
 4311        let settings = language_settings::language_settings(
 4312            buffer
 4313                .read(cx)
 4314                .language_at(buffer_position)
 4315                .map(|l| l.name()),
 4316            buffer.read(cx).file(),
 4317            cx,
 4318        );
 4319        if !settings.use_on_type_format {
 4320            return None;
 4321        }
 4322
 4323        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4324        // hence we do LSP request & edit on host side only — add formats to host's history.
 4325        let push_to_lsp_host_history = true;
 4326        // If this is not the host, append its history with new edits.
 4327        let push_to_client_history = project.read(cx).is_via_collab();
 4328
 4329        let on_type_formatting = project.update(cx, |project, cx| {
 4330            project.on_type_format(
 4331                buffer.clone(),
 4332                buffer_position,
 4333                input,
 4334                push_to_lsp_host_history,
 4335                cx,
 4336            )
 4337        });
 4338        Some(cx.spawn_in(window, async move |editor, cx| {
 4339            if let Some(transaction) = on_type_formatting.await? {
 4340                if push_to_client_history {
 4341                    buffer
 4342                        .update(cx, |buffer, _| {
 4343                            buffer.push_transaction(transaction, Instant::now());
 4344                            buffer.finalize_last_transaction();
 4345                        })
 4346                        .ok();
 4347                }
 4348                editor.update(cx, |editor, cx| {
 4349                    editor.refresh_document_highlights(cx);
 4350                })?;
 4351            }
 4352            Ok(())
 4353        }))
 4354    }
 4355
 4356    pub fn show_word_completions(
 4357        &mut self,
 4358        _: &ShowWordCompletions,
 4359        window: &mut Window,
 4360        cx: &mut Context<Self>,
 4361    ) {
 4362        self.open_completions_menu(true, None, window, cx);
 4363    }
 4364
 4365    pub fn show_completions(
 4366        &mut self,
 4367        options: &ShowCompletions,
 4368        window: &mut Window,
 4369        cx: &mut Context<Self>,
 4370    ) {
 4371        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4372    }
 4373
 4374    fn open_completions_menu(
 4375        &mut self,
 4376        ignore_completion_provider: bool,
 4377        trigger: Option<&str>,
 4378        window: &mut Window,
 4379        cx: &mut Context<Self>,
 4380    ) {
 4381        if self.pending_rename.is_some() {
 4382            return;
 4383        }
 4384        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4385            return;
 4386        }
 4387
 4388        let position = self.selections.newest_anchor().head();
 4389        if position.diff_base_anchor.is_some() {
 4390            return;
 4391        }
 4392        let (buffer, buffer_position) =
 4393            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4394                output
 4395            } else {
 4396                return;
 4397            };
 4398        let buffer_snapshot = buffer.read(cx).snapshot();
 4399        let show_completion_documentation = buffer_snapshot
 4400            .settings_at(buffer_position, cx)
 4401            .show_completion_documentation;
 4402
 4403        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4404
 4405        let trigger_kind = match trigger {
 4406            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4407                CompletionTriggerKind::TRIGGER_CHARACTER
 4408            }
 4409            _ => CompletionTriggerKind::INVOKED,
 4410        };
 4411        let completion_context = CompletionContext {
 4412            trigger_character: trigger.and_then(|trigger| {
 4413                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4414                    Some(String::from(trigger))
 4415                } else {
 4416                    None
 4417                }
 4418            }),
 4419            trigger_kind,
 4420        };
 4421
 4422        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4423        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4424            let word_to_exclude = buffer_snapshot
 4425                .text_for_range(old_range.clone())
 4426                .collect::<String>();
 4427            (
 4428                buffer_snapshot.anchor_before(old_range.start)
 4429                    ..buffer_snapshot.anchor_after(old_range.end),
 4430                Some(word_to_exclude),
 4431            )
 4432        } else {
 4433            (buffer_position..buffer_position, None)
 4434        };
 4435
 4436        let completion_settings = language_settings(
 4437            buffer_snapshot
 4438                .language_at(buffer_position)
 4439                .map(|language| language.name()),
 4440            buffer_snapshot.file(),
 4441            cx,
 4442        )
 4443        .completions;
 4444
 4445        // The document can be large, so stay in reasonable bounds when searching for words,
 4446        // otherwise completion pop-up might be slow to appear.
 4447        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4448        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4449        let min_word_search = buffer_snapshot.clip_point(
 4450            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4451            Bias::Left,
 4452        );
 4453        let max_word_search = buffer_snapshot.clip_point(
 4454            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4455            Bias::Right,
 4456        );
 4457        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4458            ..buffer_snapshot.point_to_offset(max_word_search);
 4459
 4460        let provider = self
 4461            .completion_provider
 4462            .as_ref()
 4463            .filter(|_| !ignore_completion_provider);
 4464        let skip_digits = query
 4465            .as_ref()
 4466            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4467
 4468        let (mut words, provided_completions) = match provider {
 4469            Some(provider) => {
 4470                let completions = provider.completions(
 4471                    position.excerpt_id,
 4472                    &buffer,
 4473                    buffer_position,
 4474                    completion_context,
 4475                    window,
 4476                    cx,
 4477                );
 4478
 4479                let words = match completion_settings.words {
 4480                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4481                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4482                        .background_spawn(async move {
 4483                            buffer_snapshot.words_in_range(WordsQuery {
 4484                                fuzzy_contents: None,
 4485                                range: word_search_range,
 4486                                skip_digits,
 4487                            })
 4488                        }),
 4489                };
 4490
 4491                (words, completions)
 4492            }
 4493            None => (
 4494                cx.background_spawn(async move {
 4495                    buffer_snapshot.words_in_range(WordsQuery {
 4496                        fuzzy_contents: None,
 4497                        range: word_search_range,
 4498                        skip_digits,
 4499                    })
 4500                }),
 4501                Task::ready(Ok(None)),
 4502            ),
 4503        };
 4504
 4505        let sort_completions = provider
 4506            .as_ref()
 4507            .map_or(false, |provider| provider.sort_completions());
 4508
 4509        let filter_completions = provider
 4510            .as_ref()
 4511            .map_or(true, |provider| provider.filter_completions());
 4512
 4513        let id = post_inc(&mut self.next_completion_id);
 4514        let task = cx.spawn_in(window, async move |editor, cx| {
 4515            async move {
 4516                editor.update(cx, |this, _| {
 4517                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4518                })?;
 4519
 4520                let mut completions = Vec::new();
 4521                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4522                    completions.extend(provided_completions);
 4523                    if completion_settings.words == WordsCompletionMode::Fallback {
 4524                        words = Task::ready(BTreeMap::default());
 4525                    }
 4526                }
 4527
 4528                let mut words = words.await;
 4529                if let Some(word_to_exclude) = &word_to_exclude {
 4530                    words.remove(word_to_exclude);
 4531                }
 4532                for lsp_completion in &completions {
 4533                    words.remove(&lsp_completion.new_text);
 4534                }
 4535                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4536                    replace_range: old_range.clone(),
 4537                    new_text: word.clone(),
 4538                    label: CodeLabel::plain(word, None),
 4539                    icon_path: None,
 4540                    documentation: None,
 4541                    source: CompletionSource::BufferWord {
 4542                        word_range,
 4543                        resolved: false,
 4544                    },
 4545                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4546                    confirm: None,
 4547                }));
 4548
 4549                let menu = if completions.is_empty() {
 4550                    None
 4551                } else {
 4552                    let mut menu = CompletionsMenu::new(
 4553                        id,
 4554                        sort_completions,
 4555                        show_completion_documentation,
 4556                        ignore_completion_provider,
 4557                        position,
 4558                        buffer.clone(),
 4559                        completions.into(),
 4560                    );
 4561
 4562                    menu.filter(
 4563                        if filter_completions {
 4564                            query.as_deref()
 4565                        } else {
 4566                            None
 4567                        },
 4568                        cx.background_executor().clone(),
 4569                    )
 4570                    .await;
 4571
 4572                    menu.visible().then_some(menu)
 4573                };
 4574
 4575                editor.update_in(cx, |editor, window, cx| {
 4576                    match editor.context_menu.borrow().as_ref() {
 4577                        None => {}
 4578                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4579                            if prev_menu.id > id {
 4580                                return;
 4581                            }
 4582                        }
 4583                        _ => return,
 4584                    }
 4585
 4586                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4587                        let mut menu = menu.unwrap();
 4588                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4589
 4590                        *editor.context_menu.borrow_mut() =
 4591                            Some(CodeContextMenu::Completions(menu));
 4592
 4593                        if editor.show_edit_predictions_in_menu() {
 4594                            editor.update_visible_inline_completion(window, cx);
 4595                        } else {
 4596                            editor.discard_inline_completion(false, cx);
 4597                        }
 4598
 4599                        cx.notify();
 4600                    } else if editor.completion_tasks.len() <= 1 {
 4601                        // If there are no more completion tasks and the last menu was
 4602                        // empty, we should hide it.
 4603                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4604                        // If it was already hidden and we don't show inline
 4605                        // completions in the menu, we should also show the
 4606                        // inline-completion when available.
 4607                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4608                            editor.update_visible_inline_completion(window, cx);
 4609                        }
 4610                    }
 4611                })?;
 4612
 4613                anyhow::Ok(())
 4614            }
 4615            .log_err()
 4616            .await
 4617        });
 4618
 4619        self.completion_tasks.push((id, task));
 4620    }
 4621
 4622    #[cfg(feature = "test-support")]
 4623    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4624        let menu = self.context_menu.borrow();
 4625        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4626            let completions = menu.completions.borrow();
 4627            Some(completions.to_vec())
 4628        } else {
 4629            None
 4630        }
 4631    }
 4632
 4633    pub fn confirm_completion(
 4634        &mut self,
 4635        action: &ConfirmCompletion,
 4636        window: &mut Window,
 4637        cx: &mut Context<Self>,
 4638    ) -> Option<Task<Result<()>>> {
 4639        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4640        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4641    }
 4642
 4643    pub fn confirm_completion_insert(
 4644        &mut self,
 4645        _: &ConfirmCompletionInsert,
 4646        window: &mut Window,
 4647        cx: &mut Context<Self>,
 4648    ) -> Option<Task<Result<()>>> {
 4649        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4650        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4651    }
 4652
 4653    pub fn confirm_completion_replace(
 4654        &mut self,
 4655        _: &ConfirmCompletionReplace,
 4656        window: &mut Window,
 4657        cx: &mut Context<Self>,
 4658    ) -> Option<Task<Result<()>>> {
 4659        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4660        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4661    }
 4662
 4663    pub fn compose_completion(
 4664        &mut self,
 4665        action: &ComposeCompletion,
 4666        window: &mut Window,
 4667        cx: &mut Context<Self>,
 4668    ) -> Option<Task<Result<()>>> {
 4669        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4670        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4671    }
 4672
 4673    fn do_completion(
 4674        &mut self,
 4675        item_ix: Option<usize>,
 4676        intent: CompletionIntent,
 4677        window: &mut Window,
 4678        cx: &mut Context<Editor>,
 4679    ) -> Option<Task<Result<()>>> {
 4680        use language::ToOffset as _;
 4681
 4682        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4683        else {
 4684            return None;
 4685        };
 4686
 4687        let candidate_id = {
 4688            let entries = completions_menu.entries.borrow();
 4689            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4690            if self.show_edit_predictions_in_menu() {
 4691                self.discard_inline_completion(true, cx);
 4692            }
 4693            mat.candidate_id
 4694        };
 4695
 4696        let buffer_handle = completions_menu.buffer;
 4697        let completion = completions_menu
 4698            .completions
 4699            .borrow()
 4700            .get(candidate_id)?
 4701            .clone();
 4702        cx.stop_propagation();
 4703
 4704        let snippet;
 4705        let new_text;
 4706        if completion.is_snippet() {
 4707            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4708            new_text = snippet.as_ref().unwrap().text.clone();
 4709        } else {
 4710            snippet = None;
 4711            new_text = completion.new_text.clone();
 4712        };
 4713
 4714        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4715        let buffer = buffer_handle.read(cx);
 4716        let snapshot = self.buffer.read(cx).snapshot(cx);
 4717        let replace_range_multibuffer = {
 4718            let excerpt = snapshot
 4719                .excerpt_containing(self.selections.newest_anchor().range())
 4720                .unwrap();
 4721            let multibuffer_anchor = snapshot
 4722                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4723                .unwrap()
 4724                ..snapshot
 4725                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4726                    .unwrap();
 4727            multibuffer_anchor.start.to_offset(&snapshot)
 4728                ..multibuffer_anchor.end.to_offset(&snapshot)
 4729        };
 4730        let newest_anchor = self.selections.newest_anchor();
 4731        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4732            return None;
 4733        }
 4734
 4735        let old_text = buffer
 4736            .text_for_range(replace_range.clone())
 4737            .collect::<String>();
 4738        let lookbehind = newest_anchor
 4739            .start
 4740            .text_anchor
 4741            .to_offset(buffer)
 4742            .saturating_sub(replace_range.start);
 4743        let lookahead = replace_range
 4744            .end
 4745            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4746        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4747        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4748
 4749        let selections = self.selections.all::<usize>(cx);
 4750        let mut ranges = Vec::new();
 4751        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4752
 4753        for selection in &selections {
 4754            let range = if selection.id == newest_anchor.id {
 4755                replace_range_multibuffer.clone()
 4756            } else {
 4757                let mut range = selection.range();
 4758
 4759                // if prefix is present, don't duplicate it
 4760                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 4761                    range.start = range.start.saturating_sub(lookbehind);
 4762
 4763                    // if suffix is also present, mimic the newest cursor and replace it
 4764                    if selection.id != newest_anchor.id
 4765                        && snapshot.contains_str_at(range.end, suffix)
 4766                    {
 4767                        range.end += lookahead;
 4768                    }
 4769                }
 4770                range
 4771            };
 4772
 4773            ranges.push(range);
 4774
 4775            if !self.linked_edit_ranges.is_empty() {
 4776                let start_anchor = snapshot.anchor_before(selection.head());
 4777                let end_anchor = snapshot.anchor_after(selection.tail());
 4778                if let Some(ranges) = self
 4779                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4780                {
 4781                    for (buffer, edits) in ranges {
 4782                        linked_edits
 4783                            .entry(buffer.clone())
 4784                            .or_default()
 4785                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 4786                    }
 4787                }
 4788            }
 4789        }
 4790
 4791        cx.emit(EditorEvent::InputHandled {
 4792            utf16_range_to_replace: None,
 4793            text: new_text.clone().into(),
 4794        });
 4795
 4796        self.transact(window, cx, |this, window, cx| {
 4797            if let Some(mut snippet) = snippet {
 4798                snippet.text = new_text.to_string();
 4799                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4800            } else {
 4801                this.buffer.update(cx, |buffer, cx| {
 4802                    let auto_indent = match completion.insert_text_mode {
 4803                        Some(InsertTextMode::AS_IS) => None,
 4804                        _ => this.autoindent_mode.clone(),
 4805                    };
 4806                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 4807                    buffer.edit(edits, auto_indent, cx);
 4808                });
 4809            }
 4810            for (buffer, edits) in linked_edits {
 4811                buffer.update(cx, |buffer, cx| {
 4812                    let snapshot = buffer.snapshot();
 4813                    let edits = edits
 4814                        .into_iter()
 4815                        .map(|(range, text)| {
 4816                            use text::ToPoint as TP;
 4817                            let end_point = TP::to_point(&range.end, &snapshot);
 4818                            let start_point = TP::to_point(&range.start, &snapshot);
 4819                            (start_point..end_point, text)
 4820                        })
 4821                        .sorted_by_key(|(range, _)| range.start);
 4822                    buffer.edit(edits, None, cx);
 4823                })
 4824            }
 4825
 4826            this.refresh_inline_completion(true, false, window, cx);
 4827        });
 4828
 4829        let show_new_completions_on_confirm = completion
 4830            .confirm
 4831            .as_ref()
 4832            .map_or(false, |confirm| confirm(intent, window, cx));
 4833        if show_new_completions_on_confirm {
 4834            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4835        }
 4836
 4837        let provider = self.completion_provider.as_ref()?;
 4838        drop(completion);
 4839        let apply_edits = provider.apply_additional_edits_for_completion(
 4840            buffer_handle,
 4841            completions_menu.completions.clone(),
 4842            candidate_id,
 4843            true,
 4844            cx,
 4845        );
 4846
 4847        let editor_settings = EditorSettings::get_global(cx);
 4848        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4849            // After the code completion is finished, users often want to know what signatures are needed.
 4850            // so we should automatically call signature_help
 4851            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4852        }
 4853
 4854        Some(cx.foreground_executor().spawn(async move {
 4855            apply_edits.await?;
 4856            Ok(())
 4857        }))
 4858    }
 4859
 4860    fn prepare_code_actions_task(
 4861        &mut self,
 4862        action: &ToggleCodeActions,
 4863        window: &mut Window,
 4864        cx: &mut Context<Self>,
 4865    ) -> Task<Option<(Entity<Buffer>, CodeActionContents)>> {
 4866        let snapshot = self.snapshot(window, cx);
 4867        let multibuffer_point = action
 4868            .deployed_from_indicator
 4869            .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4870            .unwrap_or_else(|| self.selections.newest::<Point>(cx).head());
 4871
 4872        let Some((buffer, buffer_row)) = snapshot
 4873            .buffer_snapshot
 4874            .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4875            .and_then(|(buffer_snapshot, range)| {
 4876                self.buffer
 4877                    .read(cx)
 4878                    .buffer(buffer_snapshot.remote_id())
 4879                    .map(|buffer| (buffer, range.start.row))
 4880            })
 4881        else {
 4882            return Task::ready(None);
 4883        };
 4884
 4885        let (_, code_actions) = self
 4886            .available_code_actions
 4887            .clone()
 4888            .and_then(|(location, code_actions)| {
 4889                let snapshot = location.buffer.read(cx).snapshot();
 4890                let point_range = location.range.to_point(&snapshot);
 4891                let point_range = point_range.start.row..=point_range.end.row;
 4892                if point_range.contains(&buffer_row) {
 4893                    Some((location, code_actions))
 4894                } else {
 4895                    None
 4896                }
 4897            })
 4898            .unzip();
 4899
 4900        let buffer_id = buffer.read(cx).remote_id();
 4901        let tasks = self
 4902            .tasks
 4903            .get(&(buffer_id, buffer_row))
 4904            .map(|t| Arc::new(t.to_owned()));
 4905
 4906        if tasks.is_none() && code_actions.is_none() {
 4907            return Task::ready(None);
 4908        }
 4909
 4910        self.completion_tasks.clear();
 4911        self.discard_inline_completion(false, cx);
 4912
 4913        let task_context = tasks
 4914            .as_ref()
 4915            .zip(self.project.clone())
 4916            .map(|(tasks, project)| {
 4917                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4918            });
 4919
 4920        cx.spawn_in(window, async move |_, cx| {
 4921            let task_context = match task_context {
 4922                Some(task_context) => task_context.await,
 4923                None => None,
 4924            };
 4925            let resolved_tasks =
 4926                tasks
 4927                    .zip(task_context)
 4928                    .map(|(tasks, task_context)| ResolvedTasks {
 4929                        templates: tasks.resolve(&task_context).collect(),
 4930                        position: snapshot
 4931                            .buffer_snapshot
 4932                            .anchor_before(Point::new(multibuffer_point.row, tasks.column)),
 4933                    });
 4934            let code_action_contents = cx
 4935                .update(|_, cx| CodeActionContents::new(resolved_tasks, code_actions, cx))
 4936                .ok()?;
 4937            Some((buffer, code_action_contents))
 4938        })
 4939    }
 4940
 4941    pub fn toggle_code_actions(
 4942        &mut self,
 4943        action: &ToggleCodeActions,
 4944        window: &mut Window,
 4945        cx: &mut Context<Self>,
 4946    ) {
 4947        let mut context_menu = self.context_menu.borrow_mut();
 4948        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4949            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4950                // Toggle if we're selecting the same one
 4951                *context_menu = None;
 4952                cx.notify();
 4953                return;
 4954            } else {
 4955                // Otherwise, clear it and start a new one
 4956                *context_menu = None;
 4957                cx.notify();
 4958            }
 4959        }
 4960        drop(context_menu);
 4961
 4962        let deployed_from_indicator = action.deployed_from_indicator;
 4963        let mut task = self.code_actions_task.take();
 4964        let action = action.clone();
 4965
 4966        cx.spawn_in(window, async move |editor, cx| {
 4967            while let Some(prev_task) = task {
 4968                prev_task.await.log_err();
 4969                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4970            }
 4971
 4972            let context_menu_task = editor.update_in(cx, |editor, window, cx| {
 4973                if !editor.focus_handle.is_focused(window) {
 4974                    return Some(Task::ready(Ok(())));
 4975                }
 4976                let debugger_flag = cx.has_flag::<Debugger>();
 4977                let code_actions_task = editor.prepare_code_actions_task(&action, window, cx);
 4978                Some(cx.spawn_in(window, async move |editor, cx| {
 4979                    if let Some((buffer, code_action_contents)) = code_actions_task.await {
 4980                        let spawn_straight_away =
 4981                            code_action_contents.tasks().map_or(false, |tasks| {
 4982                                tasks
 4983                                    .templates
 4984                                    .iter()
 4985                                    .filter(|task| {
 4986                                        if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 4987                                            debugger_flag
 4988                                        } else {
 4989                                            true
 4990                                        }
 4991                                    })
 4992                                    .count()
 4993                                    == 1
 4994                            }) && code_action_contents
 4995                                .actions
 4996                                .as_ref()
 4997                                .map_or(true, |actions| actions.is_empty());
 4998                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 4999                            *editor.context_menu.borrow_mut() =
 5000                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5001                                    buffer,
 5002                                    actions: code_action_contents,
 5003                                    selected_item: Default::default(),
 5004                                    scroll_handle: UniformListScrollHandle::default(),
 5005                                    deployed_from_indicator,
 5006                                }));
 5007                            if spawn_straight_away {
 5008                                if let Some(task) = editor.confirm_code_action(
 5009                                    &ConfirmCodeAction {
 5010                                        item_ix: Some(0),
 5011                                        from_mouse_context_menu: false,
 5012                                    },
 5013                                    window,
 5014                                    cx,
 5015                                ) {
 5016                                    cx.notify();
 5017                                    return task;
 5018                                }
 5019                            }
 5020                            cx.notify();
 5021                            Task::ready(Ok(()))
 5022                        }) {
 5023                            task.await
 5024                        } else {
 5025                            Ok(())
 5026                        }
 5027                    } else {
 5028                        Ok(())
 5029                    }
 5030                }))
 5031            })?;
 5032            if let Some(task) = context_menu_task {
 5033                task.await?;
 5034            }
 5035
 5036            Ok::<_, anyhow::Error>(())
 5037        })
 5038        .detach_and_log_err(cx);
 5039    }
 5040
 5041    pub fn confirm_code_action(
 5042        &mut self,
 5043        action: &ConfirmCodeAction,
 5044        window: &mut Window,
 5045        cx: &mut Context<Self>,
 5046    ) -> Option<Task<Result<()>>> {
 5047        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5048
 5049        let (action, buffer) = if action.from_mouse_context_menu {
 5050            if let Some(menu) = self.mouse_context_menu.take() {
 5051                let code_action = menu.code_action?;
 5052                let index = action.item_ix?;
 5053                let action = code_action.actions.get(index)?;
 5054                (action, code_action.buffer)
 5055            } else {
 5056                return None;
 5057            }
 5058        } else {
 5059            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5060                let action_ix = action.item_ix.unwrap_or(menu.selected_item);
 5061                let action = menu.actions.get(action_ix)?;
 5062                let buffer = menu.buffer;
 5063                (action, buffer)
 5064            } else {
 5065                return None;
 5066            }
 5067        };
 5068
 5069        let title = action.label();
 5070        let workspace = self.workspace()?;
 5071
 5072        match action {
 5073            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5074                match resolved_task.task_type() {
 5075                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5076                        workspace::tasks::schedule_resolved_task(
 5077                            workspace,
 5078                            task_source_kind,
 5079                            resolved_task,
 5080                            false,
 5081                            cx,
 5082                        );
 5083
 5084                        Some(Task::ready(Ok(())))
 5085                    }),
 5086                    task::TaskType::Debug(debug_args) => {
 5087                        if debug_args.locator.is_some() {
 5088                            workspace.update(cx, |workspace, cx| {
 5089                                workspace::tasks::schedule_resolved_task(
 5090                                    workspace,
 5091                                    task_source_kind,
 5092                                    resolved_task,
 5093                                    false,
 5094                                    cx,
 5095                                );
 5096                            });
 5097
 5098                            return Some(Task::ready(Ok(())));
 5099                        }
 5100
 5101                        if let Some(project) = self.project.as_ref() {
 5102                            project
 5103                                .update(cx, |project, cx| {
 5104                                    project.start_debug_session(
 5105                                        resolved_task.resolved_debug_adapter_config().unwrap(),
 5106                                        cx,
 5107                                    )
 5108                                })
 5109                                .detach_and_log_err(cx);
 5110                            Some(Task::ready(Ok(())))
 5111                        } else {
 5112                            Some(Task::ready(Ok(())))
 5113                        }
 5114                    }
 5115                }
 5116            }
 5117            CodeActionsItem::CodeAction {
 5118                excerpt_id,
 5119                action,
 5120                provider,
 5121            } => {
 5122                let apply_code_action =
 5123                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5124                let workspace = workspace.downgrade();
 5125                Some(cx.spawn_in(window, async move |editor, cx| {
 5126                    let project_transaction = apply_code_action.await?;
 5127                    Self::open_project_transaction(
 5128                        &editor,
 5129                        workspace,
 5130                        project_transaction,
 5131                        title,
 5132                        cx,
 5133                    )
 5134                    .await
 5135                }))
 5136            }
 5137        }
 5138    }
 5139
 5140    pub async fn open_project_transaction(
 5141        this: &WeakEntity<Editor>,
 5142        workspace: WeakEntity<Workspace>,
 5143        transaction: ProjectTransaction,
 5144        title: String,
 5145        cx: &mut AsyncWindowContext,
 5146    ) -> Result<()> {
 5147        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5148        cx.update(|_, cx| {
 5149            entries.sort_unstable_by_key(|(buffer, _)| {
 5150                buffer.read(cx).file().map(|f| f.path().clone())
 5151            });
 5152        })?;
 5153
 5154        // If the project transaction's edits are all contained within this editor, then
 5155        // avoid opening a new editor to display them.
 5156
 5157        if let Some((buffer, transaction)) = entries.first() {
 5158            if entries.len() == 1 {
 5159                let excerpt = this.update(cx, |editor, cx| {
 5160                    editor
 5161                        .buffer()
 5162                        .read(cx)
 5163                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5164                })?;
 5165                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5166                    if excerpted_buffer == *buffer {
 5167                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5168                            let excerpt_range = excerpt_range.to_offset(buffer);
 5169                            buffer
 5170                                .edited_ranges_for_transaction::<usize>(transaction)
 5171                                .all(|range| {
 5172                                    excerpt_range.start <= range.start
 5173                                        && excerpt_range.end >= range.end
 5174                                })
 5175                        })?;
 5176
 5177                        if all_edits_within_excerpt {
 5178                            return Ok(());
 5179                        }
 5180                    }
 5181                }
 5182            }
 5183        } else {
 5184            return Ok(());
 5185        }
 5186
 5187        let mut ranges_to_highlight = Vec::new();
 5188        let excerpt_buffer = cx.new(|cx| {
 5189            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5190            for (buffer_handle, transaction) in &entries {
 5191                let edited_ranges = buffer_handle
 5192                    .read(cx)
 5193                    .edited_ranges_for_transaction::<Point>(transaction)
 5194                    .collect::<Vec<_>>();
 5195                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5196                    PathKey::for_buffer(buffer_handle, cx),
 5197                    buffer_handle.clone(),
 5198                    edited_ranges,
 5199                    DEFAULT_MULTIBUFFER_CONTEXT,
 5200                    cx,
 5201                );
 5202
 5203                ranges_to_highlight.extend(ranges);
 5204            }
 5205            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5206            multibuffer
 5207        })?;
 5208
 5209        workspace.update_in(cx, |workspace, window, cx| {
 5210            let project = workspace.project().clone();
 5211            let editor =
 5212                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5213            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5214            editor.update(cx, |editor, cx| {
 5215                editor.highlight_background::<Self>(
 5216                    &ranges_to_highlight,
 5217                    |theme| theme.editor_highlighted_line_background,
 5218                    cx,
 5219                );
 5220            });
 5221        })?;
 5222
 5223        Ok(())
 5224    }
 5225
 5226    pub fn clear_code_action_providers(&mut self) {
 5227        self.code_action_providers.clear();
 5228        self.available_code_actions.take();
 5229    }
 5230
 5231    pub fn add_code_action_provider(
 5232        &mut self,
 5233        provider: Rc<dyn CodeActionProvider>,
 5234        window: &mut Window,
 5235        cx: &mut Context<Self>,
 5236    ) {
 5237        if self
 5238            .code_action_providers
 5239            .iter()
 5240            .any(|existing_provider| existing_provider.id() == provider.id())
 5241        {
 5242            return;
 5243        }
 5244
 5245        self.code_action_providers.push(provider);
 5246        self.refresh_code_actions(window, cx);
 5247    }
 5248
 5249    pub fn remove_code_action_provider(
 5250        &mut self,
 5251        id: Arc<str>,
 5252        window: &mut Window,
 5253        cx: &mut Context<Self>,
 5254    ) {
 5255        self.code_action_providers
 5256            .retain(|provider| provider.id() != id);
 5257        self.refresh_code_actions(window, cx);
 5258    }
 5259
 5260    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5261        let newest_selection = self.selections.newest_anchor().clone();
 5262        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5263        let buffer = self.buffer.read(cx);
 5264        if newest_selection.head().diff_base_anchor.is_some() {
 5265            return None;
 5266        }
 5267        let (start_buffer, start) =
 5268            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5269        let (end_buffer, end) =
 5270            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5271        if start_buffer != end_buffer {
 5272            return None;
 5273        }
 5274
 5275        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5276            cx.background_executor()
 5277                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5278                .await;
 5279
 5280            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5281                let providers = this.code_action_providers.clone();
 5282                let tasks = this
 5283                    .code_action_providers
 5284                    .iter()
 5285                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5286                    .collect::<Vec<_>>();
 5287                (providers, tasks)
 5288            })?;
 5289
 5290            let mut actions = Vec::new();
 5291            for (provider, provider_actions) in
 5292                providers.into_iter().zip(future::join_all(tasks).await)
 5293            {
 5294                if let Some(provider_actions) = provider_actions.log_err() {
 5295                    actions.extend(provider_actions.into_iter().map(|action| {
 5296                        AvailableCodeAction {
 5297                            excerpt_id: newest_selection.start.excerpt_id,
 5298                            action,
 5299                            provider: provider.clone(),
 5300                        }
 5301                    }));
 5302                }
 5303            }
 5304
 5305            this.update(cx, |this, cx| {
 5306                this.available_code_actions = if actions.is_empty() {
 5307                    None
 5308                } else {
 5309                    Some((
 5310                        Location {
 5311                            buffer: start_buffer,
 5312                            range: start..end,
 5313                        },
 5314                        actions.into(),
 5315                    ))
 5316                };
 5317                cx.notify();
 5318            })
 5319        }));
 5320        None
 5321    }
 5322
 5323    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5324        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5325            self.show_git_blame_inline = false;
 5326
 5327            self.show_git_blame_inline_delay_task =
 5328                Some(cx.spawn_in(window, async move |this, cx| {
 5329                    cx.background_executor().timer(delay).await;
 5330
 5331                    this.update(cx, |this, cx| {
 5332                        this.show_git_blame_inline = true;
 5333                        cx.notify();
 5334                    })
 5335                    .log_err();
 5336                }));
 5337        }
 5338    }
 5339
 5340    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5341        if self.pending_rename.is_some() {
 5342            return None;
 5343        }
 5344
 5345        let provider = self.semantics_provider.clone()?;
 5346        let buffer = self.buffer.read(cx);
 5347        let newest_selection = self.selections.newest_anchor().clone();
 5348        let cursor_position = newest_selection.head();
 5349        let (cursor_buffer, cursor_buffer_position) =
 5350            buffer.text_anchor_for_position(cursor_position, cx)?;
 5351        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5352        if cursor_buffer != tail_buffer {
 5353            return None;
 5354        }
 5355        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5356        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5357            cx.background_executor()
 5358                .timer(Duration::from_millis(debounce))
 5359                .await;
 5360
 5361            let highlights = if let Some(highlights) = cx
 5362                .update(|cx| {
 5363                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5364                })
 5365                .ok()
 5366                .flatten()
 5367            {
 5368                highlights.await.log_err()
 5369            } else {
 5370                None
 5371            };
 5372
 5373            if let Some(highlights) = highlights {
 5374                this.update(cx, |this, cx| {
 5375                    if this.pending_rename.is_some() {
 5376                        return;
 5377                    }
 5378
 5379                    let buffer_id = cursor_position.buffer_id;
 5380                    let buffer = this.buffer.read(cx);
 5381                    if !buffer
 5382                        .text_anchor_for_position(cursor_position, cx)
 5383                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5384                    {
 5385                        return;
 5386                    }
 5387
 5388                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5389                    let mut write_ranges = Vec::new();
 5390                    let mut read_ranges = Vec::new();
 5391                    for highlight in highlights {
 5392                        for (excerpt_id, excerpt_range) in
 5393                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5394                        {
 5395                            let start = highlight
 5396                                .range
 5397                                .start
 5398                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5399                            let end = highlight
 5400                                .range
 5401                                .end
 5402                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5403                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5404                                continue;
 5405                            }
 5406
 5407                            let range = Anchor {
 5408                                buffer_id,
 5409                                excerpt_id,
 5410                                text_anchor: start,
 5411                                diff_base_anchor: None,
 5412                            }..Anchor {
 5413                                buffer_id,
 5414                                excerpt_id,
 5415                                text_anchor: end,
 5416                                diff_base_anchor: None,
 5417                            };
 5418                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5419                                write_ranges.push(range);
 5420                            } else {
 5421                                read_ranges.push(range);
 5422                            }
 5423                        }
 5424                    }
 5425
 5426                    this.highlight_background::<DocumentHighlightRead>(
 5427                        &read_ranges,
 5428                        |theme| theme.editor_document_highlight_read_background,
 5429                        cx,
 5430                    );
 5431                    this.highlight_background::<DocumentHighlightWrite>(
 5432                        &write_ranges,
 5433                        |theme| theme.editor_document_highlight_write_background,
 5434                        cx,
 5435                    );
 5436                    cx.notify();
 5437                })
 5438                .log_err();
 5439            }
 5440        }));
 5441        None
 5442    }
 5443
 5444    fn prepare_highlight_query_from_selection(
 5445        &mut self,
 5446        cx: &mut Context<Editor>,
 5447    ) -> Option<(String, Range<Anchor>)> {
 5448        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5449            return None;
 5450        }
 5451        if !EditorSettings::get_global(cx).selection_highlight {
 5452            return None;
 5453        }
 5454        if self.selections.count() != 1 || self.selections.line_mode {
 5455            return None;
 5456        }
 5457        let selection = self.selections.newest::<Point>(cx);
 5458        if selection.is_empty() || selection.start.row != selection.end.row {
 5459            return None;
 5460        }
 5461        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5462        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5463        let query = multi_buffer_snapshot
 5464            .text_for_range(selection_anchor_range.clone())
 5465            .collect::<String>();
 5466        if query.trim().is_empty() {
 5467            return None;
 5468        }
 5469        Some((query, selection_anchor_range))
 5470    }
 5471
 5472    fn update_selection_occurrence_highlights(
 5473        &mut self,
 5474        query_text: String,
 5475        query_range: Range<Anchor>,
 5476        multi_buffer_range_to_query: Range<Point>,
 5477        use_debounce: bool,
 5478        window: &mut Window,
 5479        cx: &mut Context<Editor>,
 5480    ) -> Task<()> {
 5481        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5482        cx.spawn_in(window, async move |editor, cx| {
 5483            if use_debounce {
 5484                cx.background_executor()
 5485                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5486                    .await;
 5487            }
 5488            let match_task = cx.background_spawn(async move {
 5489                let buffer_ranges = multi_buffer_snapshot
 5490                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5491                    .into_iter()
 5492                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5493                let mut match_ranges = Vec::new();
 5494                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5495                    match_ranges.extend(
 5496                        project::search::SearchQuery::text(
 5497                            query_text.clone(),
 5498                            false,
 5499                            false,
 5500                            false,
 5501                            Default::default(),
 5502                            Default::default(),
 5503                            false,
 5504                            None,
 5505                        )
 5506                        .unwrap()
 5507                        .search(&buffer_snapshot, Some(search_range.clone()))
 5508                        .await
 5509                        .into_iter()
 5510                        .filter_map(|match_range| {
 5511                            let match_start = buffer_snapshot
 5512                                .anchor_after(search_range.start + match_range.start);
 5513                            let match_end =
 5514                                buffer_snapshot.anchor_before(search_range.start + match_range.end);
 5515                            let match_anchor_range = Anchor::range_in_buffer(
 5516                                excerpt_id,
 5517                                buffer_snapshot.remote_id(),
 5518                                match_start..match_end,
 5519                            );
 5520                            (match_anchor_range != query_range).then_some(match_anchor_range)
 5521                        }),
 5522                    );
 5523                }
 5524                match_ranges
 5525            });
 5526            let match_ranges = match_task.await;
 5527            editor
 5528                .update_in(cx, |editor, _, cx| {
 5529                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5530                    if !match_ranges.is_empty() {
 5531                        editor.highlight_background::<SelectedTextHighlight>(
 5532                            &match_ranges,
 5533                            |theme| theme.editor_document_highlight_bracket_background,
 5534                            cx,
 5535                        )
 5536                    }
 5537                })
 5538                .log_err();
 5539        })
 5540    }
 5541
 5542    fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
 5543        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5544        else {
 5545            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5546            self.quick_selection_highlight_task.take();
 5547            self.debounced_selection_highlight_task.take();
 5548            return;
 5549        };
 5550        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5551        if self
 5552            .quick_selection_highlight_task
 5553            .as_ref()
 5554            .map_or(true, |(prev_anchor_range, _)| {
 5555                prev_anchor_range != &query_range
 5556            })
 5557        {
 5558            let multi_buffer_visible_start = self
 5559                .scroll_manager
 5560                .anchor()
 5561                .anchor
 5562                .to_point(&multi_buffer_snapshot);
 5563            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5564                multi_buffer_visible_start
 5565                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5566                Bias::Left,
 5567            );
 5568            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5569            self.quick_selection_highlight_task = Some((
 5570                query_range.clone(),
 5571                self.update_selection_occurrence_highlights(
 5572                    query_text.clone(),
 5573                    query_range.clone(),
 5574                    multi_buffer_visible_range,
 5575                    false,
 5576                    window,
 5577                    cx,
 5578                ),
 5579            ));
 5580        }
 5581        if self
 5582            .debounced_selection_highlight_task
 5583            .as_ref()
 5584            .map_or(true, |(prev_anchor_range, _)| {
 5585                prev_anchor_range != &query_range
 5586            })
 5587        {
 5588            let multi_buffer_start = multi_buffer_snapshot
 5589                .anchor_before(0)
 5590                .to_point(&multi_buffer_snapshot);
 5591            let multi_buffer_end = multi_buffer_snapshot
 5592                .anchor_after(multi_buffer_snapshot.len())
 5593                .to_point(&multi_buffer_snapshot);
 5594            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5595            self.debounced_selection_highlight_task = Some((
 5596                query_range.clone(),
 5597                self.update_selection_occurrence_highlights(
 5598                    query_text,
 5599                    query_range,
 5600                    multi_buffer_full_range,
 5601                    true,
 5602                    window,
 5603                    cx,
 5604                ),
 5605            ));
 5606        }
 5607    }
 5608
 5609    pub fn refresh_inline_completion(
 5610        &mut self,
 5611        debounce: bool,
 5612        user_requested: bool,
 5613        window: &mut Window,
 5614        cx: &mut Context<Self>,
 5615    ) -> Option<()> {
 5616        let provider = self.edit_prediction_provider()?;
 5617        let cursor = self.selections.newest_anchor().head();
 5618        let (buffer, cursor_buffer_position) =
 5619            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5620
 5621        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5622            self.discard_inline_completion(false, cx);
 5623            return None;
 5624        }
 5625
 5626        if !user_requested
 5627            && (!self.should_show_edit_predictions()
 5628                || !self.is_focused(window)
 5629                || buffer.read(cx).is_empty())
 5630        {
 5631            self.discard_inline_completion(false, cx);
 5632            return None;
 5633        }
 5634
 5635        self.update_visible_inline_completion(window, cx);
 5636        provider.refresh(
 5637            self.project.clone(),
 5638            buffer,
 5639            cursor_buffer_position,
 5640            debounce,
 5641            cx,
 5642        );
 5643        Some(())
 5644    }
 5645
 5646    fn show_edit_predictions_in_menu(&self) -> bool {
 5647        match self.edit_prediction_settings {
 5648            EditPredictionSettings::Disabled => false,
 5649            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5650        }
 5651    }
 5652
 5653    pub fn edit_predictions_enabled(&self) -> bool {
 5654        match self.edit_prediction_settings {
 5655            EditPredictionSettings::Disabled => false,
 5656            EditPredictionSettings::Enabled { .. } => true,
 5657        }
 5658    }
 5659
 5660    fn edit_prediction_requires_modifier(&self) -> bool {
 5661        match self.edit_prediction_settings {
 5662            EditPredictionSettings::Disabled => false,
 5663            EditPredictionSettings::Enabled {
 5664                preview_requires_modifier,
 5665                ..
 5666            } => preview_requires_modifier,
 5667        }
 5668    }
 5669
 5670    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5671        if self.edit_prediction_provider.is_none() {
 5672            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5673        } else {
 5674            let selection = self.selections.newest_anchor();
 5675            let cursor = selection.head();
 5676
 5677            if let Some((buffer, cursor_buffer_position)) =
 5678                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5679            {
 5680                self.edit_prediction_settings =
 5681                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5682            }
 5683        }
 5684    }
 5685
 5686    fn edit_prediction_settings_at_position(
 5687        &self,
 5688        buffer: &Entity<Buffer>,
 5689        buffer_position: language::Anchor,
 5690        cx: &App,
 5691    ) -> EditPredictionSettings {
 5692        if !self.mode.is_full()
 5693            || !self.show_inline_completions_override.unwrap_or(true)
 5694            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5695        {
 5696            return EditPredictionSettings::Disabled;
 5697        }
 5698
 5699        let buffer = buffer.read(cx);
 5700
 5701        let file = buffer.file();
 5702
 5703        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5704            return EditPredictionSettings::Disabled;
 5705        };
 5706
 5707        let by_provider = matches!(
 5708            self.menu_inline_completions_policy,
 5709            MenuInlineCompletionsPolicy::ByProvider
 5710        );
 5711
 5712        let show_in_menu = by_provider
 5713            && self
 5714                .edit_prediction_provider
 5715                .as_ref()
 5716                .map_or(false, |provider| {
 5717                    provider.provider.show_completions_in_menu()
 5718                });
 5719
 5720        let preview_requires_modifier =
 5721            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5722
 5723        EditPredictionSettings::Enabled {
 5724            show_in_menu,
 5725            preview_requires_modifier,
 5726        }
 5727    }
 5728
 5729    fn should_show_edit_predictions(&self) -> bool {
 5730        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5731    }
 5732
 5733    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5734        matches!(
 5735            self.edit_prediction_preview,
 5736            EditPredictionPreview::Active { .. }
 5737        )
 5738    }
 5739
 5740    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5741        let cursor = self.selections.newest_anchor().head();
 5742        if let Some((buffer, cursor_position)) =
 5743            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5744        {
 5745            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5746        } else {
 5747            false
 5748        }
 5749    }
 5750
 5751    fn edit_predictions_enabled_in_buffer(
 5752        &self,
 5753        buffer: &Entity<Buffer>,
 5754        buffer_position: language::Anchor,
 5755        cx: &App,
 5756    ) -> bool {
 5757        maybe!({
 5758            if self.read_only(cx) {
 5759                return Some(false);
 5760            }
 5761            let provider = self.edit_prediction_provider()?;
 5762            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5763                return Some(false);
 5764            }
 5765            let buffer = buffer.read(cx);
 5766            let Some(file) = buffer.file() else {
 5767                return Some(true);
 5768            };
 5769            let settings = all_language_settings(Some(file), cx);
 5770            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5771        })
 5772        .unwrap_or(false)
 5773    }
 5774
 5775    fn cycle_inline_completion(
 5776        &mut self,
 5777        direction: Direction,
 5778        window: &mut Window,
 5779        cx: &mut Context<Self>,
 5780    ) -> Option<()> {
 5781        let provider = self.edit_prediction_provider()?;
 5782        let cursor = self.selections.newest_anchor().head();
 5783        let (buffer, cursor_buffer_position) =
 5784            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5785        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5786            return None;
 5787        }
 5788
 5789        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5790        self.update_visible_inline_completion(window, cx);
 5791
 5792        Some(())
 5793    }
 5794
 5795    pub fn show_inline_completion(
 5796        &mut self,
 5797        _: &ShowEditPrediction,
 5798        window: &mut Window,
 5799        cx: &mut Context<Self>,
 5800    ) {
 5801        if !self.has_active_inline_completion() {
 5802            self.refresh_inline_completion(false, true, window, cx);
 5803            return;
 5804        }
 5805
 5806        self.update_visible_inline_completion(window, cx);
 5807    }
 5808
 5809    pub fn display_cursor_names(
 5810        &mut self,
 5811        _: &DisplayCursorNames,
 5812        window: &mut Window,
 5813        cx: &mut Context<Self>,
 5814    ) {
 5815        self.show_cursor_names(window, cx);
 5816    }
 5817
 5818    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5819        self.show_cursor_names = true;
 5820        cx.notify();
 5821        cx.spawn_in(window, async move |this, cx| {
 5822            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5823            this.update(cx, |this, cx| {
 5824                this.show_cursor_names = false;
 5825                cx.notify()
 5826            })
 5827            .ok()
 5828        })
 5829        .detach();
 5830    }
 5831
 5832    pub fn next_edit_prediction(
 5833        &mut self,
 5834        _: &NextEditPrediction,
 5835        window: &mut Window,
 5836        cx: &mut Context<Self>,
 5837    ) {
 5838        if self.has_active_inline_completion() {
 5839            self.cycle_inline_completion(Direction::Next, window, cx);
 5840        } else {
 5841            let is_copilot_disabled = self
 5842                .refresh_inline_completion(false, true, window, cx)
 5843                .is_none();
 5844            if is_copilot_disabled {
 5845                cx.propagate();
 5846            }
 5847        }
 5848    }
 5849
 5850    pub fn previous_edit_prediction(
 5851        &mut self,
 5852        _: &PreviousEditPrediction,
 5853        window: &mut Window,
 5854        cx: &mut Context<Self>,
 5855    ) {
 5856        if self.has_active_inline_completion() {
 5857            self.cycle_inline_completion(Direction::Prev, window, cx);
 5858        } else {
 5859            let is_copilot_disabled = self
 5860                .refresh_inline_completion(false, true, window, cx)
 5861                .is_none();
 5862            if is_copilot_disabled {
 5863                cx.propagate();
 5864            }
 5865        }
 5866    }
 5867
 5868    pub fn accept_edit_prediction(
 5869        &mut self,
 5870        _: &AcceptEditPrediction,
 5871        window: &mut Window,
 5872        cx: &mut Context<Self>,
 5873    ) {
 5874        if self.show_edit_predictions_in_menu() {
 5875            self.hide_context_menu(window, cx);
 5876        }
 5877
 5878        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5879            return;
 5880        };
 5881
 5882        self.report_inline_completion_event(
 5883            active_inline_completion.completion_id.clone(),
 5884            true,
 5885            cx,
 5886        );
 5887
 5888        match &active_inline_completion.completion {
 5889            InlineCompletion::Move { target, .. } => {
 5890                let target = *target;
 5891
 5892                if let Some(position_map) = &self.last_position_map {
 5893                    if position_map
 5894                        .visible_row_range
 5895                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5896                        || !self.edit_prediction_requires_modifier()
 5897                    {
 5898                        self.unfold_ranges(&[target..target], true, false, cx);
 5899                        // Note that this is also done in vim's handler of the Tab action.
 5900                        self.change_selections(
 5901                            Some(Autoscroll::newest()),
 5902                            window,
 5903                            cx,
 5904                            |selections| {
 5905                                selections.select_anchor_ranges([target..target]);
 5906                            },
 5907                        );
 5908                        self.clear_row_highlights::<EditPredictionPreview>();
 5909
 5910                        self.edit_prediction_preview
 5911                            .set_previous_scroll_position(None);
 5912                    } else {
 5913                        self.edit_prediction_preview
 5914                            .set_previous_scroll_position(Some(
 5915                                position_map.snapshot.scroll_anchor,
 5916                            ));
 5917
 5918                        self.highlight_rows::<EditPredictionPreview>(
 5919                            target..target,
 5920                            cx.theme().colors().editor_highlighted_line_background,
 5921                            true,
 5922                            cx,
 5923                        );
 5924                        self.request_autoscroll(Autoscroll::fit(), cx);
 5925                    }
 5926                }
 5927            }
 5928            InlineCompletion::Edit { edits, .. } => {
 5929                if let Some(provider) = self.edit_prediction_provider() {
 5930                    provider.accept(cx);
 5931                }
 5932
 5933                let snapshot = self.buffer.read(cx).snapshot(cx);
 5934                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5935
 5936                self.buffer.update(cx, |buffer, cx| {
 5937                    buffer.edit(edits.iter().cloned(), None, cx)
 5938                });
 5939
 5940                self.change_selections(None, window, cx, |s| {
 5941                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5942                });
 5943
 5944                self.update_visible_inline_completion(window, cx);
 5945                if self.active_inline_completion.is_none() {
 5946                    self.refresh_inline_completion(true, true, window, cx);
 5947                }
 5948
 5949                cx.notify();
 5950            }
 5951        }
 5952
 5953        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5954    }
 5955
 5956    pub fn accept_partial_inline_completion(
 5957        &mut self,
 5958        _: &AcceptPartialEditPrediction,
 5959        window: &mut Window,
 5960        cx: &mut Context<Self>,
 5961    ) {
 5962        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5963            return;
 5964        };
 5965        if self.selections.count() != 1 {
 5966            return;
 5967        }
 5968
 5969        self.report_inline_completion_event(
 5970            active_inline_completion.completion_id.clone(),
 5971            true,
 5972            cx,
 5973        );
 5974
 5975        match &active_inline_completion.completion {
 5976            InlineCompletion::Move { target, .. } => {
 5977                let target = *target;
 5978                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5979                    selections.select_anchor_ranges([target..target]);
 5980                });
 5981            }
 5982            InlineCompletion::Edit { edits, .. } => {
 5983                // Find an insertion that starts at the cursor position.
 5984                let snapshot = self.buffer.read(cx).snapshot(cx);
 5985                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5986                let insertion = edits.iter().find_map(|(range, text)| {
 5987                    let range = range.to_offset(&snapshot);
 5988                    if range.is_empty() && range.start == cursor_offset {
 5989                        Some(text)
 5990                    } else {
 5991                        None
 5992                    }
 5993                });
 5994
 5995                if let Some(text) = insertion {
 5996                    let mut partial_completion = text
 5997                        .chars()
 5998                        .by_ref()
 5999                        .take_while(|c| c.is_alphabetic())
 6000                        .collect::<String>();
 6001                    if partial_completion.is_empty() {
 6002                        partial_completion = text
 6003                            .chars()
 6004                            .by_ref()
 6005                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6006                            .collect::<String>();
 6007                    }
 6008
 6009                    cx.emit(EditorEvent::InputHandled {
 6010                        utf16_range_to_replace: None,
 6011                        text: partial_completion.clone().into(),
 6012                    });
 6013
 6014                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6015
 6016                    self.refresh_inline_completion(true, true, window, cx);
 6017                    cx.notify();
 6018                } else {
 6019                    self.accept_edit_prediction(&Default::default(), window, cx);
 6020                }
 6021            }
 6022        }
 6023    }
 6024
 6025    fn discard_inline_completion(
 6026        &mut self,
 6027        should_report_inline_completion_event: bool,
 6028        cx: &mut Context<Self>,
 6029    ) -> bool {
 6030        if should_report_inline_completion_event {
 6031            let completion_id = self
 6032                .active_inline_completion
 6033                .as_ref()
 6034                .and_then(|active_completion| active_completion.completion_id.clone());
 6035
 6036            self.report_inline_completion_event(completion_id, false, cx);
 6037        }
 6038
 6039        if let Some(provider) = self.edit_prediction_provider() {
 6040            provider.discard(cx);
 6041        }
 6042
 6043        self.take_active_inline_completion(cx)
 6044    }
 6045
 6046    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6047        let Some(provider) = self.edit_prediction_provider() else {
 6048            return;
 6049        };
 6050
 6051        let Some((_, buffer, _)) = self
 6052            .buffer
 6053            .read(cx)
 6054            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6055        else {
 6056            return;
 6057        };
 6058
 6059        let extension = buffer
 6060            .read(cx)
 6061            .file()
 6062            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6063
 6064        let event_type = match accepted {
 6065            true => "Edit Prediction Accepted",
 6066            false => "Edit Prediction Discarded",
 6067        };
 6068        telemetry::event!(
 6069            event_type,
 6070            provider = provider.name(),
 6071            prediction_id = id,
 6072            suggestion_accepted = accepted,
 6073            file_extension = extension,
 6074        );
 6075    }
 6076
 6077    pub fn has_active_inline_completion(&self) -> bool {
 6078        self.active_inline_completion.is_some()
 6079    }
 6080
 6081    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6082        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6083            return false;
 6084        };
 6085
 6086        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6087        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6088        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6089        true
 6090    }
 6091
 6092    /// Returns true when we're displaying the edit prediction popover below the cursor
 6093    /// like we are not previewing and the LSP autocomplete menu is visible
 6094    /// or we are in `when_holding_modifier` mode.
 6095    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6096        if self.edit_prediction_preview_is_active()
 6097            || !self.show_edit_predictions_in_menu()
 6098            || !self.edit_predictions_enabled()
 6099        {
 6100            return false;
 6101        }
 6102
 6103        if self.has_visible_completions_menu() {
 6104            return true;
 6105        }
 6106
 6107        has_completion && self.edit_prediction_requires_modifier()
 6108    }
 6109
 6110    fn handle_modifiers_changed(
 6111        &mut self,
 6112        modifiers: Modifiers,
 6113        position_map: &PositionMap,
 6114        window: &mut Window,
 6115        cx: &mut Context<Self>,
 6116    ) {
 6117        if self.show_edit_predictions_in_menu() {
 6118            self.update_edit_prediction_preview(&modifiers, window, cx);
 6119        }
 6120
 6121        self.update_selection_mode(&modifiers, position_map, window, cx);
 6122
 6123        let mouse_position = window.mouse_position();
 6124        if !position_map.text_hitbox.is_hovered(window) {
 6125            return;
 6126        }
 6127
 6128        self.update_hovered_link(
 6129            position_map.point_for_position(mouse_position),
 6130            &position_map.snapshot,
 6131            modifiers,
 6132            window,
 6133            cx,
 6134        )
 6135    }
 6136
 6137    fn update_selection_mode(
 6138        &mut self,
 6139        modifiers: &Modifiers,
 6140        position_map: &PositionMap,
 6141        window: &mut Window,
 6142        cx: &mut Context<Self>,
 6143    ) {
 6144        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6145            return;
 6146        }
 6147
 6148        let mouse_position = window.mouse_position();
 6149        let point_for_position = position_map.point_for_position(mouse_position);
 6150        let position = point_for_position.previous_valid;
 6151
 6152        self.select(
 6153            SelectPhase::BeginColumnar {
 6154                position,
 6155                reset: false,
 6156                goal_column: point_for_position.exact_unclipped.column(),
 6157            },
 6158            window,
 6159            cx,
 6160        );
 6161    }
 6162
 6163    fn update_edit_prediction_preview(
 6164        &mut self,
 6165        modifiers: &Modifiers,
 6166        window: &mut Window,
 6167        cx: &mut Context<Self>,
 6168    ) {
 6169        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6170        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6171            return;
 6172        };
 6173
 6174        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6175            if matches!(
 6176                self.edit_prediction_preview,
 6177                EditPredictionPreview::Inactive { .. }
 6178            ) {
 6179                self.edit_prediction_preview = EditPredictionPreview::Active {
 6180                    previous_scroll_position: None,
 6181                    since: Instant::now(),
 6182                };
 6183
 6184                self.update_visible_inline_completion(window, cx);
 6185                cx.notify();
 6186            }
 6187        } else if let EditPredictionPreview::Active {
 6188            previous_scroll_position,
 6189            since,
 6190        } = self.edit_prediction_preview
 6191        {
 6192            if let (Some(previous_scroll_position), Some(position_map)) =
 6193                (previous_scroll_position, self.last_position_map.as_ref())
 6194            {
 6195                self.set_scroll_position(
 6196                    previous_scroll_position
 6197                        .scroll_position(&position_map.snapshot.display_snapshot),
 6198                    window,
 6199                    cx,
 6200                );
 6201            }
 6202
 6203            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6204                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6205            };
 6206            self.clear_row_highlights::<EditPredictionPreview>();
 6207            self.update_visible_inline_completion(window, cx);
 6208            cx.notify();
 6209        }
 6210    }
 6211
 6212    fn update_visible_inline_completion(
 6213        &mut self,
 6214        _window: &mut Window,
 6215        cx: &mut Context<Self>,
 6216    ) -> Option<()> {
 6217        let selection = self.selections.newest_anchor();
 6218        let cursor = selection.head();
 6219        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6220        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6221        let excerpt_id = cursor.excerpt_id;
 6222
 6223        let show_in_menu = self.show_edit_predictions_in_menu();
 6224        let completions_menu_has_precedence = !show_in_menu
 6225            && (self.context_menu.borrow().is_some()
 6226                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6227
 6228        if completions_menu_has_precedence
 6229            || !offset_selection.is_empty()
 6230            || self
 6231                .active_inline_completion
 6232                .as_ref()
 6233                .map_or(false, |completion| {
 6234                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6235                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6236                    !invalidation_range.contains(&offset_selection.head())
 6237                })
 6238        {
 6239            self.discard_inline_completion(false, cx);
 6240            return None;
 6241        }
 6242
 6243        self.take_active_inline_completion(cx);
 6244        let Some(provider) = self.edit_prediction_provider() else {
 6245            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6246            return None;
 6247        };
 6248
 6249        let (buffer, cursor_buffer_position) =
 6250            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6251
 6252        self.edit_prediction_settings =
 6253            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6254
 6255        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6256
 6257        if self.edit_prediction_indent_conflict {
 6258            let cursor_point = cursor.to_point(&multibuffer);
 6259
 6260            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6261
 6262            if let Some((_, indent)) = indents.iter().next() {
 6263                if indent.len == cursor_point.column {
 6264                    self.edit_prediction_indent_conflict = false;
 6265                }
 6266            }
 6267        }
 6268
 6269        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6270        let edits = inline_completion
 6271            .edits
 6272            .into_iter()
 6273            .flat_map(|(range, new_text)| {
 6274                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6275                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6276                Some((start..end, new_text))
 6277            })
 6278            .collect::<Vec<_>>();
 6279        if edits.is_empty() {
 6280            return None;
 6281        }
 6282
 6283        let first_edit_start = edits.first().unwrap().0.start;
 6284        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6285        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6286
 6287        let last_edit_end = edits.last().unwrap().0.end;
 6288        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6289        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6290
 6291        let cursor_row = cursor.to_point(&multibuffer).row;
 6292
 6293        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6294
 6295        let mut inlay_ids = Vec::new();
 6296        let invalidation_row_range;
 6297        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6298            Some(cursor_row..edit_end_row)
 6299        } else if cursor_row > edit_end_row {
 6300            Some(edit_start_row..cursor_row)
 6301        } else {
 6302            None
 6303        };
 6304        let is_move =
 6305            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6306        let completion = if is_move {
 6307            invalidation_row_range =
 6308                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6309            let target = first_edit_start;
 6310            InlineCompletion::Move { target, snapshot }
 6311        } else {
 6312            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6313                && !self.inline_completions_hidden_for_vim_mode;
 6314
 6315            if show_completions_in_buffer {
 6316                if edits
 6317                    .iter()
 6318                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6319                {
 6320                    let mut inlays = Vec::new();
 6321                    for (range, new_text) in &edits {
 6322                        let inlay = Inlay::inline_completion(
 6323                            post_inc(&mut self.next_inlay_id),
 6324                            range.start,
 6325                            new_text.as_str(),
 6326                        );
 6327                        inlay_ids.push(inlay.id);
 6328                        inlays.push(inlay);
 6329                    }
 6330
 6331                    self.splice_inlays(&[], inlays, cx);
 6332                } else {
 6333                    let background_color = cx.theme().status().deleted_background;
 6334                    self.highlight_text::<InlineCompletionHighlight>(
 6335                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6336                        HighlightStyle {
 6337                            background_color: Some(background_color),
 6338                            ..Default::default()
 6339                        },
 6340                        cx,
 6341                    );
 6342                }
 6343            }
 6344
 6345            invalidation_row_range = edit_start_row..edit_end_row;
 6346
 6347            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6348                if provider.show_tab_accept_marker() {
 6349                    EditDisplayMode::TabAccept
 6350                } else {
 6351                    EditDisplayMode::Inline
 6352                }
 6353            } else {
 6354                EditDisplayMode::DiffPopover
 6355            };
 6356
 6357            InlineCompletion::Edit {
 6358                edits,
 6359                edit_preview: inline_completion.edit_preview,
 6360                display_mode,
 6361                snapshot,
 6362            }
 6363        };
 6364
 6365        let invalidation_range = multibuffer
 6366            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6367            ..multibuffer.anchor_after(Point::new(
 6368                invalidation_row_range.end,
 6369                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6370            ));
 6371
 6372        self.stale_inline_completion_in_menu = None;
 6373        self.active_inline_completion = Some(InlineCompletionState {
 6374            inlay_ids,
 6375            completion,
 6376            completion_id: inline_completion.id,
 6377            invalidation_range,
 6378        });
 6379
 6380        cx.notify();
 6381
 6382        Some(())
 6383    }
 6384
 6385    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6386        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6387    }
 6388
 6389    fn render_code_actions_indicator(
 6390        &self,
 6391        _style: &EditorStyle,
 6392        row: DisplayRow,
 6393        is_active: bool,
 6394        breakpoint: Option<&(Anchor, Breakpoint)>,
 6395        cx: &mut Context<Self>,
 6396    ) -> Option<IconButton> {
 6397        let color = Color::Muted;
 6398        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6399        let show_tooltip = !self.context_menu_visible();
 6400
 6401        if self.available_code_actions.is_some() {
 6402            Some(
 6403                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6404                    .shape(ui::IconButtonShape::Square)
 6405                    .icon_size(IconSize::XSmall)
 6406                    .icon_color(color)
 6407                    .toggle_state(is_active)
 6408                    .when(show_tooltip, |this| {
 6409                        this.tooltip({
 6410                            let focus_handle = self.focus_handle.clone();
 6411                            move |window, cx| {
 6412                                Tooltip::for_action_in(
 6413                                    "Toggle Code Actions",
 6414                                    &ToggleCodeActions {
 6415                                        deployed_from_indicator: None,
 6416                                    },
 6417                                    &focus_handle,
 6418                                    window,
 6419                                    cx,
 6420                                )
 6421                            }
 6422                        })
 6423                    })
 6424                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6425                        window.focus(&editor.focus_handle(cx));
 6426                        editor.toggle_code_actions(
 6427                            &ToggleCodeActions {
 6428                                deployed_from_indicator: Some(row),
 6429                            },
 6430                            window,
 6431                            cx,
 6432                        );
 6433                    }))
 6434                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6435                        editor.set_breakpoint_context_menu(
 6436                            row,
 6437                            position,
 6438                            event.down.position,
 6439                            window,
 6440                            cx,
 6441                        );
 6442                    })),
 6443            )
 6444        } else {
 6445            None
 6446        }
 6447    }
 6448
 6449    fn clear_tasks(&mut self) {
 6450        self.tasks.clear()
 6451    }
 6452
 6453    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6454        if self.tasks.insert(key, value).is_some() {
 6455            // This case should hopefully be rare, but just in case...
 6456            log::error!(
 6457                "multiple different run targets found on a single line, only the last target will be rendered"
 6458            )
 6459        }
 6460    }
 6461
 6462    /// Get all display points of breakpoints that will be rendered within editor
 6463    ///
 6464    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6465    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6466    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6467    fn active_breakpoints(
 6468        &self,
 6469        range: Range<DisplayRow>,
 6470        window: &mut Window,
 6471        cx: &mut Context<Self>,
 6472    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6473        let mut breakpoint_display_points = HashMap::default();
 6474
 6475        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6476            return breakpoint_display_points;
 6477        };
 6478
 6479        let snapshot = self.snapshot(window, cx);
 6480
 6481        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6482        let Some(project) = self.project.as_ref() else {
 6483            return breakpoint_display_points;
 6484        };
 6485
 6486        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6487            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6488
 6489        for (buffer_snapshot, range, excerpt_id) in
 6490            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6491        {
 6492            let Some(buffer) = project.read_with(cx, |this, cx| {
 6493                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6494            }) else {
 6495                continue;
 6496            };
 6497            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6498                &buffer,
 6499                Some(
 6500                    buffer_snapshot.anchor_before(range.start)
 6501                        ..buffer_snapshot.anchor_after(range.end),
 6502                ),
 6503                buffer_snapshot,
 6504                cx,
 6505            );
 6506            for (anchor, breakpoint) in breakpoints {
 6507                let multi_buffer_anchor =
 6508                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6509                let position = multi_buffer_anchor
 6510                    .to_point(&multi_buffer_snapshot)
 6511                    .to_display_point(&snapshot);
 6512
 6513                breakpoint_display_points
 6514                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6515            }
 6516        }
 6517
 6518        breakpoint_display_points
 6519    }
 6520
 6521    fn breakpoint_context_menu(
 6522        &self,
 6523        anchor: Anchor,
 6524        window: &mut Window,
 6525        cx: &mut Context<Self>,
 6526    ) -> Entity<ui::ContextMenu> {
 6527        let weak_editor = cx.weak_entity();
 6528        let focus_handle = self.focus_handle(cx);
 6529
 6530        let row = self
 6531            .buffer
 6532            .read(cx)
 6533            .snapshot(cx)
 6534            .summary_for_anchor::<Point>(&anchor)
 6535            .row;
 6536
 6537        let breakpoint = self
 6538            .breakpoint_at_row(row, window, cx)
 6539            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6540
 6541        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6542            "Edit Log Breakpoint"
 6543        } else {
 6544            "Set Log Breakpoint"
 6545        };
 6546
 6547        let condition_breakpoint_msg = if breakpoint
 6548            .as_ref()
 6549            .is_some_and(|bp| bp.1.condition.is_some())
 6550        {
 6551            "Edit Condition Breakpoint"
 6552        } else {
 6553            "Set Condition Breakpoint"
 6554        };
 6555
 6556        let hit_condition_breakpoint_msg = if breakpoint
 6557            .as_ref()
 6558            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6559        {
 6560            "Edit Hit Condition Breakpoint"
 6561        } else {
 6562            "Set Hit Condition Breakpoint"
 6563        };
 6564
 6565        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6566            "Unset Breakpoint"
 6567        } else {
 6568            "Set Breakpoint"
 6569        };
 6570
 6571        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6572            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6573
 6574        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6575            BreakpointState::Enabled => Some("Disable"),
 6576            BreakpointState::Disabled => Some("Enable"),
 6577        });
 6578
 6579        let (anchor, breakpoint) =
 6580            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6581
 6582        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6583            menu.on_blur_subscription(Subscription::new(|| {}))
 6584                .context(focus_handle)
 6585                .when(run_to_cursor, |this| {
 6586                    let weak_editor = weak_editor.clone();
 6587                    this.entry("Run to cursor", None, move |window, cx| {
 6588                        weak_editor
 6589                            .update(cx, |editor, cx| {
 6590                                editor.change_selections(None, window, cx, |s| {
 6591                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6592                                });
 6593                            })
 6594                            .ok();
 6595
 6596                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6597                    })
 6598                    .separator()
 6599                })
 6600                .when_some(toggle_state_msg, |this, msg| {
 6601                    this.entry(msg, None, {
 6602                        let weak_editor = weak_editor.clone();
 6603                        let breakpoint = breakpoint.clone();
 6604                        move |_window, cx| {
 6605                            weak_editor
 6606                                .update(cx, |this, cx| {
 6607                                    this.edit_breakpoint_at_anchor(
 6608                                        anchor,
 6609                                        breakpoint.as_ref().clone(),
 6610                                        BreakpointEditAction::InvertState,
 6611                                        cx,
 6612                                    );
 6613                                })
 6614                                .log_err();
 6615                        }
 6616                    })
 6617                })
 6618                .entry(set_breakpoint_msg, None, {
 6619                    let weak_editor = weak_editor.clone();
 6620                    let breakpoint = breakpoint.clone();
 6621                    move |_window, cx| {
 6622                        weak_editor
 6623                            .update(cx, |this, cx| {
 6624                                this.edit_breakpoint_at_anchor(
 6625                                    anchor,
 6626                                    breakpoint.as_ref().clone(),
 6627                                    BreakpointEditAction::Toggle,
 6628                                    cx,
 6629                                );
 6630                            })
 6631                            .log_err();
 6632                    }
 6633                })
 6634                .entry(log_breakpoint_msg, None, {
 6635                    let breakpoint = breakpoint.clone();
 6636                    let weak_editor = weak_editor.clone();
 6637                    move |window, cx| {
 6638                        weak_editor
 6639                            .update(cx, |this, cx| {
 6640                                this.add_edit_breakpoint_block(
 6641                                    anchor,
 6642                                    breakpoint.as_ref(),
 6643                                    BreakpointPromptEditAction::Log,
 6644                                    window,
 6645                                    cx,
 6646                                );
 6647                            })
 6648                            .log_err();
 6649                    }
 6650                })
 6651                .entry(condition_breakpoint_msg, None, {
 6652                    let breakpoint = breakpoint.clone();
 6653                    let weak_editor = weak_editor.clone();
 6654                    move |window, cx| {
 6655                        weak_editor
 6656                            .update(cx, |this, cx| {
 6657                                this.add_edit_breakpoint_block(
 6658                                    anchor,
 6659                                    breakpoint.as_ref(),
 6660                                    BreakpointPromptEditAction::Condition,
 6661                                    window,
 6662                                    cx,
 6663                                );
 6664                            })
 6665                            .log_err();
 6666                    }
 6667                })
 6668                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6669                    weak_editor
 6670                        .update(cx, |this, cx| {
 6671                            this.add_edit_breakpoint_block(
 6672                                anchor,
 6673                                breakpoint.as_ref(),
 6674                                BreakpointPromptEditAction::HitCondition,
 6675                                window,
 6676                                cx,
 6677                            );
 6678                        })
 6679                        .log_err();
 6680                })
 6681        })
 6682    }
 6683
 6684    fn render_breakpoint(
 6685        &self,
 6686        position: Anchor,
 6687        row: DisplayRow,
 6688        breakpoint: &Breakpoint,
 6689        cx: &mut Context<Self>,
 6690    ) -> IconButton {
 6691        let (color, icon) = {
 6692            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6693                (false, false) => ui::IconName::DebugBreakpoint,
 6694                (true, false) => ui::IconName::DebugLogBreakpoint,
 6695                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6696                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6697            };
 6698
 6699            let color = if self
 6700                .gutter_breakpoint_indicator
 6701                .0
 6702                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6703            {
 6704                Color::Hint
 6705            } else {
 6706                Color::Debugger
 6707            };
 6708
 6709            (color, icon)
 6710        };
 6711
 6712        let breakpoint = Arc::from(breakpoint.clone());
 6713
 6714        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6715            .icon_size(IconSize::XSmall)
 6716            .size(ui::ButtonSize::None)
 6717            .icon_color(color)
 6718            .style(ButtonStyle::Transparent)
 6719            .on_click(cx.listener({
 6720                let breakpoint = breakpoint.clone();
 6721
 6722                move |editor, event: &ClickEvent, window, cx| {
 6723                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6724                        BreakpointEditAction::InvertState
 6725                    } else {
 6726                        BreakpointEditAction::Toggle
 6727                    };
 6728
 6729                    window.focus(&editor.focus_handle(cx));
 6730                    editor.edit_breakpoint_at_anchor(
 6731                        position,
 6732                        breakpoint.as_ref().clone(),
 6733                        edit_action,
 6734                        cx,
 6735                    );
 6736                }
 6737            }))
 6738            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6739                editor.set_breakpoint_context_menu(
 6740                    row,
 6741                    Some(position),
 6742                    event.down.position,
 6743                    window,
 6744                    cx,
 6745                );
 6746            }))
 6747    }
 6748
 6749    fn build_tasks_context(
 6750        project: &Entity<Project>,
 6751        buffer: &Entity<Buffer>,
 6752        buffer_row: u32,
 6753        tasks: &Arc<RunnableTasks>,
 6754        cx: &mut Context<Self>,
 6755    ) -> Task<Option<task::TaskContext>> {
 6756        let position = Point::new(buffer_row, tasks.column);
 6757        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6758        let location = Location {
 6759            buffer: buffer.clone(),
 6760            range: range_start..range_start,
 6761        };
 6762        // Fill in the environmental variables from the tree-sitter captures
 6763        let mut captured_task_variables = TaskVariables::default();
 6764        for (capture_name, value) in tasks.extra_variables.clone() {
 6765            captured_task_variables.insert(
 6766                task::VariableName::Custom(capture_name.into()),
 6767                value.clone(),
 6768            );
 6769        }
 6770        project.update(cx, |project, cx| {
 6771            project.task_store().update(cx, |task_store, cx| {
 6772                task_store.task_context_for_location(captured_task_variables, location, cx)
 6773            })
 6774        })
 6775    }
 6776
 6777    pub fn spawn_nearest_task(
 6778        &mut self,
 6779        action: &SpawnNearestTask,
 6780        window: &mut Window,
 6781        cx: &mut Context<Self>,
 6782    ) {
 6783        let Some((workspace, _)) = self.workspace.clone() else {
 6784            return;
 6785        };
 6786        let Some(project) = self.project.clone() else {
 6787            return;
 6788        };
 6789
 6790        // Try to find a closest, enclosing node using tree-sitter that has a
 6791        // task
 6792        let Some((buffer, buffer_row, tasks)) = self
 6793            .find_enclosing_node_task(cx)
 6794            // Or find the task that's closest in row-distance.
 6795            .or_else(|| self.find_closest_task(cx))
 6796        else {
 6797            return;
 6798        };
 6799
 6800        let reveal_strategy = action.reveal;
 6801        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6802        cx.spawn_in(window, async move |_, cx| {
 6803            let context = task_context.await?;
 6804            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6805
 6806            let resolved = resolved_task.resolved.as_mut()?;
 6807            resolved.reveal = reveal_strategy;
 6808
 6809            workspace
 6810                .update(cx, |workspace, cx| {
 6811                    workspace::tasks::schedule_resolved_task(
 6812                        workspace,
 6813                        task_source_kind,
 6814                        resolved_task,
 6815                        false,
 6816                        cx,
 6817                    );
 6818                })
 6819                .ok()
 6820        })
 6821        .detach();
 6822    }
 6823
 6824    fn find_closest_task(
 6825        &mut self,
 6826        cx: &mut Context<Self>,
 6827    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6828        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6829
 6830        let ((buffer_id, row), tasks) = self
 6831            .tasks
 6832            .iter()
 6833            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6834
 6835        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6836        let tasks = Arc::new(tasks.to_owned());
 6837        Some((buffer, *row, tasks))
 6838    }
 6839
 6840    fn find_enclosing_node_task(
 6841        &mut self,
 6842        cx: &mut Context<Self>,
 6843    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6844        let snapshot = self.buffer.read(cx).snapshot(cx);
 6845        let offset = self.selections.newest::<usize>(cx).head();
 6846        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6847        let buffer_id = excerpt.buffer().remote_id();
 6848
 6849        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6850        let mut cursor = layer.node().walk();
 6851
 6852        while cursor.goto_first_child_for_byte(offset).is_some() {
 6853            if cursor.node().end_byte() == offset {
 6854                cursor.goto_next_sibling();
 6855            }
 6856        }
 6857
 6858        // Ascend to the smallest ancestor that contains the range and has a task.
 6859        loop {
 6860            let node = cursor.node();
 6861            let node_range = node.byte_range();
 6862            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6863
 6864            // Check if this node contains our offset
 6865            if node_range.start <= offset && node_range.end >= offset {
 6866                // If it contains offset, check for task
 6867                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6868                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6869                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6870                }
 6871            }
 6872
 6873            if !cursor.goto_parent() {
 6874                break;
 6875            }
 6876        }
 6877        None
 6878    }
 6879
 6880    fn render_run_indicator(
 6881        &self,
 6882        _style: &EditorStyle,
 6883        is_active: bool,
 6884        row: DisplayRow,
 6885        breakpoint: Option<(Anchor, Breakpoint)>,
 6886        cx: &mut Context<Self>,
 6887    ) -> IconButton {
 6888        let color = Color::Muted;
 6889        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6890
 6891        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6892            .shape(ui::IconButtonShape::Square)
 6893            .icon_size(IconSize::XSmall)
 6894            .icon_color(color)
 6895            .toggle_state(is_active)
 6896            .on_click(cx.listener(move |editor, _e, window, cx| {
 6897                window.focus(&editor.focus_handle(cx));
 6898                editor.toggle_code_actions(
 6899                    &ToggleCodeActions {
 6900                        deployed_from_indicator: Some(row),
 6901                    },
 6902                    window,
 6903                    cx,
 6904                );
 6905            }))
 6906            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6907                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6908            }))
 6909    }
 6910
 6911    pub fn context_menu_visible(&self) -> bool {
 6912        !self.edit_prediction_preview_is_active()
 6913            && self
 6914                .context_menu
 6915                .borrow()
 6916                .as_ref()
 6917                .map_or(false, |menu| menu.visible())
 6918    }
 6919
 6920    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6921        self.context_menu
 6922            .borrow()
 6923            .as_ref()
 6924            .map(|menu| menu.origin())
 6925    }
 6926
 6927    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6928        self.context_menu_options = Some(options);
 6929    }
 6930
 6931    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6932    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6933
 6934    fn render_edit_prediction_popover(
 6935        &mut self,
 6936        text_bounds: &Bounds<Pixels>,
 6937        content_origin: gpui::Point<Pixels>,
 6938        editor_snapshot: &EditorSnapshot,
 6939        visible_row_range: Range<DisplayRow>,
 6940        scroll_top: f32,
 6941        scroll_bottom: f32,
 6942        line_layouts: &[LineWithInvisibles],
 6943        line_height: Pixels,
 6944        scroll_pixel_position: gpui::Point<Pixels>,
 6945        newest_selection_head: Option<DisplayPoint>,
 6946        editor_width: Pixels,
 6947        style: &EditorStyle,
 6948        window: &mut Window,
 6949        cx: &mut App,
 6950    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6951        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6952
 6953        if self.edit_prediction_visible_in_cursor_popover(true) {
 6954            return None;
 6955        }
 6956
 6957        match &active_inline_completion.completion {
 6958            InlineCompletion::Move { target, .. } => {
 6959                let target_display_point = target.to_display_point(editor_snapshot);
 6960
 6961                if self.edit_prediction_requires_modifier() {
 6962                    if !self.edit_prediction_preview_is_active() {
 6963                        return None;
 6964                    }
 6965
 6966                    self.render_edit_prediction_modifier_jump_popover(
 6967                        text_bounds,
 6968                        content_origin,
 6969                        visible_row_range,
 6970                        line_layouts,
 6971                        line_height,
 6972                        scroll_pixel_position,
 6973                        newest_selection_head,
 6974                        target_display_point,
 6975                        window,
 6976                        cx,
 6977                    )
 6978                } else {
 6979                    self.render_edit_prediction_eager_jump_popover(
 6980                        text_bounds,
 6981                        content_origin,
 6982                        editor_snapshot,
 6983                        visible_row_range,
 6984                        scroll_top,
 6985                        scroll_bottom,
 6986                        line_height,
 6987                        scroll_pixel_position,
 6988                        target_display_point,
 6989                        editor_width,
 6990                        window,
 6991                        cx,
 6992                    )
 6993                }
 6994            }
 6995            InlineCompletion::Edit {
 6996                display_mode: EditDisplayMode::Inline,
 6997                ..
 6998            } => None,
 6999            InlineCompletion::Edit {
 7000                display_mode: EditDisplayMode::TabAccept,
 7001                edits,
 7002                ..
 7003            } => {
 7004                let range = &edits.first()?.0;
 7005                let target_display_point = range.end.to_display_point(editor_snapshot);
 7006
 7007                self.render_edit_prediction_end_of_line_popover(
 7008                    "Accept",
 7009                    editor_snapshot,
 7010                    visible_row_range,
 7011                    target_display_point,
 7012                    line_height,
 7013                    scroll_pixel_position,
 7014                    content_origin,
 7015                    editor_width,
 7016                    window,
 7017                    cx,
 7018                )
 7019            }
 7020            InlineCompletion::Edit {
 7021                edits,
 7022                edit_preview,
 7023                display_mode: EditDisplayMode::DiffPopover,
 7024                snapshot,
 7025            } => self.render_edit_prediction_diff_popover(
 7026                text_bounds,
 7027                content_origin,
 7028                editor_snapshot,
 7029                visible_row_range,
 7030                line_layouts,
 7031                line_height,
 7032                scroll_pixel_position,
 7033                newest_selection_head,
 7034                editor_width,
 7035                style,
 7036                edits,
 7037                edit_preview,
 7038                snapshot,
 7039                window,
 7040                cx,
 7041            ),
 7042        }
 7043    }
 7044
 7045    fn render_edit_prediction_modifier_jump_popover(
 7046        &mut self,
 7047        text_bounds: &Bounds<Pixels>,
 7048        content_origin: gpui::Point<Pixels>,
 7049        visible_row_range: Range<DisplayRow>,
 7050        line_layouts: &[LineWithInvisibles],
 7051        line_height: Pixels,
 7052        scroll_pixel_position: gpui::Point<Pixels>,
 7053        newest_selection_head: Option<DisplayPoint>,
 7054        target_display_point: DisplayPoint,
 7055        window: &mut Window,
 7056        cx: &mut App,
 7057    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7058        let scrolled_content_origin =
 7059            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7060
 7061        const SCROLL_PADDING_Y: Pixels = px(12.);
 7062
 7063        if target_display_point.row() < visible_row_range.start {
 7064            return self.render_edit_prediction_scroll_popover(
 7065                |_| SCROLL_PADDING_Y,
 7066                IconName::ArrowUp,
 7067                visible_row_range,
 7068                line_layouts,
 7069                newest_selection_head,
 7070                scrolled_content_origin,
 7071                window,
 7072                cx,
 7073            );
 7074        } else if target_display_point.row() >= visible_row_range.end {
 7075            return self.render_edit_prediction_scroll_popover(
 7076                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7077                IconName::ArrowDown,
 7078                visible_row_range,
 7079                line_layouts,
 7080                newest_selection_head,
 7081                scrolled_content_origin,
 7082                window,
 7083                cx,
 7084            );
 7085        }
 7086
 7087        const POLE_WIDTH: Pixels = px(2.);
 7088
 7089        let line_layout =
 7090            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7091        let target_column = target_display_point.column() as usize;
 7092
 7093        let target_x = line_layout.x_for_index(target_column);
 7094        let target_y =
 7095            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7096
 7097        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7098
 7099        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7100        border_color.l += 0.001;
 7101
 7102        let mut element = v_flex()
 7103            .items_end()
 7104            .when(flag_on_right, |el| el.items_start())
 7105            .child(if flag_on_right {
 7106                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7107                    .rounded_bl(px(0.))
 7108                    .rounded_tl(px(0.))
 7109                    .border_l_2()
 7110                    .border_color(border_color)
 7111            } else {
 7112                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7113                    .rounded_br(px(0.))
 7114                    .rounded_tr(px(0.))
 7115                    .border_r_2()
 7116                    .border_color(border_color)
 7117            })
 7118            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7119            .into_any();
 7120
 7121        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7122
 7123        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7124            - point(
 7125                if flag_on_right {
 7126                    POLE_WIDTH
 7127                } else {
 7128                    size.width - POLE_WIDTH
 7129                },
 7130                size.height - line_height,
 7131            );
 7132
 7133        origin.x = origin.x.max(content_origin.x);
 7134
 7135        element.prepaint_at(origin, window, cx);
 7136
 7137        Some((element, origin))
 7138    }
 7139
 7140    fn render_edit_prediction_scroll_popover(
 7141        &mut self,
 7142        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7143        scroll_icon: IconName,
 7144        visible_row_range: Range<DisplayRow>,
 7145        line_layouts: &[LineWithInvisibles],
 7146        newest_selection_head: Option<DisplayPoint>,
 7147        scrolled_content_origin: gpui::Point<Pixels>,
 7148        window: &mut Window,
 7149        cx: &mut App,
 7150    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7151        let mut element = self
 7152            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7153            .into_any();
 7154
 7155        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7156
 7157        let cursor = newest_selection_head?;
 7158        let cursor_row_layout =
 7159            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7160        let cursor_column = cursor.column() as usize;
 7161
 7162        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7163
 7164        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7165
 7166        element.prepaint_at(origin, window, cx);
 7167        Some((element, origin))
 7168    }
 7169
 7170    fn render_edit_prediction_eager_jump_popover(
 7171        &mut self,
 7172        text_bounds: &Bounds<Pixels>,
 7173        content_origin: gpui::Point<Pixels>,
 7174        editor_snapshot: &EditorSnapshot,
 7175        visible_row_range: Range<DisplayRow>,
 7176        scroll_top: f32,
 7177        scroll_bottom: f32,
 7178        line_height: Pixels,
 7179        scroll_pixel_position: gpui::Point<Pixels>,
 7180        target_display_point: DisplayPoint,
 7181        editor_width: Pixels,
 7182        window: &mut Window,
 7183        cx: &mut App,
 7184    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7185        if target_display_point.row().as_f32() < scroll_top {
 7186            let mut element = self
 7187                .render_edit_prediction_line_popover(
 7188                    "Jump to Edit",
 7189                    Some(IconName::ArrowUp),
 7190                    window,
 7191                    cx,
 7192                )?
 7193                .into_any();
 7194
 7195            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7196            let offset = point(
 7197                (text_bounds.size.width - size.width) / 2.,
 7198                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7199            );
 7200
 7201            let origin = text_bounds.origin + offset;
 7202            element.prepaint_at(origin, window, cx);
 7203            Some((element, origin))
 7204        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7205            let mut element = self
 7206                .render_edit_prediction_line_popover(
 7207                    "Jump to Edit",
 7208                    Some(IconName::ArrowDown),
 7209                    window,
 7210                    cx,
 7211                )?
 7212                .into_any();
 7213
 7214            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7215            let offset = point(
 7216                (text_bounds.size.width - size.width) / 2.,
 7217                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7218            );
 7219
 7220            let origin = text_bounds.origin + offset;
 7221            element.prepaint_at(origin, window, cx);
 7222            Some((element, origin))
 7223        } else {
 7224            self.render_edit_prediction_end_of_line_popover(
 7225                "Jump to Edit",
 7226                editor_snapshot,
 7227                visible_row_range,
 7228                target_display_point,
 7229                line_height,
 7230                scroll_pixel_position,
 7231                content_origin,
 7232                editor_width,
 7233                window,
 7234                cx,
 7235            )
 7236        }
 7237    }
 7238
 7239    fn render_edit_prediction_end_of_line_popover(
 7240        self: &mut Editor,
 7241        label: &'static str,
 7242        editor_snapshot: &EditorSnapshot,
 7243        visible_row_range: Range<DisplayRow>,
 7244        target_display_point: DisplayPoint,
 7245        line_height: Pixels,
 7246        scroll_pixel_position: gpui::Point<Pixels>,
 7247        content_origin: gpui::Point<Pixels>,
 7248        editor_width: Pixels,
 7249        window: &mut Window,
 7250        cx: &mut App,
 7251    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7252        let target_line_end = DisplayPoint::new(
 7253            target_display_point.row(),
 7254            editor_snapshot.line_len(target_display_point.row()),
 7255        );
 7256
 7257        let mut element = self
 7258            .render_edit_prediction_line_popover(label, None, window, cx)?
 7259            .into_any();
 7260
 7261        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7262
 7263        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7264
 7265        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7266        let mut origin = start_point
 7267            + line_origin
 7268            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7269        origin.x = origin.x.max(content_origin.x);
 7270
 7271        let max_x = content_origin.x + editor_width - size.width;
 7272
 7273        if origin.x > max_x {
 7274            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7275
 7276            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7277                origin.y += offset;
 7278                IconName::ArrowUp
 7279            } else {
 7280                origin.y -= offset;
 7281                IconName::ArrowDown
 7282            };
 7283
 7284            element = self
 7285                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7286                .into_any();
 7287
 7288            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7289
 7290            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7291        }
 7292
 7293        element.prepaint_at(origin, window, cx);
 7294        Some((element, origin))
 7295    }
 7296
 7297    fn render_edit_prediction_diff_popover(
 7298        self: &Editor,
 7299        text_bounds: &Bounds<Pixels>,
 7300        content_origin: gpui::Point<Pixels>,
 7301        editor_snapshot: &EditorSnapshot,
 7302        visible_row_range: Range<DisplayRow>,
 7303        line_layouts: &[LineWithInvisibles],
 7304        line_height: Pixels,
 7305        scroll_pixel_position: gpui::Point<Pixels>,
 7306        newest_selection_head: Option<DisplayPoint>,
 7307        editor_width: Pixels,
 7308        style: &EditorStyle,
 7309        edits: &Vec<(Range<Anchor>, String)>,
 7310        edit_preview: &Option<language::EditPreview>,
 7311        snapshot: &language::BufferSnapshot,
 7312        window: &mut Window,
 7313        cx: &mut App,
 7314    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7315        let edit_start = edits
 7316            .first()
 7317            .unwrap()
 7318            .0
 7319            .start
 7320            .to_display_point(editor_snapshot);
 7321        let edit_end = edits
 7322            .last()
 7323            .unwrap()
 7324            .0
 7325            .end
 7326            .to_display_point(editor_snapshot);
 7327
 7328        let is_visible = visible_row_range.contains(&edit_start.row())
 7329            || visible_row_range.contains(&edit_end.row());
 7330        if !is_visible {
 7331            return None;
 7332        }
 7333
 7334        let highlighted_edits =
 7335            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7336
 7337        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7338        let line_count = highlighted_edits.text.lines().count();
 7339
 7340        const BORDER_WIDTH: Pixels = px(1.);
 7341
 7342        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7343        let has_keybind = keybind.is_some();
 7344
 7345        let mut element = h_flex()
 7346            .items_start()
 7347            .child(
 7348                h_flex()
 7349                    .bg(cx.theme().colors().editor_background)
 7350                    .border(BORDER_WIDTH)
 7351                    .shadow_sm()
 7352                    .border_color(cx.theme().colors().border)
 7353                    .rounded_l_lg()
 7354                    .when(line_count > 1, |el| el.rounded_br_lg())
 7355                    .pr_1()
 7356                    .child(styled_text),
 7357            )
 7358            .child(
 7359                h_flex()
 7360                    .h(line_height + BORDER_WIDTH * 2.)
 7361                    .px_1p5()
 7362                    .gap_1()
 7363                    // Workaround: For some reason, there's a gap if we don't do this
 7364                    .ml(-BORDER_WIDTH)
 7365                    .shadow(smallvec![gpui::BoxShadow {
 7366                        color: gpui::black().opacity(0.05),
 7367                        offset: point(px(1.), px(1.)),
 7368                        blur_radius: px(2.),
 7369                        spread_radius: px(0.),
 7370                    }])
 7371                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7372                    .border(BORDER_WIDTH)
 7373                    .border_color(cx.theme().colors().border)
 7374                    .rounded_r_lg()
 7375                    .id("edit_prediction_diff_popover_keybind")
 7376                    .when(!has_keybind, |el| {
 7377                        let status_colors = cx.theme().status();
 7378
 7379                        el.bg(status_colors.error_background)
 7380                            .border_color(status_colors.error.opacity(0.6))
 7381                            .child(Icon::new(IconName::Info).color(Color::Error))
 7382                            .cursor_default()
 7383                            .hoverable_tooltip(move |_window, cx| {
 7384                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7385                            })
 7386                    })
 7387                    .children(keybind),
 7388            )
 7389            .into_any();
 7390
 7391        let longest_row =
 7392            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7393        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7394            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7395        } else {
 7396            layout_line(
 7397                longest_row,
 7398                editor_snapshot,
 7399                style,
 7400                editor_width,
 7401                |_| false,
 7402                window,
 7403                cx,
 7404            )
 7405            .width
 7406        };
 7407
 7408        let viewport_bounds =
 7409            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7410                right: -EditorElement::SCROLLBAR_WIDTH,
 7411                ..Default::default()
 7412            });
 7413
 7414        let x_after_longest =
 7415            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7416                - scroll_pixel_position.x;
 7417
 7418        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7419
 7420        // Fully visible if it can be displayed within the window (allow overlapping other
 7421        // panes). However, this is only allowed if the popover starts within text_bounds.
 7422        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7423            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7424
 7425        let mut origin = if can_position_to_the_right {
 7426            point(
 7427                x_after_longest,
 7428                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7429                    - scroll_pixel_position.y,
 7430            )
 7431        } else {
 7432            let cursor_row = newest_selection_head.map(|head| head.row());
 7433            let above_edit = edit_start
 7434                .row()
 7435                .0
 7436                .checked_sub(line_count as u32)
 7437                .map(DisplayRow);
 7438            let below_edit = Some(edit_end.row() + 1);
 7439            let above_cursor =
 7440                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7441            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7442
 7443            // Place the edit popover adjacent to the edit if there is a location
 7444            // available that is onscreen and does not obscure the cursor. Otherwise,
 7445            // place it adjacent to the cursor.
 7446            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7447                .into_iter()
 7448                .flatten()
 7449                .find(|&start_row| {
 7450                    let end_row = start_row + line_count as u32;
 7451                    visible_row_range.contains(&start_row)
 7452                        && visible_row_range.contains(&end_row)
 7453                        && cursor_row.map_or(true, |cursor_row| {
 7454                            !((start_row..end_row).contains(&cursor_row))
 7455                        })
 7456                })?;
 7457
 7458            content_origin
 7459                + point(
 7460                    -scroll_pixel_position.x,
 7461                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7462                )
 7463        };
 7464
 7465        origin.x -= BORDER_WIDTH;
 7466
 7467        window.defer_draw(element, origin, 1);
 7468
 7469        // Do not return an element, since it will already be drawn due to defer_draw.
 7470        None
 7471    }
 7472
 7473    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7474        px(30.)
 7475    }
 7476
 7477    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7478        if self.read_only(cx) {
 7479            cx.theme().players().read_only()
 7480        } else {
 7481            self.style.as_ref().unwrap().local_player
 7482        }
 7483    }
 7484
 7485    fn render_edit_prediction_accept_keybind(
 7486        &self,
 7487        window: &mut Window,
 7488        cx: &App,
 7489    ) -> Option<AnyElement> {
 7490        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7491        let accept_keystroke = accept_binding.keystroke()?;
 7492
 7493        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7494
 7495        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7496            Color::Accent
 7497        } else {
 7498            Color::Muted
 7499        };
 7500
 7501        h_flex()
 7502            .px_0p5()
 7503            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7504            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7505            .text_size(TextSize::XSmall.rems(cx))
 7506            .child(h_flex().children(ui::render_modifiers(
 7507                &accept_keystroke.modifiers,
 7508                PlatformStyle::platform(),
 7509                Some(modifiers_color),
 7510                Some(IconSize::XSmall.rems().into()),
 7511                true,
 7512            )))
 7513            .when(is_platform_style_mac, |parent| {
 7514                parent.child(accept_keystroke.key.clone())
 7515            })
 7516            .when(!is_platform_style_mac, |parent| {
 7517                parent.child(
 7518                    Key::new(
 7519                        util::capitalize(&accept_keystroke.key),
 7520                        Some(Color::Default),
 7521                    )
 7522                    .size(Some(IconSize::XSmall.rems().into())),
 7523                )
 7524            })
 7525            .into_any()
 7526            .into()
 7527    }
 7528
 7529    fn render_edit_prediction_line_popover(
 7530        &self,
 7531        label: impl Into<SharedString>,
 7532        icon: Option<IconName>,
 7533        window: &mut Window,
 7534        cx: &App,
 7535    ) -> Option<Stateful<Div>> {
 7536        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7537
 7538        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7539        let has_keybind = keybind.is_some();
 7540
 7541        let result = h_flex()
 7542            .id("ep-line-popover")
 7543            .py_0p5()
 7544            .pl_1()
 7545            .pr(padding_right)
 7546            .gap_1()
 7547            .rounded_md()
 7548            .border_1()
 7549            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7550            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7551            .shadow_sm()
 7552            .when(!has_keybind, |el| {
 7553                let status_colors = cx.theme().status();
 7554
 7555                el.bg(status_colors.error_background)
 7556                    .border_color(status_colors.error.opacity(0.6))
 7557                    .pl_2()
 7558                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7559                    .cursor_default()
 7560                    .hoverable_tooltip(move |_window, cx| {
 7561                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7562                    })
 7563            })
 7564            .children(keybind)
 7565            .child(
 7566                Label::new(label)
 7567                    .size(LabelSize::Small)
 7568                    .when(!has_keybind, |el| {
 7569                        el.color(cx.theme().status().error.into()).strikethrough()
 7570                    }),
 7571            )
 7572            .when(!has_keybind, |el| {
 7573                el.child(
 7574                    h_flex().ml_1().child(
 7575                        Icon::new(IconName::Info)
 7576                            .size(IconSize::Small)
 7577                            .color(cx.theme().status().error.into()),
 7578                    ),
 7579                )
 7580            })
 7581            .when_some(icon, |element, icon| {
 7582                element.child(
 7583                    div()
 7584                        .mt(px(1.5))
 7585                        .child(Icon::new(icon).size(IconSize::Small)),
 7586                )
 7587            });
 7588
 7589        Some(result)
 7590    }
 7591
 7592    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7593        let accent_color = cx.theme().colors().text_accent;
 7594        let editor_bg_color = cx.theme().colors().editor_background;
 7595        editor_bg_color.blend(accent_color.opacity(0.1))
 7596    }
 7597
 7598    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7599        let accent_color = cx.theme().colors().text_accent;
 7600        let editor_bg_color = cx.theme().colors().editor_background;
 7601        editor_bg_color.blend(accent_color.opacity(0.6))
 7602    }
 7603
 7604    fn render_edit_prediction_cursor_popover(
 7605        &self,
 7606        min_width: Pixels,
 7607        max_width: Pixels,
 7608        cursor_point: Point,
 7609        style: &EditorStyle,
 7610        accept_keystroke: Option<&gpui::Keystroke>,
 7611        _window: &Window,
 7612        cx: &mut Context<Editor>,
 7613    ) -> Option<AnyElement> {
 7614        let provider = self.edit_prediction_provider.as_ref()?;
 7615
 7616        if provider.provider.needs_terms_acceptance(cx) {
 7617            return Some(
 7618                h_flex()
 7619                    .min_w(min_width)
 7620                    .flex_1()
 7621                    .px_2()
 7622                    .py_1()
 7623                    .gap_3()
 7624                    .elevation_2(cx)
 7625                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7626                    .id("accept-terms")
 7627                    .cursor_pointer()
 7628                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7629                    .on_click(cx.listener(|this, _event, window, cx| {
 7630                        cx.stop_propagation();
 7631                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7632                        window.dispatch_action(
 7633                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7634                            cx,
 7635                        );
 7636                    }))
 7637                    .child(
 7638                        h_flex()
 7639                            .flex_1()
 7640                            .gap_2()
 7641                            .child(Icon::new(IconName::ZedPredict))
 7642                            .child(Label::new("Accept Terms of Service"))
 7643                            .child(div().w_full())
 7644                            .child(
 7645                                Icon::new(IconName::ArrowUpRight)
 7646                                    .color(Color::Muted)
 7647                                    .size(IconSize::Small),
 7648                            )
 7649                            .into_any_element(),
 7650                    )
 7651                    .into_any(),
 7652            );
 7653        }
 7654
 7655        let is_refreshing = provider.provider.is_refreshing(cx);
 7656
 7657        fn pending_completion_container() -> Div {
 7658            h_flex()
 7659                .h_full()
 7660                .flex_1()
 7661                .gap_2()
 7662                .child(Icon::new(IconName::ZedPredict))
 7663        }
 7664
 7665        let completion = match &self.active_inline_completion {
 7666            Some(prediction) => {
 7667                if !self.has_visible_completions_menu() {
 7668                    const RADIUS: Pixels = px(6.);
 7669                    const BORDER_WIDTH: Pixels = px(1.);
 7670
 7671                    return Some(
 7672                        h_flex()
 7673                            .elevation_2(cx)
 7674                            .border(BORDER_WIDTH)
 7675                            .border_color(cx.theme().colors().border)
 7676                            .when(accept_keystroke.is_none(), |el| {
 7677                                el.border_color(cx.theme().status().error)
 7678                            })
 7679                            .rounded(RADIUS)
 7680                            .rounded_tl(px(0.))
 7681                            .overflow_hidden()
 7682                            .child(div().px_1p5().child(match &prediction.completion {
 7683                                InlineCompletion::Move { target, snapshot } => {
 7684                                    use text::ToPoint as _;
 7685                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7686                                    {
 7687                                        Icon::new(IconName::ZedPredictDown)
 7688                                    } else {
 7689                                        Icon::new(IconName::ZedPredictUp)
 7690                                    }
 7691                                }
 7692                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7693                            }))
 7694                            .child(
 7695                                h_flex()
 7696                                    .gap_1()
 7697                                    .py_1()
 7698                                    .px_2()
 7699                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7700                                    .border_l_1()
 7701                                    .border_color(cx.theme().colors().border)
 7702                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7703                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7704                                        el.child(
 7705                                            Label::new("Hold")
 7706                                                .size(LabelSize::Small)
 7707                                                .when(accept_keystroke.is_none(), |el| {
 7708                                                    el.strikethrough()
 7709                                                })
 7710                                                .line_height_style(LineHeightStyle::UiLabel),
 7711                                        )
 7712                                    })
 7713                                    .id("edit_prediction_cursor_popover_keybind")
 7714                                    .when(accept_keystroke.is_none(), |el| {
 7715                                        let status_colors = cx.theme().status();
 7716
 7717                                        el.bg(status_colors.error_background)
 7718                                            .border_color(status_colors.error.opacity(0.6))
 7719                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7720                                            .cursor_default()
 7721                                            .hoverable_tooltip(move |_window, cx| {
 7722                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7723                                                    .into()
 7724                                            })
 7725                                    })
 7726                                    .when_some(
 7727                                        accept_keystroke.as_ref(),
 7728                                        |el, accept_keystroke| {
 7729                                            el.child(h_flex().children(ui::render_modifiers(
 7730                                                &accept_keystroke.modifiers,
 7731                                                PlatformStyle::platform(),
 7732                                                Some(Color::Default),
 7733                                                Some(IconSize::XSmall.rems().into()),
 7734                                                false,
 7735                                            )))
 7736                                        },
 7737                                    ),
 7738                            )
 7739                            .into_any(),
 7740                    );
 7741                }
 7742
 7743                self.render_edit_prediction_cursor_popover_preview(
 7744                    prediction,
 7745                    cursor_point,
 7746                    style,
 7747                    cx,
 7748                )?
 7749            }
 7750
 7751            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7752                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7753                    stale_completion,
 7754                    cursor_point,
 7755                    style,
 7756                    cx,
 7757                )?,
 7758
 7759                None => {
 7760                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7761                }
 7762            },
 7763
 7764            None => pending_completion_container().child(Label::new("No Prediction")),
 7765        };
 7766
 7767        let completion = if is_refreshing {
 7768            completion
 7769                .with_animation(
 7770                    "loading-completion",
 7771                    Animation::new(Duration::from_secs(2))
 7772                        .repeat()
 7773                        .with_easing(pulsating_between(0.4, 0.8)),
 7774                    |label, delta| label.opacity(delta),
 7775                )
 7776                .into_any_element()
 7777        } else {
 7778            completion.into_any_element()
 7779        };
 7780
 7781        let has_completion = self.active_inline_completion.is_some();
 7782
 7783        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7784        Some(
 7785            h_flex()
 7786                .min_w(min_width)
 7787                .max_w(max_width)
 7788                .flex_1()
 7789                .elevation_2(cx)
 7790                .border_color(cx.theme().colors().border)
 7791                .child(
 7792                    div()
 7793                        .flex_1()
 7794                        .py_1()
 7795                        .px_2()
 7796                        .overflow_hidden()
 7797                        .child(completion),
 7798                )
 7799                .when_some(accept_keystroke, |el, accept_keystroke| {
 7800                    if !accept_keystroke.modifiers.modified() {
 7801                        return el;
 7802                    }
 7803
 7804                    el.child(
 7805                        h_flex()
 7806                            .h_full()
 7807                            .border_l_1()
 7808                            .rounded_r_lg()
 7809                            .border_color(cx.theme().colors().border)
 7810                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7811                            .gap_1()
 7812                            .py_1()
 7813                            .px_2()
 7814                            .child(
 7815                                h_flex()
 7816                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7817                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7818                                    .child(h_flex().children(ui::render_modifiers(
 7819                                        &accept_keystroke.modifiers,
 7820                                        PlatformStyle::platform(),
 7821                                        Some(if !has_completion {
 7822                                            Color::Muted
 7823                                        } else {
 7824                                            Color::Default
 7825                                        }),
 7826                                        None,
 7827                                        false,
 7828                                    ))),
 7829                            )
 7830                            .child(Label::new("Preview").into_any_element())
 7831                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7832                    )
 7833                })
 7834                .into_any(),
 7835        )
 7836    }
 7837
 7838    fn render_edit_prediction_cursor_popover_preview(
 7839        &self,
 7840        completion: &InlineCompletionState,
 7841        cursor_point: Point,
 7842        style: &EditorStyle,
 7843        cx: &mut Context<Editor>,
 7844    ) -> Option<Div> {
 7845        use text::ToPoint as _;
 7846
 7847        fn render_relative_row_jump(
 7848            prefix: impl Into<String>,
 7849            current_row: u32,
 7850            target_row: u32,
 7851        ) -> Div {
 7852            let (row_diff, arrow) = if target_row < current_row {
 7853                (current_row - target_row, IconName::ArrowUp)
 7854            } else {
 7855                (target_row - current_row, IconName::ArrowDown)
 7856            };
 7857
 7858            h_flex()
 7859                .child(
 7860                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7861                        .color(Color::Muted)
 7862                        .size(LabelSize::Small),
 7863                )
 7864                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7865        }
 7866
 7867        match &completion.completion {
 7868            InlineCompletion::Move {
 7869                target, snapshot, ..
 7870            } => Some(
 7871                h_flex()
 7872                    .px_2()
 7873                    .gap_2()
 7874                    .flex_1()
 7875                    .child(
 7876                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7877                            Icon::new(IconName::ZedPredictDown)
 7878                        } else {
 7879                            Icon::new(IconName::ZedPredictUp)
 7880                        },
 7881                    )
 7882                    .child(Label::new("Jump to Edit")),
 7883            ),
 7884
 7885            InlineCompletion::Edit {
 7886                edits,
 7887                edit_preview,
 7888                snapshot,
 7889                display_mode: _,
 7890            } => {
 7891                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7892
 7893                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7894                    &snapshot,
 7895                    &edits,
 7896                    edit_preview.as_ref()?,
 7897                    true,
 7898                    cx,
 7899                )
 7900                .first_line_preview();
 7901
 7902                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7903                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7904
 7905                let preview = h_flex()
 7906                    .gap_1()
 7907                    .min_w_16()
 7908                    .child(styled_text)
 7909                    .when(has_more_lines, |parent| parent.child(""));
 7910
 7911                let left = if first_edit_row != cursor_point.row {
 7912                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7913                        .into_any_element()
 7914                } else {
 7915                    Icon::new(IconName::ZedPredict).into_any_element()
 7916                };
 7917
 7918                Some(
 7919                    h_flex()
 7920                        .h_full()
 7921                        .flex_1()
 7922                        .gap_2()
 7923                        .pr_1()
 7924                        .overflow_x_hidden()
 7925                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7926                        .child(left)
 7927                        .child(preview),
 7928                )
 7929            }
 7930        }
 7931    }
 7932
 7933    fn render_context_menu(
 7934        &self,
 7935        style: &EditorStyle,
 7936        max_height_in_lines: u32,
 7937        window: &mut Window,
 7938        cx: &mut Context<Editor>,
 7939    ) -> Option<AnyElement> {
 7940        let menu = self.context_menu.borrow();
 7941        let menu = menu.as_ref()?;
 7942        if !menu.visible() {
 7943            return None;
 7944        };
 7945        Some(menu.render(style, max_height_in_lines, window, cx))
 7946    }
 7947
 7948    fn render_context_menu_aside(
 7949        &mut self,
 7950        max_size: Size<Pixels>,
 7951        window: &mut Window,
 7952        cx: &mut Context<Editor>,
 7953    ) -> Option<AnyElement> {
 7954        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7955            if menu.visible() {
 7956                menu.render_aside(self, max_size, window, cx)
 7957            } else {
 7958                None
 7959            }
 7960        })
 7961    }
 7962
 7963    fn hide_context_menu(
 7964        &mut self,
 7965        window: &mut Window,
 7966        cx: &mut Context<Self>,
 7967    ) -> Option<CodeContextMenu> {
 7968        cx.notify();
 7969        self.completion_tasks.clear();
 7970        let context_menu = self.context_menu.borrow_mut().take();
 7971        self.stale_inline_completion_in_menu.take();
 7972        self.update_visible_inline_completion(window, cx);
 7973        context_menu
 7974    }
 7975
 7976    fn show_snippet_choices(
 7977        &mut self,
 7978        choices: &Vec<String>,
 7979        selection: Range<Anchor>,
 7980        cx: &mut Context<Self>,
 7981    ) {
 7982        if selection.start.buffer_id.is_none() {
 7983            return;
 7984        }
 7985        let buffer_id = selection.start.buffer_id.unwrap();
 7986        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7987        let id = post_inc(&mut self.next_completion_id);
 7988
 7989        if let Some(buffer) = buffer {
 7990            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7991                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7992            ));
 7993        }
 7994    }
 7995
 7996    pub fn insert_snippet(
 7997        &mut self,
 7998        insertion_ranges: &[Range<usize>],
 7999        snippet: Snippet,
 8000        window: &mut Window,
 8001        cx: &mut Context<Self>,
 8002    ) -> Result<()> {
 8003        struct Tabstop<T> {
 8004            is_end_tabstop: bool,
 8005            ranges: Vec<Range<T>>,
 8006            choices: Option<Vec<String>>,
 8007        }
 8008
 8009        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8010            let snippet_text: Arc<str> = snippet.text.clone().into();
 8011            let edits = insertion_ranges
 8012                .iter()
 8013                .cloned()
 8014                .map(|range| (range, snippet_text.clone()));
 8015            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8016
 8017            let snapshot = &*buffer.read(cx);
 8018            let snippet = &snippet;
 8019            snippet
 8020                .tabstops
 8021                .iter()
 8022                .map(|tabstop| {
 8023                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8024                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8025                    });
 8026                    let mut tabstop_ranges = tabstop
 8027                        .ranges
 8028                        .iter()
 8029                        .flat_map(|tabstop_range| {
 8030                            let mut delta = 0_isize;
 8031                            insertion_ranges.iter().map(move |insertion_range| {
 8032                                let insertion_start = insertion_range.start as isize + delta;
 8033                                delta +=
 8034                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8035
 8036                                let start = ((insertion_start + tabstop_range.start) as usize)
 8037                                    .min(snapshot.len());
 8038                                let end = ((insertion_start + tabstop_range.end) as usize)
 8039                                    .min(snapshot.len());
 8040                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8041                            })
 8042                        })
 8043                        .collect::<Vec<_>>();
 8044                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8045
 8046                    Tabstop {
 8047                        is_end_tabstop,
 8048                        ranges: tabstop_ranges,
 8049                        choices: tabstop.choices.clone(),
 8050                    }
 8051                })
 8052                .collect::<Vec<_>>()
 8053        });
 8054        if let Some(tabstop) = tabstops.first() {
 8055            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8056                s.select_ranges(tabstop.ranges.iter().cloned());
 8057            });
 8058
 8059            if let Some(choices) = &tabstop.choices {
 8060                if let Some(selection) = tabstop.ranges.first() {
 8061                    self.show_snippet_choices(choices, selection.clone(), cx)
 8062                }
 8063            }
 8064
 8065            // If we're already at the last tabstop and it's at the end of the snippet,
 8066            // we're done, we don't need to keep the state around.
 8067            if !tabstop.is_end_tabstop {
 8068                let choices = tabstops
 8069                    .iter()
 8070                    .map(|tabstop| tabstop.choices.clone())
 8071                    .collect();
 8072
 8073                let ranges = tabstops
 8074                    .into_iter()
 8075                    .map(|tabstop| tabstop.ranges)
 8076                    .collect::<Vec<_>>();
 8077
 8078                self.snippet_stack.push(SnippetState {
 8079                    active_index: 0,
 8080                    ranges,
 8081                    choices,
 8082                });
 8083            }
 8084
 8085            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8086            if self.autoclose_regions.is_empty() {
 8087                let snapshot = self.buffer.read(cx).snapshot(cx);
 8088                for selection in &mut self.selections.all::<Point>(cx) {
 8089                    let selection_head = selection.head();
 8090                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8091                        continue;
 8092                    };
 8093
 8094                    let mut bracket_pair = None;
 8095                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8096                    let prev_chars = snapshot
 8097                        .reversed_chars_at(selection_head)
 8098                        .collect::<String>();
 8099                    for (pair, enabled) in scope.brackets() {
 8100                        if enabled
 8101                            && pair.close
 8102                            && prev_chars.starts_with(pair.start.as_str())
 8103                            && next_chars.starts_with(pair.end.as_str())
 8104                        {
 8105                            bracket_pair = Some(pair.clone());
 8106                            break;
 8107                        }
 8108                    }
 8109                    if let Some(pair) = bracket_pair {
 8110                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8111                        let autoclose_enabled =
 8112                            self.use_autoclose && snapshot_settings.use_autoclose;
 8113                        if autoclose_enabled {
 8114                            let start = snapshot.anchor_after(selection_head);
 8115                            let end = snapshot.anchor_after(selection_head);
 8116                            self.autoclose_regions.push(AutocloseRegion {
 8117                                selection_id: selection.id,
 8118                                range: start..end,
 8119                                pair,
 8120                            });
 8121                        }
 8122                    }
 8123                }
 8124            }
 8125        }
 8126        Ok(())
 8127    }
 8128
 8129    pub fn move_to_next_snippet_tabstop(
 8130        &mut self,
 8131        window: &mut Window,
 8132        cx: &mut Context<Self>,
 8133    ) -> bool {
 8134        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8135    }
 8136
 8137    pub fn move_to_prev_snippet_tabstop(
 8138        &mut self,
 8139        window: &mut Window,
 8140        cx: &mut Context<Self>,
 8141    ) -> bool {
 8142        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8143    }
 8144
 8145    pub fn move_to_snippet_tabstop(
 8146        &mut self,
 8147        bias: Bias,
 8148        window: &mut Window,
 8149        cx: &mut Context<Self>,
 8150    ) -> bool {
 8151        if let Some(mut snippet) = self.snippet_stack.pop() {
 8152            match bias {
 8153                Bias::Left => {
 8154                    if snippet.active_index > 0 {
 8155                        snippet.active_index -= 1;
 8156                    } else {
 8157                        self.snippet_stack.push(snippet);
 8158                        return false;
 8159                    }
 8160                }
 8161                Bias::Right => {
 8162                    if snippet.active_index + 1 < snippet.ranges.len() {
 8163                        snippet.active_index += 1;
 8164                    } else {
 8165                        self.snippet_stack.push(snippet);
 8166                        return false;
 8167                    }
 8168                }
 8169            }
 8170            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8171                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8172                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8173                });
 8174
 8175                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8176                    if let Some(selection) = current_ranges.first() {
 8177                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8178                    }
 8179                }
 8180
 8181                // If snippet state is not at the last tabstop, push it back on the stack
 8182                if snippet.active_index + 1 < snippet.ranges.len() {
 8183                    self.snippet_stack.push(snippet);
 8184                }
 8185                return true;
 8186            }
 8187        }
 8188
 8189        false
 8190    }
 8191
 8192    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8193        self.transact(window, cx, |this, window, cx| {
 8194            this.select_all(&SelectAll, window, cx);
 8195            this.insert("", window, cx);
 8196        });
 8197    }
 8198
 8199    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8200        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8201        self.transact(window, cx, |this, window, cx| {
 8202            this.select_autoclose_pair(window, cx);
 8203            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8204            if !this.linked_edit_ranges.is_empty() {
 8205                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8206                let snapshot = this.buffer.read(cx).snapshot(cx);
 8207
 8208                for selection in selections.iter() {
 8209                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8210                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8211                    if selection_start.buffer_id != selection_end.buffer_id {
 8212                        continue;
 8213                    }
 8214                    if let Some(ranges) =
 8215                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8216                    {
 8217                        for (buffer, entries) in ranges {
 8218                            linked_ranges.entry(buffer).or_default().extend(entries);
 8219                        }
 8220                    }
 8221                }
 8222            }
 8223
 8224            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8225            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8226            for selection in &mut selections {
 8227                if selection.is_empty() {
 8228                    let old_head = selection.head();
 8229                    let mut new_head =
 8230                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8231                            .to_point(&display_map);
 8232                    if let Some((buffer, line_buffer_range)) = display_map
 8233                        .buffer_snapshot
 8234                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8235                    {
 8236                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8237                        let indent_len = match indent_size.kind {
 8238                            IndentKind::Space => {
 8239                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8240                            }
 8241                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8242                        };
 8243                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8244                            let indent_len = indent_len.get();
 8245                            new_head = cmp::min(
 8246                                new_head,
 8247                                MultiBufferPoint::new(
 8248                                    old_head.row,
 8249                                    ((old_head.column - 1) / indent_len) * indent_len,
 8250                                ),
 8251                            );
 8252                        }
 8253                    }
 8254
 8255                    selection.set_head(new_head, SelectionGoal::None);
 8256                }
 8257            }
 8258
 8259            this.signature_help_state.set_backspace_pressed(true);
 8260            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8261                s.select(selections)
 8262            });
 8263            this.insert("", window, cx);
 8264            let empty_str: Arc<str> = Arc::from("");
 8265            for (buffer, edits) in linked_ranges {
 8266                let snapshot = buffer.read(cx).snapshot();
 8267                use text::ToPoint as TP;
 8268
 8269                let edits = edits
 8270                    .into_iter()
 8271                    .map(|range| {
 8272                        let end_point = TP::to_point(&range.end, &snapshot);
 8273                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8274
 8275                        if end_point == start_point {
 8276                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8277                                .saturating_sub(1);
 8278                            start_point =
 8279                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8280                        };
 8281
 8282                        (start_point..end_point, empty_str.clone())
 8283                    })
 8284                    .sorted_by_key(|(range, _)| range.start)
 8285                    .collect::<Vec<_>>();
 8286                buffer.update(cx, |this, cx| {
 8287                    this.edit(edits, None, cx);
 8288                })
 8289            }
 8290            this.refresh_inline_completion(true, false, window, cx);
 8291            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8292        });
 8293    }
 8294
 8295    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8296        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8297        self.transact(window, cx, |this, window, cx| {
 8298            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8299                s.move_with(|map, selection| {
 8300                    if selection.is_empty() {
 8301                        let cursor = movement::right(map, selection.head());
 8302                        selection.end = cursor;
 8303                        selection.reversed = true;
 8304                        selection.goal = SelectionGoal::None;
 8305                    }
 8306                })
 8307            });
 8308            this.insert("", window, cx);
 8309            this.refresh_inline_completion(true, false, window, cx);
 8310        });
 8311    }
 8312
 8313    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8314        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8315        if self.move_to_prev_snippet_tabstop(window, cx) {
 8316            return;
 8317        }
 8318        self.outdent(&Outdent, window, cx);
 8319    }
 8320
 8321    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8322        if self.move_to_next_snippet_tabstop(window, cx) {
 8323            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8324            return;
 8325        }
 8326        if self.read_only(cx) {
 8327            return;
 8328        }
 8329        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8330        let mut selections = self.selections.all_adjusted(cx);
 8331        let buffer = self.buffer.read(cx);
 8332        let snapshot = buffer.snapshot(cx);
 8333        let rows_iter = selections.iter().map(|s| s.head().row);
 8334        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8335
 8336        let mut edits = Vec::new();
 8337        let mut prev_edited_row = 0;
 8338        let mut row_delta = 0;
 8339        for selection in &mut selections {
 8340            if selection.start.row != prev_edited_row {
 8341                row_delta = 0;
 8342            }
 8343            prev_edited_row = selection.end.row;
 8344
 8345            // If the selection is non-empty, then increase the indentation of the selected lines.
 8346            if !selection.is_empty() {
 8347                row_delta =
 8348                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8349                continue;
 8350            }
 8351
 8352            // If the selection is empty and the cursor is in the leading whitespace before the
 8353            // suggested indentation, then auto-indent the line.
 8354            let cursor = selection.head();
 8355            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8356            if let Some(suggested_indent) =
 8357                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8358            {
 8359                if cursor.column < suggested_indent.len
 8360                    && cursor.column <= current_indent.len
 8361                    && current_indent.len <= suggested_indent.len
 8362                {
 8363                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8364                    selection.end = selection.start;
 8365                    if row_delta == 0 {
 8366                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8367                            cursor.row,
 8368                            current_indent,
 8369                            suggested_indent,
 8370                        ));
 8371                        row_delta = suggested_indent.len - current_indent.len;
 8372                    }
 8373                    continue;
 8374                }
 8375            }
 8376
 8377            // Otherwise, insert a hard or soft tab.
 8378            let settings = buffer.language_settings_at(cursor, cx);
 8379            let tab_size = if settings.hard_tabs {
 8380                IndentSize::tab()
 8381            } else {
 8382                let tab_size = settings.tab_size.get();
 8383                let indent_remainder = snapshot
 8384                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8385                    .flat_map(str::chars)
 8386                    .fold(row_delta % tab_size, |counter: u32, c| {
 8387                        if c == '\t' {
 8388                            0
 8389                        } else {
 8390                            (counter + 1) % tab_size
 8391                        }
 8392                    });
 8393
 8394                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8395                IndentSize::spaces(chars_to_next_tab_stop)
 8396            };
 8397            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8398            selection.end = selection.start;
 8399            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8400            row_delta += tab_size.len;
 8401        }
 8402
 8403        self.transact(window, cx, |this, window, cx| {
 8404            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8405            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8406                s.select(selections)
 8407            });
 8408            this.refresh_inline_completion(true, false, window, cx);
 8409        });
 8410    }
 8411
 8412    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8413        if self.read_only(cx) {
 8414            return;
 8415        }
 8416        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8417        let mut selections = self.selections.all::<Point>(cx);
 8418        let mut prev_edited_row = 0;
 8419        let mut row_delta = 0;
 8420        let mut edits = Vec::new();
 8421        let buffer = self.buffer.read(cx);
 8422        let snapshot = buffer.snapshot(cx);
 8423        for selection in &mut selections {
 8424            if selection.start.row != prev_edited_row {
 8425                row_delta = 0;
 8426            }
 8427            prev_edited_row = selection.end.row;
 8428
 8429            row_delta =
 8430                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8431        }
 8432
 8433        self.transact(window, cx, |this, window, cx| {
 8434            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8435            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8436                s.select(selections)
 8437            });
 8438        });
 8439    }
 8440
 8441    fn indent_selection(
 8442        buffer: &MultiBuffer,
 8443        snapshot: &MultiBufferSnapshot,
 8444        selection: &mut Selection<Point>,
 8445        edits: &mut Vec<(Range<Point>, String)>,
 8446        delta_for_start_row: u32,
 8447        cx: &App,
 8448    ) -> u32 {
 8449        let settings = buffer.language_settings_at(selection.start, cx);
 8450        let tab_size = settings.tab_size.get();
 8451        let indent_kind = if settings.hard_tabs {
 8452            IndentKind::Tab
 8453        } else {
 8454            IndentKind::Space
 8455        };
 8456        let mut start_row = selection.start.row;
 8457        let mut end_row = selection.end.row + 1;
 8458
 8459        // If a selection ends at the beginning of a line, don't indent
 8460        // that last line.
 8461        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8462            end_row -= 1;
 8463        }
 8464
 8465        // Avoid re-indenting a row that has already been indented by a
 8466        // previous selection, but still update this selection's column
 8467        // to reflect that indentation.
 8468        if delta_for_start_row > 0 {
 8469            start_row += 1;
 8470            selection.start.column += delta_for_start_row;
 8471            if selection.end.row == selection.start.row {
 8472                selection.end.column += delta_for_start_row;
 8473            }
 8474        }
 8475
 8476        let mut delta_for_end_row = 0;
 8477        let has_multiple_rows = start_row + 1 != end_row;
 8478        for row in start_row..end_row {
 8479            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8480            let indent_delta = match (current_indent.kind, indent_kind) {
 8481                (IndentKind::Space, IndentKind::Space) => {
 8482                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8483                    IndentSize::spaces(columns_to_next_tab_stop)
 8484                }
 8485                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8486                (_, IndentKind::Tab) => IndentSize::tab(),
 8487            };
 8488
 8489            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8490                0
 8491            } else {
 8492                selection.start.column
 8493            };
 8494            let row_start = Point::new(row, start);
 8495            edits.push((
 8496                row_start..row_start,
 8497                indent_delta.chars().collect::<String>(),
 8498            ));
 8499
 8500            // Update this selection's endpoints to reflect the indentation.
 8501            if row == selection.start.row {
 8502                selection.start.column += indent_delta.len;
 8503            }
 8504            if row == selection.end.row {
 8505                selection.end.column += indent_delta.len;
 8506                delta_for_end_row = indent_delta.len;
 8507            }
 8508        }
 8509
 8510        if selection.start.row == selection.end.row {
 8511            delta_for_start_row + delta_for_end_row
 8512        } else {
 8513            delta_for_end_row
 8514        }
 8515    }
 8516
 8517    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8518        if self.read_only(cx) {
 8519            return;
 8520        }
 8521        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8522        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8523        let selections = self.selections.all::<Point>(cx);
 8524        let mut deletion_ranges = Vec::new();
 8525        let mut last_outdent = None;
 8526        {
 8527            let buffer = self.buffer.read(cx);
 8528            let snapshot = buffer.snapshot(cx);
 8529            for selection in &selections {
 8530                let settings = buffer.language_settings_at(selection.start, cx);
 8531                let tab_size = settings.tab_size.get();
 8532                let mut rows = selection.spanned_rows(false, &display_map);
 8533
 8534                // Avoid re-outdenting a row that has already been outdented by a
 8535                // previous selection.
 8536                if let Some(last_row) = last_outdent {
 8537                    if last_row == rows.start {
 8538                        rows.start = rows.start.next_row();
 8539                    }
 8540                }
 8541                let has_multiple_rows = rows.len() > 1;
 8542                for row in rows.iter_rows() {
 8543                    let indent_size = snapshot.indent_size_for_line(row);
 8544                    if indent_size.len > 0 {
 8545                        let deletion_len = match indent_size.kind {
 8546                            IndentKind::Space => {
 8547                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8548                                if columns_to_prev_tab_stop == 0 {
 8549                                    tab_size
 8550                                } else {
 8551                                    columns_to_prev_tab_stop
 8552                                }
 8553                            }
 8554                            IndentKind::Tab => 1,
 8555                        };
 8556                        let start = if has_multiple_rows
 8557                            || deletion_len > selection.start.column
 8558                            || indent_size.len < selection.start.column
 8559                        {
 8560                            0
 8561                        } else {
 8562                            selection.start.column - deletion_len
 8563                        };
 8564                        deletion_ranges.push(
 8565                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8566                        );
 8567                        last_outdent = Some(row);
 8568                    }
 8569                }
 8570            }
 8571        }
 8572
 8573        self.transact(window, cx, |this, window, cx| {
 8574            this.buffer.update(cx, |buffer, cx| {
 8575                let empty_str: Arc<str> = Arc::default();
 8576                buffer.edit(
 8577                    deletion_ranges
 8578                        .into_iter()
 8579                        .map(|range| (range, empty_str.clone())),
 8580                    None,
 8581                    cx,
 8582                );
 8583            });
 8584            let selections = this.selections.all::<usize>(cx);
 8585            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8586                s.select(selections)
 8587            });
 8588        });
 8589    }
 8590
 8591    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8592        if self.read_only(cx) {
 8593            return;
 8594        }
 8595        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8596        let selections = self
 8597            .selections
 8598            .all::<usize>(cx)
 8599            .into_iter()
 8600            .map(|s| s.range());
 8601
 8602        self.transact(window, cx, |this, window, cx| {
 8603            this.buffer.update(cx, |buffer, cx| {
 8604                buffer.autoindent_ranges(selections, cx);
 8605            });
 8606            let selections = this.selections.all::<usize>(cx);
 8607            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8608                s.select(selections)
 8609            });
 8610        });
 8611    }
 8612
 8613    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8614        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8615        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8616        let selections = self.selections.all::<Point>(cx);
 8617
 8618        let mut new_cursors = Vec::new();
 8619        let mut edit_ranges = Vec::new();
 8620        let mut selections = selections.iter().peekable();
 8621        while let Some(selection) = selections.next() {
 8622            let mut rows = selection.spanned_rows(false, &display_map);
 8623            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8624
 8625            // Accumulate contiguous regions of rows that we want to delete.
 8626            while let Some(next_selection) = selections.peek() {
 8627                let next_rows = next_selection.spanned_rows(false, &display_map);
 8628                if next_rows.start <= rows.end {
 8629                    rows.end = next_rows.end;
 8630                    selections.next().unwrap();
 8631                } else {
 8632                    break;
 8633                }
 8634            }
 8635
 8636            let buffer = &display_map.buffer_snapshot;
 8637            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8638            let edit_end;
 8639            let cursor_buffer_row;
 8640            if buffer.max_point().row >= rows.end.0 {
 8641                // If there's a line after the range, delete the \n from the end of the row range
 8642                // and position the cursor on the next line.
 8643                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8644                cursor_buffer_row = rows.end;
 8645            } else {
 8646                // If there isn't a line after the range, delete the \n from the line before the
 8647                // start of the row range and position the cursor there.
 8648                edit_start = edit_start.saturating_sub(1);
 8649                edit_end = buffer.len();
 8650                cursor_buffer_row = rows.start.previous_row();
 8651            }
 8652
 8653            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8654            *cursor.column_mut() =
 8655                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8656
 8657            new_cursors.push((
 8658                selection.id,
 8659                buffer.anchor_after(cursor.to_point(&display_map)),
 8660            ));
 8661            edit_ranges.push(edit_start..edit_end);
 8662        }
 8663
 8664        self.transact(window, cx, |this, window, cx| {
 8665            let buffer = this.buffer.update(cx, |buffer, cx| {
 8666                let empty_str: Arc<str> = Arc::default();
 8667                buffer.edit(
 8668                    edit_ranges
 8669                        .into_iter()
 8670                        .map(|range| (range, empty_str.clone())),
 8671                    None,
 8672                    cx,
 8673                );
 8674                buffer.snapshot(cx)
 8675            });
 8676            let new_selections = new_cursors
 8677                .into_iter()
 8678                .map(|(id, cursor)| {
 8679                    let cursor = cursor.to_point(&buffer);
 8680                    Selection {
 8681                        id,
 8682                        start: cursor,
 8683                        end: cursor,
 8684                        reversed: false,
 8685                        goal: SelectionGoal::None,
 8686                    }
 8687                })
 8688                .collect();
 8689
 8690            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8691                s.select(new_selections);
 8692            });
 8693        });
 8694    }
 8695
 8696    pub fn join_lines_impl(
 8697        &mut self,
 8698        insert_whitespace: bool,
 8699        window: &mut Window,
 8700        cx: &mut Context<Self>,
 8701    ) {
 8702        if self.read_only(cx) {
 8703            return;
 8704        }
 8705        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8706        for selection in self.selections.all::<Point>(cx) {
 8707            let start = MultiBufferRow(selection.start.row);
 8708            // Treat single line selections as if they include the next line. Otherwise this action
 8709            // would do nothing for single line selections individual cursors.
 8710            let end = if selection.start.row == selection.end.row {
 8711                MultiBufferRow(selection.start.row + 1)
 8712            } else {
 8713                MultiBufferRow(selection.end.row)
 8714            };
 8715
 8716            if let Some(last_row_range) = row_ranges.last_mut() {
 8717                if start <= last_row_range.end {
 8718                    last_row_range.end = end;
 8719                    continue;
 8720                }
 8721            }
 8722            row_ranges.push(start..end);
 8723        }
 8724
 8725        let snapshot = self.buffer.read(cx).snapshot(cx);
 8726        let mut cursor_positions = Vec::new();
 8727        for row_range in &row_ranges {
 8728            let anchor = snapshot.anchor_before(Point::new(
 8729                row_range.end.previous_row().0,
 8730                snapshot.line_len(row_range.end.previous_row()),
 8731            ));
 8732            cursor_positions.push(anchor..anchor);
 8733        }
 8734
 8735        self.transact(window, cx, |this, window, cx| {
 8736            for row_range in row_ranges.into_iter().rev() {
 8737                for row in row_range.iter_rows().rev() {
 8738                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8739                    let next_line_row = row.next_row();
 8740                    let indent = snapshot.indent_size_for_line(next_line_row);
 8741                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8742
 8743                    let replace =
 8744                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8745                            " "
 8746                        } else {
 8747                            ""
 8748                        };
 8749
 8750                    this.buffer.update(cx, |buffer, cx| {
 8751                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8752                    });
 8753                }
 8754            }
 8755
 8756            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8757                s.select_anchor_ranges(cursor_positions)
 8758            });
 8759        });
 8760    }
 8761
 8762    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8763        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8764        self.join_lines_impl(true, window, cx);
 8765    }
 8766
 8767    pub fn sort_lines_case_sensitive(
 8768        &mut self,
 8769        _: &SortLinesCaseSensitive,
 8770        window: &mut Window,
 8771        cx: &mut Context<Self>,
 8772    ) {
 8773        self.manipulate_lines(window, cx, |lines| lines.sort())
 8774    }
 8775
 8776    pub fn sort_lines_case_insensitive(
 8777        &mut self,
 8778        _: &SortLinesCaseInsensitive,
 8779        window: &mut Window,
 8780        cx: &mut Context<Self>,
 8781    ) {
 8782        self.manipulate_lines(window, cx, |lines| {
 8783            lines.sort_by_key(|line| line.to_lowercase())
 8784        })
 8785    }
 8786
 8787    pub fn unique_lines_case_insensitive(
 8788        &mut self,
 8789        _: &UniqueLinesCaseInsensitive,
 8790        window: &mut Window,
 8791        cx: &mut Context<Self>,
 8792    ) {
 8793        self.manipulate_lines(window, cx, |lines| {
 8794            let mut seen = HashSet::default();
 8795            lines.retain(|line| seen.insert(line.to_lowercase()));
 8796        })
 8797    }
 8798
 8799    pub fn unique_lines_case_sensitive(
 8800        &mut self,
 8801        _: &UniqueLinesCaseSensitive,
 8802        window: &mut Window,
 8803        cx: &mut Context<Self>,
 8804    ) {
 8805        self.manipulate_lines(window, cx, |lines| {
 8806            let mut seen = HashSet::default();
 8807            lines.retain(|line| seen.insert(*line));
 8808        })
 8809    }
 8810
 8811    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8812        let Some(project) = self.project.clone() else {
 8813            return;
 8814        };
 8815        self.reload(project, window, cx)
 8816            .detach_and_notify_err(window, cx);
 8817    }
 8818
 8819    pub fn restore_file(
 8820        &mut self,
 8821        _: &::git::RestoreFile,
 8822        window: &mut Window,
 8823        cx: &mut Context<Self>,
 8824    ) {
 8825        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8826        let mut buffer_ids = HashSet::default();
 8827        let snapshot = self.buffer().read(cx).snapshot(cx);
 8828        for selection in self.selections.all::<usize>(cx) {
 8829            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8830        }
 8831
 8832        let buffer = self.buffer().read(cx);
 8833        let ranges = buffer_ids
 8834            .into_iter()
 8835            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8836            .collect::<Vec<_>>();
 8837
 8838        self.restore_hunks_in_ranges(ranges, window, cx);
 8839    }
 8840
 8841    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8842        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8843        let selections = self
 8844            .selections
 8845            .all(cx)
 8846            .into_iter()
 8847            .map(|s| s.range())
 8848            .collect();
 8849        self.restore_hunks_in_ranges(selections, window, cx);
 8850    }
 8851
 8852    pub fn restore_hunks_in_ranges(
 8853        &mut self,
 8854        ranges: Vec<Range<Point>>,
 8855        window: &mut Window,
 8856        cx: &mut Context<Editor>,
 8857    ) {
 8858        let mut revert_changes = HashMap::default();
 8859        let chunk_by = self
 8860            .snapshot(window, cx)
 8861            .hunks_for_ranges(ranges)
 8862            .into_iter()
 8863            .chunk_by(|hunk| hunk.buffer_id);
 8864        for (buffer_id, hunks) in &chunk_by {
 8865            let hunks = hunks.collect::<Vec<_>>();
 8866            for hunk in &hunks {
 8867                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8868            }
 8869            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8870        }
 8871        drop(chunk_by);
 8872        if !revert_changes.is_empty() {
 8873            self.transact(window, cx, |editor, window, cx| {
 8874                editor.restore(revert_changes, window, cx);
 8875            });
 8876        }
 8877    }
 8878
 8879    pub fn open_active_item_in_terminal(
 8880        &mut self,
 8881        _: &OpenInTerminal,
 8882        window: &mut Window,
 8883        cx: &mut Context<Self>,
 8884    ) {
 8885        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8886            let project_path = buffer.read(cx).project_path(cx)?;
 8887            let project = self.project.as_ref()?.read(cx);
 8888            let entry = project.entry_for_path(&project_path, cx)?;
 8889            let parent = match &entry.canonical_path {
 8890                Some(canonical_path) => canonical_path.to_path_buf(),
 8891                None => project.absolute_path(&project_path, cx)?,
 8892            }
 8893            .parent()?
 8894            .to_path_buf();
 8895            Some(parent)
 8896        }) {
 8897            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8898        }
 8899    }
 8900
 8901    fn set_breakpoint_context_menu(
 8902        &mut self,
 8903        display_row: DisplayRow,
 8904        position: Option<Anchor>,
 8905        clicked_point: gpui::Point<Pixels>,
 8906        window: &mut Window,
 8907        cx: &mut Context<Self>,
 8908    ) {
 8909        if !cx.has_flag::<Debugger>() {
 8910            return;
 8911        }
 8912        let source = self
 8913            .buffer
 8914            .read(cx)
 8915            .snapshot(cx)
 8916            .anchor_before(Point::new(display_row.0, 0u32));
 8917
 8918        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8919
 8920        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8921            self,
 8922            source,
 8923            clicked_point,
 8924            None,
 8925            context_menu,
 8926            window,
 8927            cx,
 8928        );
 8929    }
 8930
 8931    fn add_edit_breakpoint_block(
 8932        &mut self,
 8933        anchor: Anchor,
 8934        breakpoint: &Breakpoint,
 8935        edit_action: BreakpointPromptEditAction,
 8936        window: &mut Window,
 8937        cx: &mut Context<Self>,
 8938    ) {
 8939        let weak_editor = cx.weak_entity();
 8940        let bp_prompt = cx.new(|cx| {
 8941            BreakpointPromptEditor::new(
 8942                weak_editor,
 8943                anchor,
 8944                breakpoint.clone(),
 8945                edit_action,
 8946                window,
 8947                cx,
 8948            )
 8949        });
 8950
 8951        let height = bp_prompt.update(cx, |this, cx| {
 8952            this.prompt
 8953                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8954        });
 8955        let cloned_prompt = bp_prompt.clone();
 8956        let blocks = vec![BlockProperties {
 8957            style: BlockStyle::Sticky,
 8958            placement: BlockPlacement::Above(anchor),
 8959            height: Some(height),
 8960            render: Arc::new(move |cx| {
 8961                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8962                cloned_prompt.clone().into_any_element()
 8963            }),
 8964            priority: 0,
 8965        }];
 8966
 8967        let focus_handle = bp_prompt.focus_handle(cx);
 8968        window.focus(&focus_handle);
 8969
 8970        let block_ids = self.insert_blocks(blocks, None, cx);
 8971        bp_prompt.update(cx, |prompt, _| {
 8972            prompt.add_block_ids(block_ids);
 8973        });
 8974    }
 8975
 8976    pub(crate) fn breakpoint_at_row(
 8977        &self,
 8978        row: u32,
 8979        window: &mut Window,
 8980        cx: &mut Context<Self>,
 8981    ) -> Option<(Anchor, Breakpoint)> {
 8982        let snapshot = self.snapshot(window, cx);
 8983        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8984
 8985        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 8986    }
 8987
 8988    pub(crate) fn breakpoint_at_anchor(
 8989        &self,
 8990        breakpoint_position: Anchor,
 8991        snapshot: &EditorSnapshot,
 8992        cx: &mut Context<Self>,
 8993    ) -> Option<(Anchor, Breakpoint)> {
 8994        let project = self.project.clone()?;
 8995
 8996        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 8997            snapshot
 8998                .buffer_snapshot
 8999                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9000        })?;
 9001
 9002        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9003        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9004        let buffer_snapshot = buffer.read(cx).snapshot();
 9005
 9006        let row = buffer_snapshot
 9007            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9008            .row;
 9009
 9010        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9011        let anchor_end = snapshot
 9012            .buffer_snapshot
 9013            .anchor_after(Point::new(row, line_len));
 9014
 9015        let bp = self
 9016            .breakpoint_store
 9017            .as_ref()?
 9018            .read_with(cx, |breakpoint_store, cx| {
 9019                breakpoint_store
 9020                    .breakpoints(
 9021                        &buffer,
 9022                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9023                        &buffer_snapshot,
 9024                        cx,
 9025                    )
 9026                    .next()
 9027                    .and_then(|(anchor, bp)| {
 9028                        let breakpoint_row = buffer_snapshot
 9029                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9030                            .row;
 9031
 9032                        if breakpoint_row == row {
 9033                            snapshot
 9034                                .buffer_snapshot
 9035                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9036                                .map(|anchor| (anchor, bp.clone()))
 9037                        } else {
 9038                            None
 9039                        }
 9040                    })
 9041            });
 9042        bp
 9043    }
 9044
 9045    pub fn edit_log_breakpoint(
 9046        &mut self,
 9047        _: &EditLogBreakpoint,
 9048        window: &mut Window,
 9049        cx: &mut Context<Self>,
 9050    ) {
 9051        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9052            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9053                message: None,
 9054                state: BreakpointState::Enabled,
 9055                condition: None,
 9056                hit_condition: None,
 9057            });
 9058
 9059            self.add_edit_breakpoint_block(
 9060                anchor,
 9061                &breakpoint,
 9062                BreakpointPromptEditAction::Log,
 9063                window,
 9064                cx,
 9065            );
 9066        }
 9067    }
 9068
 9069    fn breakpoints_at_cursors(
 9070        &self,
 9071        window: &mut Window,
 9072        cx: &mut Context<Self>,
 9073    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9074        let snapshot = self.snapshot(window, cx);
 9075        let cursors = self
 9076            .selections
 9077            .disjoint_anchors()
 9078            .into_iter()
 9079            .map(|selection| {
 9080                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9081
 9082                let breakpoint_position = self
 9083                    .breakpoint_at_row(cursor_position.row, window, cx)
 9084                    .map(|bp| bp.0)
 9085                    .unwrap_or_else(|| {
 9086                        snapshot
 9087                            .display_snapshot
 9088                            .buffer_snapshot
 9089                            .anchor_after(Point::new(cursor_position.row, 0))
 9090                    });
 9091
 9092                let breakpoint = self
 9093                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9094                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9095
 9096                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9097            })
 9098            // There might be multiple cursors on the same line; all of them should have the same anchors though as their breakpoints positions, which makes it possible to sort and dedup the list.
 9099            .collect::<HashMap<Anchor, _>>();
 9100
 9101        cursors.into_iter().collect()
 9102    }
 9103
 9104    pub fn enable_breakpoint(
 9105        &mut self,
 9106        _: &crate::actions::EnableBreakpoint,
 9107        window: &mut Window,
 9108        cx: &mut Context<Self>,
 9109    ) {
 9110        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9111            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9112                continue;
 9113            };
 9114            self.edit_breakpoint_at_anchor(
 9115                anchor,
 9116                breakpoint,
 9117                BreakpointEditAction::InvertState,
 9118                cx,
 9119            );
 9120        }
 9121    }
 9122
 9123    pub fn disable_breakpoint(
 9124        &mut self,
 9125        _: &crate::actions::DisableBreakpoint,
 9126        window: &mut Window,
 9127        cx: &mut Context<Self>,
 9128    ) {
 9129        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9130            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9131                continue;
 9132            };
 9133            self.edit_breakpoint_at_anchor(
 9134                anchor,
 9135                breakpoint,
 9136                BreakpointEditAction::InvertState,
 9137                cx,
 9138            );
 9139        }
 9140    }
 9141
 9142    pub fn toggle_breakpoint(
 9143        &mut self,
 9144        _: &crate::actions::ToggleBreakpoint,
 9145        window: &mut Window,
 9146        cx: &mut Context<Self>,
 9147    ) {
 9148        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9149            if let Some(breakpoint) = breakpoint {
 9150                self.edit_breakpoint_at_anchor(
 9151                    anchor,
 9152                    breakpoint,
 9153                    BreakpointEditAction::Toggle,
 9154                    cx,
 9155                );
 9156            } else {
 9157                self.edit_breakpoint_at_anchor(
 9158                    anchor,
 9159                    Breakpoint::new_standard(),
 9160                    BreakpointEditAction::Toggle,
 9161                    cx,
 9162                );
 9163            }
 9164        }
 9165    }
 9166
 9167    pub fn edit_breakpoint_at_anchor(
 9168        &mut self,
 9169        breakpoint_position: Anchor,
 9170        breakpoint: Breakpoint,
 9171        edit_action: BreakpointEditAction,
 9172        cx: &mut Context<Self>,
 9173    ) {
 9174        let Some(breakpoint_store) = &self.breakpoint_store else {
 9175            return;
 9176        };
 9177
 9178        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9179            if breakpoint_position == Anchor::min() {
 9180                self.buffer()
 9181                    .read(cx)
 9182                    .excerpt_buffer_ids()
 9183                    .into_iter()
 9184                    .next()
 9185            } else {
 9186                None
 9187            }
 9188        }) else {
 9189            return;
 9190        };
 9191
 9192        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9193            return;
 9194        };
 9195
 9196        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9197            breakpoint_store.toggle_breakpoint(
 9198                buffer,
 9199                (breakpoint_position.text_anchor, breakpoint),
 9200                edit_action,
 9201                cx,
 9202            );
 9203        });
 9204
 9205        cx.notify();
 9206    }
 9207
 9208    #[cfg(any(test, feature = "test-support"))]
 9209    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9210        self.breakpoint_store.clone()
 9211    }
 9212
 9213    pub fn prepare_restore_change(
 9214        &self,
 9215        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9216        hunk: &MultiBufferDiffHunk,
 9217        cx: &mut App,
 9218    ) -> Option<()> {
 9219        if hunk.is_created_file() {
 9220            return None;
 9221        }
 9222        let buffer = self.buffer.read(cx);
 9223        let diff = buffer.diff_for(hunk.buffer_id)?;
 9224        let buffer = buffer.buffer(hunk.buffer_id)?;
 9225        let buffer = buffer.read(cx);
 9226        let original_text = diff
 9227            .read(cx)
 9228            .base_text()
 9229            .as_rope()
 9230            .slice(hunk.diff_base_byte_range.clone());
 9231        let buffer_snapshot = buffer.snapshot();
 9232        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9233        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9234            probe
 9235                .0
 9236                .start
 9237                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9238                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9239        }) {
 9240            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9241            Some(())
 9242        } else {
 9243            None
 9244        }
 9245    }
 9246
 9247    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9248        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9249    }
 9250
 9251    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9252        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9253    }
 9254
 9255    fn manipulate_lines<Fn>(
 9256        &mut self,
 9257        window: &mut Window,
 9258        cx: &mut Context<Self>,
 9259        mut callback: Fn,
 9260    ) where
 9261        Fn: FnMut(&mut Vec<&str>),
 9262    {
 9263        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9264
 9265        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9266        let buffer = self.buffer.read(cx).snapshot(cx);
 9267
 9268        let mut edits = Vec::new();
 9269
 9270        let selections = self.selections.all::<Point>(cx);
 9271        let mut selections = selections.iter().peekable();
 9272        let mut contiguous_row_selections = Vec::new();
 9273        let mut new_selections = Vec::new();
 9274        let mut added_lines = 0;
 9275        let mut removed_lines = 0;
 9276
 9277        while let Some(selection) = selections.next() {
 9278            let (start_row, end_row) = consume_contiguous_rows(
 9279                &mut contiguous_row_selections,
 9280                selection,
 9281                &display_map,
 9282                &mut selections,
 9283            );
 9284
 9285            let start_point = Point::new(start_row.0, 0);
 9286            let end_point = Point::new(
 9287                end_row.previous_row().0,
 9288                buffer.line_len(end_row.previous_row()),
 9289            );
 9290            let text = buffer
 9291                .text_for_range(start_point..end_point)
 9292                .collect::<String>();
 9293
 9294            let mut lines = text.split('\n').collect_vec();
 9295
 9296            let lines_before = lines.len();
 9297            callback(&mut lines);
 9298            let lines_after = lines.len();
 9299
 9300            edits.push((start_point..end_point, lines.join("\n")));
 9301
 9302            // Selections must change based on added and removed line count
 9303            let start_row =
 9304                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9305            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9306            new_selections.push(Selection {
 9307                id: selection.id,
 9308                start: start_row,
 9309                end: end_row,
 9310                goal: SelectionGoal::None,
 9311                reversed: selection.reversed,
 9312            });
 9313
 9314            if lines_after > lines_before {
 9315                added_lines += lines_after - lines_before;
 9316            } else if lines_before > lines_after {
 9317                removed_lines += lines_before - lines_after;
 9318            }
 9319        }
 9320
 9321        self.transact(window, cx, |this, window, cx| {
 9322            let buffer = this.buffer.update(cx, |buffer, cx| {
 9323                buffer.edit(edits, None, cx);
 9324                buffer.snapshot(cx)
 9325            });
 9326
 9327            // Recalculate offsets on newly edited buffer
 9328            let new_selections = new_selections
 9329                .iter()
 9330                .map(|s| {
 9331                    let start_point = Point::new(s.start.0, 0);
 9332                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9333                    Selection {
 9334                        id: s.id,
 9335                        start: buffer.point_to_offset(start_point),
 9336                        end: buffer.point_to_offset(end_point),
 9337                        goal: s.goal,
 9338                        reversed: s.reversed,
 9339                    }
 9340                })
 9341                .collect();
 9342
 9343            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9344                s.select(new_selections);
 9345            });
 9346
 9347            this.request_autoscroll(Autoscroll::fit(), cx);
 9348        });
 9349    }
 9350
 9351    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9352        self.manipulate_text(window, cx, |text| {
 9353            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9354            if has_upper_case_characters {
 9355                text.to_lowercase()
 9356            } else {
 9357                text.to_uppercase()
 9358            }
 9359        })
 9360    }
 9361
 9362    pub fn convert_to_upper_case(
 9363        &mut self,
 9364        _: &ConvertToUpperCase,
 9365        window: &mut Window,
 9366        cx: &mut Context<Self>,
 9367    ) {
 9368        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9369    }
 9370
 9371    pub fn convert_to_lower_case(
 9372        &mut self,
 9373        _: &ConvertToLowerCase,
 9374        window: &mut Window,
 9375        cx: &mut Context<Self>,
 9376    ) {
 9377        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9378    }
 9379
 9380    pub fn convert_to_title_case(
 9381        &mut self,
 9382        _: &ConvertToTitleCase,
 9383        window: &mut Window,
 9384        cx: &mut Context<Self>,
 9385    ) {
 9386        self.manipulate_text(window, cx, |text| {
 9387            text.split('\n')
 9388                .map(|line| line.to_case(Case::Title))
 9389                .join("\n")
 9390        })
 9391    }
 9392
 9393    pub fn convert_to_snake_case(
 9394        &mut self,
 9395        _: &ConvertToSnakeCase,
 9396        window: &mut Window,
 9397        cx: &mut Context<Self>,
 9398    ) {
 9399        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9400    }
 9401
 9402    pub fn convert_to_kebab_case(
 9403        &mut self,
 9404        _: &ConvertToKebabCase,
 9405        window: &mut Window,
 9406        cx: &mut Context<Self>,
 9407    ) {
 9408        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9409    }
 9410
 9411    pub fn convert_to_upper_camel_case(
 9412        &mut self,
 9413        _: &ConvertToUpperCamelCase,
 9414        window: &mut Window,
 9415        cx: &mut Context<Self>,
 9416    ) {
 9417        self.manipulate_text(window, cx, |text| {
 9418            text.split('\n')
 9419                .map(|line| line.to_case(Case::UpperCamel))
 9420                .join("\n")
 9421        })
 9422    }
 9423
 9424    pub fn convert_to_lower_camel_case(
 9425        &mut self,
 9426        _: &ConvertToLowerCamelCase,
 9427        window: &mut Window,
 9428        cx: &mut Context<Self>,
 9429    ) {
 9430        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9431    }
 9432
 9433    pub fn convert_to_opposite_case(
 9434        &mut self,
 9435        _: &ConvertToOppositeCase,
 9436        window: &mut Window,
 9437        cx: &mut Context<Self>,
 9438    ) {
 9439        self.manipulate_text(window, cx, |text| {
 9440            text.chars()
 9441                .fold(String::with_capacity(text.len()), |mut t, c| {
 9442                    if c.is_uppercase() {
 9443                        t.extend(c.to_lowercase());
 9444                    } else {
 9445                        t.extend(c.to_uppercase());
 9446                    }
 9447                    t
 9448                })
 9449        })
 9450    }
 9451
 9452    pub fn convert_to_rot13(
 9453        &mut self,
 9454        _: &ConvertToRot13,
 9455        window: &mut Window,
 9456        cx: &mut Context<Self>,
 9457    ) {
 9458        self.manipulate_text(window, cx, |text| {
 9459            text.chars()
 9460                .map(|c| match c {
 9461                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9462                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9463                    _ => c,
 9464                })
 9465                .collect()
 9466        })
 9467    }
 9468
 9469    pub fn convert_to_rot47(
 9470        &mut self,
 9471        _: &ConvertToRot47,
 9472        window: &mut Window,
 9473        cx: &mut Context<Self>,
 9474    ) {
 9475        self.manipulate_text(window, cx, |text| {
 9476            text.chars()
 9477                .map(|c| {
 9478                    let code_point = c as u32;
 9479                    if code_point >= 33 && code_point <= 126 {
 9480                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9481                    }
 9482                    c
 9483                })
 9484                .collect()
 9485        })
 9486    }
 9487
 9488    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9489    where
 9490        Fn: FnMut(&str) -> String,
 9491    {
 9492        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9493        let buffer = self.buffer.read(cx).snapshot(cx);
 9494
 9495        let mut new_selections = Vec::new();
 9496        let mut edits = Vec::new();
 9497        let mut selection_adjustment = 0i32;
 9498
 9499        for selection in self.selections.all::<usize>(cx) {
 9500            let selection_is_empty = selection.is_empty();
 9501
 9502            let (start, end) = if selection_is_empty {
 9503                let word_range = movement::surrounding_word(
 9504                    &display_map,
 9505                    selection.start.to_display_point(&display_map),
 9506                );
 9507                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9508                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9509                (start, end)
 9510            } else {
 9511                (selection.start, selection.end)
 9512            };
 9513
 9514            let text = buffer.text_for_range(start..end).collect::<String>();
 9515            let old_length = text.len() as i32;
 9516            let text = callback(&text);
 9517
 9518            new_selections.push(Selection {
 9519                start: (start as i32 - selection_adjustment) as usize,
 9520                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9521                goal: SelectionGoal::None,
 9522                ..selection
 9523            });
 9524
 9525            selection_adjustment += old_length - text.len() as i32;
 9526
 9527            edits.push((start..end, text));
 9528        }
 9529
 9530        self.transact(window, cx, |this, window, cx| {
 9531            this.buffer.update(cx, |buffer, cx| {
 9532                buffer.edit(edits, None, cx);
 9533            });
 9534
 9535            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9536                s.select(new_selections);
 9537            });
 9538
 9539            this.request_autoscroll(Autoscroll::fit(), cx);
 9540        });
 9541    }
 9542
 9543    pub fn duplicate(
 9544        &mut self,
 9545        upwards: bool,
 9546        whole_lines: bool,
 9547        window: &mut Window,
 9548        cx: &mut Context<Self>,
 9549    ) {
 9550        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9551
 9552        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9553        let buffer = &display_map.buffer_snapshot;
 9554        let selections = self.selections.all::<Point>(cx);
 9555
 9556        let mut edits = Vec::new();
 9557        let mut selections_iter = selections.iter().peekable();
 9558        while let Some(selection) = selections_iter.next() {
 9559            let mut rows = selection.spanned_rows(false, &display_map);
 9560            // duplicate line-wise
 9561            if whole_lines || selection.start == selection.end {
 9562                // Avoid duplicating the same lines twice.
 9563                while let Some(next_selection) = selections_iter.peek() {
 9564                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9565                    if next_rows.start < rows.end {
 9566                        rows.end = next_rows.end;
 9567                        selections_iter.next().unwrap();
 9568                    } else {
 9569                        break;
 9570                    }
 9571                }
 9572
 9573                // Copy the text from the selected row region and splice it either at the start
 9574                // or end of the region.
 9575                let start = Point::new(rows.start.0, 0);
 9576                let end = Point::new(
 9577                    rows.end.previous_row().0,
 9578                    buffer.line_len(rows.end.previous_row()),
 9579                );
 9580                let text = buffer
 9581                    .text_for_range(start..end)
 9582                    .chain(Some("\n"))
 9583                    .collect::<String>();
 9584                let insert_location = if upwards {
 9585                    Point::new(rows.end.0, 0)
 9586                } else {
 9587                    start
 9588                };
 9589                edits.push((insert_location..insert_location, text));
 9590            } else {
 9591                // duplicate character-wise
 9592                let start = selection.start;
 9593                let end = selection.end;
 9594                let text = buffer.text_for_range(start..end).collect::<String>();
 9595                edits.push((selection.end..selection.end, text));
 9596            }
 9597        }
 9598
 9599        self.transact(window, cx, |this, _, cx| {
 9600            this.buffer.update(cx, |buffer, cx| {
 9601                buffer.edit(edits, None, cx);
 9602            });
 9603
 9604            this.request_autoscroll(Autoscroll::fit(), cx);
 9605        });
 9606    }
 9607
 9608    pub fn duplicate_line_up(
 9609        &mut self,
 9610        _: &DuplicateLineUp,
 9611        window: &mut Window,
 9612        cx: &mut Context<Self>,
 9613    ) {
 9614        self.duplicate(true, true, window, cx);
 9615    }
 9616
 9617    pub fn duplicate_line_down(
 9618        &mut self,
 9619        _: &DuplicateLineDown,
 9620        window: &mut Window,
 9621        cx: &mut Context<Self>,
 9622    ) {
 9623        self.duplicate(false, true, window, cx);
 9624    }
 9625
 9626    pub fn duplicate_selection(
 9627        &mut self,
 9628        _: &DuplicateSelection,
 9629        window: &mut Window,
 9630        cx: &mut Context<Self>,
 9631    ) {
 9632        self.duplicate(false, false, window, cx);
 9633    }
 9634
 9635    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9636        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9637
 9638        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9639        let buffer = self.buffer.read(cx).snapshot(cx);
 9640
 9641        let mut edits = Vec::new();
 9642        let mut unfold_ranges = Vec::new();
 9643        let mut refold_creases = Vec::new();
 9644
 9645        let selections = self.selections.all::<Point>(cx);
 9646        let mut selections = selections.iter().peekable();
 9647        let mut contiguous_row_selections = Vec::new();
 9648        let mut new_selections = Vec::new();
 9649
 9650        while let Some(selection) = selections.next() {
 9651            // Find all the selections that span a contiguous row range
 9652            let (start_row, end_row) = consume_contiguous_rows(
 9653                &mut contiguous_row_selections,
 9654                selection,
 9655                &display_map,
 9656                &mut selections,
 9657            );
 9658
 9659            // Move the text spanned by the row range to be before the line preceding the row range
 9660            if start_row.0 > 0 {
 9661                let range_to_move = Point::new(
 9662                    start_row.previous_row().0,
 9663                    buffer.line_len(start_row.previous_row()),
 9664                )
 9665                    ..Point::new(
 9666                        end_row.previous_row().0,
 9667                        buffer.line_len(end_row.previous_row()),
 9668                    );
 9669                let insertion_point = display_map
 9670                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9671                    .0;
 9672
 9673                // Don't move lines across excerpts
 9674                if buffer
 9675                    .excerpt_containing(insertion_point..range_to_move.end)
 9676                    .is_some()
 9677                {
 9678                    let text = buffer
 9679                        .text_for_range(range_to_move.clone())
 9680                        .flat_map(|s| s.chars())
 9681                        .skip(1)
 9682                        .chain(['\n'])
 9683                        .collect::<String>();
 9684
 9685                    edits.push((
 9686                        buffer.anchor_after(range_to_move.start)
 9687                            ..buffer.anchor_before(range_to_move.end),
 9688                        String::new(),
 9689                    ));
 9690                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9691                    edits.push((insertion_anchor..insertion_anchor, text));
 9692
 9693                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9694
 9695                    // Move selections up
 9696                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9697                        |mut selection| {
 9698                            selection.start.row -= row_delta;
 9699                            selection.end.row -= row_delta;
 9700                            selection
 9701                        },
 9702                    ));
 9703
 9704                    // Move folds up
 9705                    unfold_ranges.push(range_to_move.clone());
 9706                    for fold in display_map.folds_in_range(
 9707                        buffer.anchor_before(range_to_move.start)
 9708                            ..buffer.anchor_after(range_to_move.end),
 9709                    ) {
 9710                        let mut start = fold.range.start.to_point(&buffer);
 9711                        let mut end = fold.range.end.to_point(&buffer);
 9712                        start.row -= row_delta;
 9713                        end.row -= row_delta;
 9714                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9715                    }
 9716                }
 9717            }
 9718
 9719            // If we didn't move line(s), preserve the existing selections
 9720            new_selections.append(&mut contiguous_row_selections);
 9721        }
 9722
 9723        self.transact(window, cx, |this, window, cx| {
 9724            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9725            this.buffer.update(cx, |buffer, cx| {
 9726                for (range, text) in edits {
 9727                    buffer.edit([(range, text)], None, cx);
 9728                }
 9729            });
 9730            this.fold_creases(refold_creases, true, window, cx);
 9731            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9732                s.select(new_selections);
 9733            })
 9734        });
 9735    }
 9736
 9737    pub fn move_line_down(
 9738        &mut self,
 9739        _: &MoveLineDown,
 9740        window: &mut Window,
 9741        cx: &mut Context<Self>,
 9742    ) {
 9743        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9744
 9745        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9746        let buffer = self.buffer.read(cx).snapshot(cx);
 9747
 9748        let mut edits = Vec::new();
 9749        let mut unfold_ranges = Vec::new();
 9750        let mut refold_creases = Vec::new();
 9751
 9752        let selections = self.selections.all::<Point>(cx);
 9753        let mut selections = selections.iter().peekable();
 9754        let mut contiguous_row_selections = Vec::new();
 9755        let mut new_selections = Vec::new();
 9756
 9757        while let Some(selection) = selections.next() {
 9758            // Find all the selections that span a contiguous row range
 9759            let (start_row, end_row) = consume_contiguous_rows(
 9760                &mut contiguous_row_selections,
 9761                selection,
 9762                &display_map,
 9763                &mut selections,
 9764            );
 9765
 9766            // Move the text spanned by the row range to be after the last line of the row range
 9767            if end_row.0 <= buffer.max_point().row {
 9768                let range_to_move =
 9769                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9770                let insertion_point = display_map
 9771                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9772                    .0;
 9773
 9774                // Don't move lines across excerpt boundaries
 9775                if buffer
 9776                    .excerpt_containing(range_to_move.start..insertion_point)
 9777                    .is_some()
 9778                {
 9779                    let mut text = String::from("\n");
 9780                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9781                    text.pop(); // Drop trailing newline
 9782                    edits.push((
 9783                        buffer.anchor_after(range_to_move.start)
 9784                            ..buffer.anchor_before(range_to_move.end),
 9785                        String::new(),
 9786                    ));
 9787                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9788                    edits.push((insertion_anchor..insertion_anchor, text));
 9789
 9790                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9791
 9792                    // Move selections down
 9793                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9794                        |mut selection| {
 9795                            selection.start.row += row_delta;
 9796                            selection.end.row += row_delta;
 9797                            selection
 9798                        },
 9799                    ));
 9800
 9801                    // Move folds down
 9802                    unfold_ranges.push(range_to_move.clone());
 9803                    for fold in display_map.folds_in_range(
 9804                        buffer.anchor_before(range_to_move.start)
 9805                            ..buffer.anchor_after(range_to_move.end),
 9806                    ) {
 9807                        let mut start = fold.range.start.to_point(&buffer);
 9808                        let mut end = fold.range.end.to_point(&buffer);
 9809                        start.row += row_delta;
 9810                        end.row += row_delta;
 9811                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9812                    }
 9813                }
 9814            }
 9815
 9816            // If we didn't move line(s), preserve the existing selections
 9817            new_selections.append(&mut contiguous_row_selections);
 9818        }
 9819
 9820        self.transact(window, cx, |this, window, cx| {
 9821            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9822            this.buffer.update(cx, |buffer, cx| {
 9823                for (range, text) in edits {
 9824                    buffer.edit([(range, text)], None, cx);
 9825                }
 9826            });
 9827            this.fold_creases(refold_creases, true, window, cx);
 9828            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9829                s.select(new_selections)
 9830            });
 9831        });
 9832    }
 9833
 9834    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9835        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9836        let text_layout_details = &self.text_layout_details(window);
 9837        self.transact(window, cx, |this, window, cx| {
 9838            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9839                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9840                s.move_with(|display_map, selection| {
 9841                    if !selection.is_empty() {
 9842                        return;
 9843                    }
 9844
 9845                    let mut head = selection.head();
 9846                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9847                    if head.column() == display_map.line_len(head.row()) {
 9848                        transpose_offset = display_map
 9849                            .buffer_snapshot
 9850                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9851                    }
 9852
 9853                    if transpose_offset == 0 {
 9854                        return;
 9855                    }
 9856
 9857                    *head.column_mut() += 1;
 9858                    head = display_map.clip_point(head, Bias::Right);
 9859                    let goal = SelectionGoal::HorizontalPosition(
 9860                        display_map
 9861                            .x_for_display_point(head, text_layout_details)
 9862                            .into(),
 9863                    );
 9864                    selection.collapse_to(head, goal);
 9865
 9866                    let transpose_start = display_map
 9867                        .buffer_snapshot
 9868                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9869                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9870                        let transpose_end = display_map
 9871                            .buffer_snapshot
 9872                            .clip_offset(transpose_offset + 1, Bias::Right);
 9873                        if let Some(ch) =
 9874                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9875                        {
 9876                            edits.push((transpose_start..transpose_offset, String::new()));
 9877                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9878                        }
 9879                    }
 9880                });
 9881                edits
 9882            });
 9883            this.buffer
 9884                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9885            let selections = this.selections.all::<usize>(cx);
 9886            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9887                s.select(selections);
 9888            });
 9889        });
 9890    }
 9891
 9892    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9893        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9894        self.rewrap_impl(RewrapOptions::default(), cx)
 9895    }
 9896
 9897    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9898        let buffer = self.buffer.read(cx).snapshot(cx);
 9899        let selections = self.selections.all::<Point>(cx);
 9900        let mut selections = selections.iter().peekable();
 9901
 9902        let mut edits = Vec::new();
 9903        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9904
 9905        while let Some(selection) = selections.next() {
 9906            let mut start_row = selection.start.row;
 9907            let mut end_row = selection.end.row;
 9908
 9909            // Skip selections that overlap with a range that has already been rewrapped.
 9910            let selection_range = start_row..end_row;
 9911            if rewrapped_row_ranges
 9912                .iter()
 9913                .any(|range| range.overlaps(&selection_range))
 9914            {
 9915                continue;
 9916            }
 9917
 9918            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9919
 9920            // Since not all lines in the selection may be at the same indent
 9921            // level, choose the indent size that is the most common between all
 9922            // of the lines.
 9923            //
 9924            // If there is a tie, we use the deepest indent.
 9925            let (indent_size, indent_end) = {
 9926                let mut indent_size_occurrences = HashMap::default();
 9927                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9928
 9929                for row in start_row..=end_row {
 9930                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9931                    rows_by_indent_size.entry(indent).or_default().push(row);
 9932                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9933                }
 9934
 9935                let indent_size = indent_size_occurrences
 9936                    .into_iter()
 9937                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9938                    .map(|(indent, _)| indent)
 9939                    .unwrap_or_default();
 9940                let row = rows_by_indent_size[&indent_size][0];
 9941                let indent_end = Point::new(row, indent_size.len);
 9942
 9943                (indent_size, indent_end)
 9944            };
 9945
 9946            let mut line_prefix = indent_size.chars().collect::<String>();
 9947
 9948            let mut inside_comment = false;
 9949            if let Some(comment_prefix) =
 9950                buffer
 9951                    .language_scope_at(selection.head())
 9952                    .and_then(|language| {
 9953                        language
 9954                            .line_comment_prefixes()
 9955                            .iter()
 9956                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9957                            .cloned()
 9958                    })
 9959            {
 9960                line_prefix.push_str(&comment_prefix);
 9961                inside_comment = true;
 9962            }
 9963
 9964            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9965            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9966                RewrapBehavior::InComments => inside_comment,
 9967                RewrapBehavior::InSelections => !selection.is_empty(),
 9968                RewrapBehavior::Anywhere => true,
 9969            };
 9970
 9971            let should_rewrap = options.override_language_settings
 9972                || allow_rewrap_based_on_language
 9973                || self.hard_wrap.is_some();
 9974            if !should_rewrap {
 9975                continue;
 9976            }
 9977
 9978            if selection.is_empty() {
 9979                'expand_upwards: while start_row > 0 {
 9980                    let prev_row = start_row - 1;
 9981                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9982                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9983                    {
 9984                        start_row = prev_row;
 9985                    } else {
 9986                        break 'expand_upwards;
 9987                    }
 9988                }
 9989
 9990                'expand_downwards: while end_row < buffer.max_point().row {
 9991                    let next_row = end_row + 1;
 9992                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9993                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9994                    {
 9995                        end_row = next_row;
 9996                    } else {
 9997                        break 'expand_downwards;
 9998                    }
 9999                }
10000            }
10001
10002            let start = Point::new(start_row, 0);
10003            let start_offset = start.to_offset(&buffer);
10004            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10005            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10006            let Some(lines_without_prefixes) = selection_text
10007                .lines()
10008                .map(|line| {
10009                    line.strip_prefix(&line_prefix)
10010                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10011                        .ok_or_else(|| {
10012                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10013                        })
10014                })
10015                .collect::<Result<Vec<_>, _>>()
10016                .log_err()
10017            else {
10018                continue;
10019            };
10020
10021            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10022                buffer
10023                    .language_settings_at(Point::new(start_row, 0), cx)
10024                    .preferred_line_length as usize
10025            });
10026            let wrapped_text = wrap_with_prefix(
10027                line_prefix,
10028                lines_without_prefixes.join("\n"),
10029                wrap_column,
10030                tab_size,
10031                options.preserve_existing_whitespace,
10032            );
10033
10034            // TODO: should always use char-based diff while still supporting cursor behavior that
10035            // matches vim.
10036            let mut diff_options = DiffOptions::default();
10037            if options.override_language_settings {
10038                diff_options.max_word_diff_len = 0;
10039                diff_options.max_word_diff_line_count = 0;
10040            } else {
10041                diff_options.max_word_diff_len = usize::MAX;
10042                diff_options.max_word_diff_line_count = usize::MAX;
10043            }
10044
10045            for (old_range, new_text) in
10046                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10047            {
10048                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10049                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10050                edits.push((edit_start..edit_end, new_text));
10051            }
10052
10053            rewrapped_row_ranges.push(start_row..=end_row);
10054        }
10055
10056        self.buffer
10057            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10058    }
10059
10060    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10061        let mut text = String::new();
10062        let buffer = self.buffer.read(cx).snapshot(cx);
10063        let mut selections = self.selections.all::<Point>(cx);
10064        let mut clipboard_selections = Vec::with_capacity(selections.len());
10065        {
10066            let max_point = buffer.max_point();
10067            let mut is_first = true;
10068            for selection in &mut selections {
10069                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10070                if is_entire_line {
10071                    selection.start = Point::new(selection.start.row, 0);
10072                    if !selection.is_empty() && selection.end.column == 0 {
10073                        selection.end = cmp::min(max_point, selection.end);
10074                    } else {
10075                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10076                    }
10077                    selection.goal = SelectionGoal::None;
10078                }
10079                if is_first {
10080                    is_first = false;
10081                } else {
10082                    text += "\n";
10083                }
10084                let mut len = 0;
10085                for chunk in buffer.text_for_range(selection.start..selection.end) {
10086                    text.push_str(chunk);
10087                    len += chunk.len();
10088                }
10089                clipboard_selections.push(ClipboardSelection {
10090                    len,
10091                    is_entire_line,
10092                    first_line_indent: buffer
10093                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10094                        .len,
10095                });
10096            }
10097        }
10098
10099        self.transact(window, cx, |this, window, cx| {
10100            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10101                s.select(selections);
10102            });
10103            this.insert("", window, cx);
10104        });
10105        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10106    }
10107
10108    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10109        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10110        let item = self.cut_common(window, cx);
10111        cx.write_to_clipboard(item);
10112    }
10113
10114    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10115        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10116        self.change_selections(None, window, cx, |s| {
10117            s.move_with(|snapshot, sel| {
10118                if sel.is_empty() {
10119                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10120                }
10121            });
10122        });
10123        let item = self.cut_common(window, cx);
10124        cx.set_global(KillRing(item))
10125    }
10126
10127    pub fn kill_ring_yank(
10128        &mut self,
10129        _: &KillRingYank,
10130        window: &mut Window,
10131        cx: &mut Context<Self>,
10132    ) {
10133        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10134        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10135            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10136                (kill_ring.text().to_string(), kill_ring.metadata_json())
10137            } else {
10138                return;
10139            }
10140        } else {
10141            return;
10142        };
10143        self.do_paste(&text, metadata, false, window, cx);
10144    }
10145
10146    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10147        self.do_copy(true, cx);
10148    }
10149
10150    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10151        self.do_copy(false, cx);
10152    }
10153
10154    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10155        let selections = self.selections.all::<Point>(cx);
10156        let buffer = self.buffer.read(cx).read(cx);
10157        let mut text = String::new();
10158
10159        let mut clipboard_selections = Vec::with_capacity(selections.len());
10160        {
10161            let max_point = buffer.max_point();
10162            let mut is_first = true;
10163            for selection in &selections {
10164                let mut start = selection.start;
10165                let mut end = selection.end;
10166                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10167                if is_entire_line {
10168                    start = Point::new(start.row, 0);
10169                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10170                }
10171
10172                let mut trimmed_selections = Vec::new();
10173                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10174                    let row = MultiBufferRow(start.row);
10175                    let first_indent = buffer.indent_size_for_line(row);
10176                    if first_indent.len == 0 || start.column > first_indent.len {
10177                        trimmed_selections.push(start..end);
10178                    } else {
10179                        trimmed_selections.push(
10180                            Point::new(row.0, first_indent.len)
10181                                ..Point::new(row.0, buffer.line_len(row)),
10182                        );
10183                        for row in start.row + 1..=end.row {
10184                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10185                            if row == end.row {
10186                                line_len = end.column;
10187                            }
10188                            if line_len == 0 {
10189                                trimmed_selections
10190                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10191                                continue;
10192                            }
10193                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10194                            if row_indent_size.len >= first_indent.len {
10195                                trimmed_selections.push(
10196                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10197                                );
10198                            } else {
10199                                trimmed_selections.clear();
10200                                trimmed_selections.push(start..end);
10201                                break;
10202                            }
10203                        }
10204                    }
10205                } else {
10206                    trimmed_selections.push(start..end);
10207                }
10208
10209                for trimmed_range in trimmed_selections {
10210                    if is_first {
10211                        is_first = false;
10212                    } else {
10213                        text += "\n";
10214                    }
10215                    let mut len = 0;
10216                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10217                        text.push_str(chunk);
10218                        len += chunk.len();
10219                    }
10220                    clipboard_selections.push(ClipboardSelection {
10221                        len,
10222                        is_entire_line,
10223                        first_line_indent: buffer
10224                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10225                            .len,
10226                    });
10227                }
10228            }
10229        }
10230
10231        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10232            text,
10233            clipboard_selections,
10234        ));
10235    }
10236
10237    pub fn do_paste(
10238        &mut self,
10239        text: &String,
10240        clipboard_selections: Option<Vec<ClipboardSelection>>,
10241        handle_entire_lines: bool,
10242        window: &mut Window,
10243        cx: &mut Context<Self>,
10244    ) {
10245        if self.read_only(cx) {
10246            return;
10247        }
10248
10249        let clipboard_text = Cow::Borrowed(text);
10250
10251        self.transact(window, cx, |this, window, cx| {
10252            if let Some(mut clipboard_selections) = clipboard_selections {
10253                let old_selections = this.selections.all::<usize>(cx);
10254                let all_selections_were_entire_line =
10255                    clipboard_selections.iter().all(|s| s.is_entire_line);
10256                let first_selection_indent_column =
10257                    clipboard_selections.first().map(|s| s.first_line_indent);
10258                if clipboard_selections.len() != old_selections.len() {
10259                    clipboard_selections.drain(..);
10260                }
10261                let cursor_offset = this.selections.last::<usize>(cx).head();
10262                let mut auto_indent_on_paste = true;
10263
10264                this.buffer.update(cx, |buffer, cx| {
10265                    let snapshot = buffer.read(cx);
10266                    auto_indent_on_paste = snapshot
10267                        .language_settings_at(cursor_offset, cx)
10268                        .auto_indent_on_paste;
10269
10270                    let mut start_offset = 0;
10271                    let mut edits = Vec::new();
10272                    let mut original_indent_columns = Vec::new();
10273                    for (ix, selection) in old_selections.iter().enumerate() {
10274                        let to_insert;
10275                        let entire_line;
10276                        let original_indent_column;
10277                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10278                            let end_offset = start_offset + clipboard_selection.len;
10279                            to_insert = &clipboard_text[start_offset..end_offset];
10280                            entire_line = clipboard_selection.is_entire_line;
10281                            start_offset = end_offset + 1;
10282                            original_indent_column = Some(clipboard_selection.first_line_indent);
10283                        } else {
10284                            to_insert = clipboard_text.as_str();
10285                            entire_line = all_selections_were_entire_line;
10286                            original_indent_column = first_selection_indent_column
10287                        }
10288
10289                        // If the corresponding selection was empty when this slice of the
10290                        // clipboard text was written, then the entire line containing the
10291                        // selection was copied. If this selection is also currently empty,
10292                        // then paste the line before the current line of the buffer.
10293                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10294                            let column = selection.start.to_point(&snapshot).column as usize;
10295                            let line_start = selection.start - column;
10296                            line_start..line_start
10297                        } else {
10298                            selection.range()
10299                        };
10300
10301                        edits.push((range, to_insert));
10302                        original_indent_columns.push(original_indent_column);
10303                    }
10304                    drop(snapshot);
10305
10306                    buffer.edit(
10307                        edits,
10308                        if auto_indent_on_paste {
10309                            Some(AutoindentMode::Block {
10310                                original_indent_columns,
10311                            })
10312                        } else {
10313                            None
10314                        },
10315                        cx,
10316                    );
10317                });
10318
10319                let selections = this.selections.all::<usize>(cx);
10320                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10321                    s.select(selections)
10322                });
10323            } else {
10324                this.insert(&clipboard_text, window, cx);
10325            }
10326        });
10327    }
10328
10329    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10330        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10331        if let Some(item) = cx.read_from_clipboard() {
10332            let entries = item.entries();
10333
10334            match entries.first() {
10335                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10336                // of all the pasted entries.
10337                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10338                    .do_paste(
10339                        clipboard_string.text(),
10340                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10341                        true,
10342                        window,
10343                        cx,
10344                    ),
10345                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10346            }
10347        }
10348    }
10349
10350    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10351        if self.read_only(cx) {
10352            return;
10353        }
10354
10355        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10356
10357        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10358            if let Some((selections, _)) =
10359                self.selection_history.transaction(transaction_id).cloned()
10360            {
10361                self.change_selections(None, window, cx, |s| {
10362                    s.select_anchors(selections.to_vec());
10363                });
10364            } else {
10365                log::error!(
10366                    "No entry in selection_history found for undo. \
10367                     This may correspond to a bug where undo does not update the selection. \
10368                     If this is occurring, please add details to \
10369                     https://github.com/zed-industries/zed/issues/22692"
10370                );
10371            }
10372            self.request_autoscroll(Autoscroll::fit(), cx);
10373            self.unmark_text(window, cx);
10374            self.refresh_inline_completion(true, false, window, cx);
10375            cx.emit(EditorEvent::Edited { transaction_id });
10376            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10377        }
10378    }
10379
10380    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10381        if self.read_only(cx) {
10382            return;
10383        }
10384
10385        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10386
10387        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10388            if let Some((_, Some(selections))) =
10389                self.selection_history.transaction(transaction_id).cloned()
10390            {
10391                self.change_selections(None, window, cx, |s| {
10392                    s.select_anchors(selections.to_vec());
10393                });
10394            } else {
10395                log::error!(
10396                    "No entry in selection_history found for redo. \
10397                     This may correspond to a bug where undo does not update the selection. \
10398                     If this is occurring, please add details to \
10399                     https://github.com/zed-industries/zed/issues/22692"
10400                );
10401            }
10402            self.request_autoscroll(Autoscroll::fit(), cx);
10403            self.unmark_text(window, cx);
10404            self.refresh_inline_completion(true, false, window, cx);
10405            cx.emit(EditorEvent::Edited { transaction_id });
10406        }
10407    }
10408
10409    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10410        self.buffer
10411            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10412    }
10413
10414    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10415        self.buffer
10416            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10417    }
10418
10419    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10420        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10421        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10422            s.move_with(|map, selection| {
10423                let cursor = if selection.is_empty() {
10424                    movement::left(map, selection.start)
10425                } else {
10426                    selection.start
10427                };
10428                selection.collapse_to(cursor, SelectionGoal::None);
10429            });
10430        })
10431    }
10432
10433    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10434        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10435        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10436            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10437        })
10438    }
10439
10440    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10441        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10442        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10443            s.move_with(|map, selection| {
10444                let cursor = if selection.is_empty() {
10445                    movement::right(map, selection.end)
10446                } else {
10447                    selection.end
10448                };
10449                selection.collapse_to(cursor, SelectionGoal::None)
10450            });
10451        })
10452    }
10453
10454    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10455        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10456        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10457            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10458        })
10459    }
10460
10461    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10462        if self.take_rename(true, window, cx).is_some() {
10463            return;
10464        }
10465
10466        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10467            cx.propagate();
10468            return;
10469        }
10470
10471        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10472
10473        let text_layout_details = &self.text_layout_details(window);
10474        let selection_count = self.selections.count();
10475        let first_selection = self.selections.first_anchor();
10476
10477        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10478            s.move_with(|map, selection| {
10479                if !selection.is_empty() {
10480                    selection.goal = SelectionGoal::None;
10481                }
10482                let (cursor, goal) = movement::up(
10483                    map,
10484                    selection.start,
10485                    selection.goal,
10486                    false,
10487                    text_layout_details,
10488                );
10489                selection.collapse_to(cursor, goal);
10490            });
10491        });
10492
10493        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10494        {
10495            cx.propagate();
10496        }
10497    }
10498
10499    pub fn move_up_by_lines(
10500        &mut self,
10501        action: &MoveUpByLines,
10502        window: &mut Window,
10503        cx: &mut Context<Self>,
10504    ) {
10505        if self.take_rename(true, window, cx).is_some() {
10506            return;
10507        }
10508
10509        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10510            cx.propagate();
10511            return;
10512        }
10513
10514        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10515
10516        let text_layout_details = &self.text_layout_details(window);
10517
10518        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10519            s.move_with(|map, selection| {
10520                if !selection.is_empty() {
10521                    selection.goal = SelectionGoal::None;
10522                }
10523                let (cursor, goal) = movement::up_by_rows(
10524                    map,
10525                    selection.start,
10526                    action.lines,
10527                    selection.goal,
10528                    false,
10529                    text_layout_details,
10530                );
10531                selection.collapse_to(cursor, goal);
10532            });
10533        })
10534    }
10535
10536    pub fn move_down_by_lines(
10537        &mut self,
10538        action: &MoveDownByLines,
10539        window: &mut Window,
10540        cx: &mut Context<Self>,
10541    ) {
10542        if self.take_rename(true, window, cx).is_some() {
10543            return;
10544        }
10545
10546        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10547            cx.propagate();
10548            return;
10549        }
10550
10551        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10552
10553        let text_layout_details = &self.text_layout_details(window);
10554
10555        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10556            s.move_with(|map, selection| {
10557                if !selection.is_empty() {
10558                    selection.goal = SelectionGoal::None;
10559                }
10560                let (cursor, goal) = movement::down_by_rows(
10561                    map,
10562                    selection.start,
10563                    action.lines,
10564                    selection.goal,
10565                    false,
10566                    text_layout_details,
10567                );
10568                selection.collapse_to(cursor, goal);
10569            });
10570        })
10571    }
10572
10573    pub fn select_down_by_lines(
10574        &mut self,
10575        action: &SelectDownByLines,
10576        window: &mut Window,
10577        cx: &mut Context<Self>,
10578    ) {
10579        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10580        let text_layout_details = &self.text_layout_details(window);
10581        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10582            s.move_heads_with(|map, head, goal| {
10583                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10584            })
10585        })
10586    }
10587
10588    pub fn select_up_by_lines(
10589        &mut self,
10590        action: &SelectUpByLines,
10591        window: &mut Window,
10592        cx: &mut Context<Self>,
10593    ) {
10594        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10595        let text_layout_details = &self.text_layout_details(window);
10596        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10597            s.move_heads_with(|map, head, goal| {
10598                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10599            })
10600        })
10601    }
10602
10603    pub fn select_page_up(
10604        &mut self,
10605        _: &SelectPageUp,
10606        window: &mut Window,
10607        cx: &mut Context<Self>,
10608    ) {
10609        let Some(row_count) = self.visible_row_count() else {
10610            return;
10611        };
10612
10613        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10614
10615        let text_layout_details = &self.text_layout_details(window);
10616
10617        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10618            s.move_heads_with(|map, head, goal| {
10619                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10620            })
10621        })
10622    }
10623
10624    pub fn move_page_up(
10625        &mut self,
10626        action: &MovePageUp,
10627        window: &mut Window,
10628        cx: &mut Context<Self>,
10629    ) {
10630        if self.take_rename(true, window, cx).is_some() {
10631            return;
10632        }
10633
10634        if self
10635            .context_menu
10636            .borrow_mut()
10637            .as_mut()
10638            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10639            .unwrap_or(false)
10640        {
10641            return;
10642        }
10643
10644        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10645            cx.propagate();
10646            return;
10647        }
10648
10649        let Some(row_count) = self.visible_row_count() else {
10650            return;
10651        };
10652
10653        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10654
10655        let autoscroll = if action.center_cursor {
10656            Autoscroll::center()
10657        } else {
10658            Autoscroll::fit()
10659        };
10660
10661        let text_layout_details = &self.text_layout_details(window);
10662
10663        self.change_selections(Some(autoscroll), window, cx, |s| {
10664            s.move_with(|map, selection| {
10665                if !selection.is_empty() {
10666                    selection.goal = SelectionGoal::None;
10667                }
10668                let (cursor, goal) = movement::up_by_rows(
10669                    map,
10670                    selection.end,
10671                    row_count,
10672                    selection.goal,
10673                    false,
10674                    text_layout_details,
10675                );
10676                selection.collapse_to(cursor, goal);
10677            });
10678        });
10679    }
10680
10681    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10682        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10683        let text_layout_details = &self.text_layout_details(window);
10684        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10685            s.move_heads_with(|map, head, goal| {
10686                movement::up(map, head, goal, false, text_layout_details)
10687            })
10688        })
10689    }
10690
10691    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10692        self.take_rename(true, window, cx);
10693
10694        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10695            cx.propagate();
10696            return;
10697        }
10698
10699        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10700
10701        let text_layout_details = &self.text_layout_details(window);
10702        let selection_count = self.selections.count();
10703        let first_selection = self.selections.first_anchor();
10704
10705        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10706            s.move_with(|map, selection| {
10707                if !selection.is_empty() {
10708                    selection.goal = SelectionGoal::None;
10709                }
10710                let (cursor, goal) = movement::down(
10711                    map,
10712                    selection.end,
10713                    selection.goal,
10714                    false,
10715                    text_layout_details,
10716                );
10717                selection.collapse_to(cursor, goal);
10718            });
10719        });
10720
10721        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10722        {
10723            cx.propagate();
10724        }
10725    }
10726
10727    pub fn select_page_down(
10728        &mut self,
10729        _: &SelectPageDown,
10730        window: &mut Window,
10731        cx: &mut Context<Self>,
10732    ) {
10733        let Some(row_count) = self.visible_row_count() else {
10734            return;
10735        };
10736
10737        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10738
10739        let text_layout_details = &self.text_layout_details(window);
10740
10741        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10742            s.move_heads_with(|map, head, goal| {
10743                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10744            })
10745        })
10746    }
10747
10748    pub fn move_page_down(
10749        &mut self,
10750        action: &MovePageDown,
10751        window: &mut Window,
10752        cx: &mut Context<Self>,
10753    ) {
10754        if self.take_rename(true, window, cx).is_some() {
10755            return;
10756        }
10757
10758        if self
10759            .context_menu
10760            .borrow_mut()
10761            .as_mut()
10762            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10763            .unwrap_or(false)
10764        {
10765            return;
10766        }
10767
10768        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10769            cx.propagate();
10770            return;
10771        }
10772
10773        let Some(row_count) = self.visible_row_count() else {
10774            return;
10775        };
10776
10777        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10778
10779        let autoscroll = if action.center_cursor {
10780            Autoscroll::center()
10781        } else {
10782            Autoscroll::fit()
10783        };
10784
10785        let text_layout_details = &self.text_layout_details(window);
10786        self.change_selections(Some(autoscroll), window, cx, |s| {
10787            s.move_with(|map, selection| {
10788                if !selection.is_empty() {
10789                    selection.goal = SelectionGoal::None;
10790                }
10791                let (cursor, goal) = movement::down_by_rows(
10792                    map,
10793                    selection.end,
10794                    row_count,
10795                    selection.goal,
10796                    false,
10797                    text_layout_details,
10798                );
10799                selection.collapse_to(cursor, goal);
10800            });
10801        });
10802    }
10803
10804    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10805        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10806        let text_layout_details = &self.text_layout_details(window);
10807        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10808            s.move_heads_with(|map, head, goal| {
10809                movement::down(map, head, goal, false, text_layout_details)
10810            })
10811        });
10812    }
10813
10814    pub fn context_menu_first(
10815        &mut self,
10816        _: &ContextMenuFirst,
10817        _window: &mut Window,
10818        cx: &mut Context<Self>,
10819    ) {
10820        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10821            context_menu.select_first(self.completion_provider.as_deref(), cx);
10822        }
10823    }
10824
10825    pub fn context_menu_prev(
10826        &mut self,
10827        _: &ContextMenuPrevious,
10828        _window: &mut Window,
10829        cx: &mut Context<Self>,
10830    ) {
10831        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10832            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10833        }
10834    }
10835
10836    pub fn context_menu_next(
10837        &mut self,
10838        _: &ContextMenuNext,
10839        _window: &mut Window,
10840        cx: &mut Context<Self>,
10841    ) {
10842        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10843            context_menu.select_next(self.completion_provider.as_deref(), cx);
10844        }
10845    }
10846
10847    pub fn context_menu_last(
10848        &mut self,
10849        _: &ContextMenuLast,
10850        _window: &mut Window,
10851        cx: &mut Context<Self>,
10852    ) {
10853        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10854            context_menu.select_last(self.completion_provider.as_deref(), cx);
10855        }
10856    }
10857
10858    pub fn move_to_previous_word_start(
10859        &mut self,
10860        _: &MoveToPreviousWordStart,
10861        window: &mut Window,
10862        cx: &mut Context<Self>,
10863    ) {
10864        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10865        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10866            s.move_cursors_with(|map, head, _| {
10867                (
10868                    movement::previous_word_start(map, head),
10869                    SelectionGoal::None,
10870                )
10871            });
10872        })
10873    }
10874
10875    pub fn move_to_previous_subword_start(
10876        &mut self,
10877        _: &MoveToPreviousSubwordStart,
10878        window: &mut Window,
10879        cx: &mut Context<Self>,
10880    ) {
10881        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10882        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10883            s.move_cursors_with(|map, head, _| {
10884                (
10885                    movement::previous_subword_start(map, head),
10886                    SelectionGoal::None,
10887                )
10888            });
10889        })
10890    }
10891
10892    pub fn select_to_previous_word_start(
10893        &mut self,
10894        _: &SelectToPreviousWordStart,
10895        window: &mut Window,
10896        cx: &mut Context<Self>,
10897    ) {
10898        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10899        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10900            s.move_heads_with(|map, head, _| {
10901                (
10902                    movement::previous_word_start(map, head),
10903                    SelectionGoal::None,
10904                )
10905            });
10906        })
10907    }
10908
10909    pub fn select_to_previous_subword_start(
10910        &mut self,
10911        _: &SelectToPreviousSubwordStart,
10912        window: &mut Window,
10913        cx: &mut Context<Self>,
10914    ) {
10915        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10916        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10917            s.move_heads_with(|map, head, _| {
10918                (
10919                    movement::previous_subword_start(map, head),
10920                    SelectionGoal::None,
10921                )
10922            });
10923        })
10924    }
10925
10926    pub fn delete_to_previous_word_start(
10927        &mut self,
10928        action: &DeleteToPreviousWordStart,
10929        window: &mut Window,
10930        cx: &mut Context<Self>,
10931    ) {
10932        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10933        self.transact(window, cx, |this, window, cx| {
10934            this.select_autoclose_pair(window, cx);
10935            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10936                s.move_with(|map, selection| {
10937                    if selection.is_empty() {
10938                        let cursor = if action.ignore_newlines {
10939                            movement::previous_word_start(map, selection.head())
10940                        } else {
10941                            movement::previous_word_start_or_newline(map, selection.head())
10942                        };
10943                        selection.set_head(cursor, SelectionGoal::None);
10944                    }
10945                });
10946            });
10947            this.insert("", window, cx);
10948        });
10949    }
10950
10951    pub fn delete_to_previous_subword_start(
10952        &mut self,
10953        _: &DeleteToPreviousSubwordStart,
10954        window: &mut Window,
10955        cx: &mut Context<Self>,
10956    ) {
10957        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10958        self.transact(window, cx, |this, window, cx| {
10959            this.select_autoclose_pair(window, cx);
10960            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10961                s.move_with(|map, selection| {
10962                    if selection.is_empty() {
10963                        let cursor = movement::previous_subword_start(map, selection.head());
10964                        selection.set_head(cursor, SelectionGoal::None);
10965                    }
10966                });
10967            });
10968            this.insert("", window, cx);
10969        });
10970    }
10971
10972    pub fn move_to_next_word_end(
10973        &mut self,
10974        _: &MoveToNextWordEnd,
10975        window: &mut Window,
10976        cx: &mut Context<Self>,
10977    ) {
10978        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10979        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10980            s.move_cursors_with(|map, head, _| {
10981                (movement::next_word_end(map, head), SelectionGoal::None)
10982            });
10983        })
10984    }
10985
10986    pub fn move_to_next_subword_end(
10987        &mut self,
10988        _: &MoveToNextSubwordEnd,
10989        window: &mut Window,
10990        cx: &mut Context<Self>,
10991    ) {
10992        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10993        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10994            s.move_cursors_with(|map, head, _| {
10995                (movement::next_subword_end(map, head), SelectionGoal::None)
10996            });
10997        })
10998    }
10999
11000    pub fn select_to_next_word_end(
11001        &mut self,
11002        _: &SelectToNextWordEnd,
11003        window: &mut Window,
11004        cx: &mut Context<Self>,
11005    ) {
11006        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11007        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11008            s.move_heads_with(|map, head, _| {
11009                (movement::next_word_end(map, head), SelectionGoal::None)
11010            });
11011        })
11012    }
11013
11014    pub fn select_to_next_subword_end(
11015        &mut self,
11016        _: &SelectToNextSubwordEnd,
11017        window: &mut Window,
11018        cx: &mut Context<Self>,
11019    ) {
11020        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11021        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11022            s.move_heads_with(|map, head, _| {
11023                (movement::next_subword_end(map, head), SelectionGoal::None)
11024            });
11025        })
11026    }
11027
11028    pub fn delete_to_next_word_end(
11029        &mut self,
11030        action: &DeleteToNextWordEnd,
11031        window: &mut Window,
11032        cx: &mut Context<Self>,
11033    ) {
11034        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11035        self.transact(window, cx, |this, window, cx| {
11036            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11037                s.move_with(|map, selection| {
11038                    if selection.is_empty() {
11039                        let cursor = if action.ignore_newlines {
11040                            movement::next_word_end(map, selection.head())
11041                        } else {
11042                            movement::next_word_end_or_newline(map, selection.head())
11043                        };
11044                        selection.set_head(cursor, SelectionGoal::None);
11045                    }
11046                });
11047            });
11048            this.insert("", window, cx);
11049        });
11050    }
11051
11052    pub fn delete_to_next_subword_end(
11053        &mut self,
11054        _: &DeleteToNextSubwordEnd,
11055        window: &mut Window,
11056        cx: &mut Context<Self>,
11057    ) {
11058        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11059        self.transact(window, cx, |this, window, cx| {
11060            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11061                s.move_with(|map, selection| {
11062                    if selection.is_empty() {
11063                        let cursor = movement::next_subword_end(map, selection.head());
11064                        selection.set_head(cursor, SelectionGoal::None);
11065                    }
11066                });
11067            });
11068            this.insert("", window, cx);
11069        });
11070    }
11071
11072    pub fn move_to_beginning_of_line(
11073        &mut self,
11074        action: &MoveToBeginningOfLine,
11075        window: &mut Window,
11076        cx: &mut Context<Self>,
11077    ) {
11078        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11079        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11080            s.move_cursors_with(|map, head, _| {
11081                (
11082                    movement::indented_line_beginning(
11083                        map,
11084                        head,
11085                        action.stop_at_soft_wraps,
11086                        action.stop_at_indent,
11087                    ),
11088                    SelectionGoal::None,
11089                )
11090            });
11091        })
11092    }
11093
11094    pub fn select_to_beginning_of_line(
11095        &mut self,
11096        action: &SelectToBeginningOfLine,
11097        window: &mut Window,
11098        cx: &mut Context<Self>,
11099    ) {
11100        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11101        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11102            s.move_heads_with(|map, head, _| {
11103                (
11104                    movement::indented_line_beginning(
11105                        map,
11106                        head,
11107                        action.stop_at_soft_wraps,
11108                        action.stop_at_indent,
11109                    ),
11110                    SelectionGoal::None,
11111                )
11112            });
11113        });
11114    }
11115
11116    pub fn delete_to_beginning_of_line(
11117        &mut self,
11118        action: &DeleteToBeginningOfLine,
11119        window: &mut Window,
11120        cx: &mut Context<Self>,
11121    ) {
11122        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11123        self.transact(window, cx, |this, window, cx| {
11124            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11125                s.move_with(|_, selection| {
11126                    selection.reversed = true;
11127                });
11128            });
11129
11130            this.select_to_beginning_of_line(
11131                &SelectToBeginningOfLine {
11132                    stop_at_soft_wraps: false,
11133                    stop_at_indent: action.stop_at_indent,
11134                },
11135                window,
11136                cx,
11137            );
11138            this.backspace(&Backspace, window, cx);
11139        });
11140    }
11141
11142    pub fn move_to_end_of_line(
11143        &mut self,
11144        action: &MoveToEndOfLine,
11145        window: &mut Window,
11146        cx: &mut Context<Self>,
11147    ) {
11148        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11149        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11150            s.move_cursors_with(|map, head, _| {
11151                (
11152                    movement::line_end(map, head, action.stop_at_soft_wraps),
11153                    SelectionGoal::None,
11154                )
11155            });
11156        })
11157    }
11158
11159    pub fn select_to_end_of_line(
11160        &mut self,
11161        action: &SelectToEndOfLine,
11162        window: &mut Window,
11163        cx: &mut Context<Self>,
11164    ) {
11165        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11166        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11167            s.move_heads_with(|map, head, _| {
11168                (
11169                    movement::line_end(map, head, action.stop_at_soft_wraps),
11170                    SelectionGoal::None,
11171                )
11172            });
11173        })
11174    }
11175
11176    pub fn delete_to_end_of_line(
11177        &mut self,
11178        _: &DeleteToEndOfLine,
11179        window: &mut Window,
11180        cx: &mut Context<Self>,
11181    ) {
11182        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11183        self.transact(window, cx, |this, window, cx| {
11184            this.select_to_end_of_line(
11185                &SelectToEndOfLine {
11186                    stop_at_soft_wraps: false,
11187                },
11188                window,
11189                cx,
11190            );
11191            this.delete(&Delete, window, cx);
11192        });
11193    }
11194
11195    pub fn cut_to_end_of_line(
11196        &mut self,
11197        _: &CutToEndOfLine,
11198        window: &mut Window,
11199        cx: &mut Context<Self>,
11200    ) {
11201        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11202        self.transact(window, cx, |this, window, cx| {
11203            this.select_to_end_of_line(
11204                &SelectToEndOfLine {
11205                    stop_at_soft_wraps: false,
11206                },
11207                window,
11208                cx,
11209            );
11210            this.cut(&Cut, window, cx);
11211        });
11212    }
11213
11214    pub fn move_to_start_of_paragraph(
11215        &mut self,
11216        _: &MoveToStartOfParagraph,
11217        window: &mut Window,
11218        cx: &mut Context<Self>,
11219    ) {
11220        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11221            cx.propagate();
11222            return;
11223        }
11224        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11225        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11226            s.move_with(|map, selection| {
11227                selection.collapse_to(
11228                    movement::start_of_paragraph(map, selection.head(), 1),
11229                    SelectionGoal::None,
11230                )
11231            });
11232        })
11233    }
11234
11235    pub fn move_to_end_of_paragraph(
11236        &mut self,
11237        _: &MoveToEndOfParagraph,
11238        window: &mut Window,
11239        cx: &mut Context<Self>,
11240    ) {
11241        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11242            cx.propagate();
11243            return;
11244        }
11245        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11246        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11247            s.move_with(|map, selection| {
11248                selection.collapse_to(
11249                    movement::end_of_paragraph(map, selection.head(), 1),
11250                    SelectionGoal::None,
11251                )
11252            });
11253        })
11254    }
11255
11256    pub fn select_to_start_of_paragraph(
11257        &mut self,
11258        _: &SelectToStartOfParagraph,
11259        window: &mut Window,
11260        cx: &mut Context<Self>,
11261    ) {
11262        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11263            cx.propagate();
11264            return;
11265        }
11266        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11267        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11268            s.move_heads_with(|map, head, _| {
11269                (
11270                    movement::start_of_paragraph(map, head, 1),
11271                    SelectionGoal::None,
11272                )
11273            });
11274        })
11275    }
11276
11277    pub fn select_to_end_of_paragraph(
11278        &mut self,
11279        _: &SelectToEndOfParagraph,
11280        window: &mut Window,
11281        cx: &mut Context<Self>,
11282    ) {
11283        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11284            cx.propagate();
11285            return;
11286        }
11287        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11288        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11289            s.move_heads_with(|map, head, _| {
11290                (
11291                    movement::end_of_paragraph(map, head, 1),
11292                    SelectionGoal::None,
11293                )
11294            });
11295        })
11296    }
11297
11298    pub fn move_to_start_of_excerpt(
11299        &mut self,
11300        _: &MoveToStartOfExcerpt,
11301        window: &mut Window,
11302        cx: &mut Context<Self>,
11303    ) {
11304        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11305            cx.propagate();
11306            return;
11307        }
11308        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11309        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11310            s.move_with(|map, selection| {
11311                selection.collapse_to(
11312                    movement::start_of_excerpt(
11313                        map,
11314                        selection.head(),
11315                        workspace::searchable::Direction::Prev,
11316                    ),
11317                    SelectionGoal::None,
11318                )
11319            });
11320        })
11321    }
11322
11323    pub fn move_to_start_of_next_excerpt(
11324        &mut self,
11325        _: &MoveToStartOfNextExcerpt,
11326        window: &mut Window,
11327        cx: &mut Context<Self>,
11328    ) {
11329        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11330            cx.propagate();
11331            return;
11332        }
11333
11334        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11335            s.move_with(|map, selection| {
11336                selection.collapse_to(
11337                    movement::start_of_excerpt(
11338                        map,
11339                        selection.head(),
11340                        workspace::searchable::Direction::Next,
11341                    ),
11342                    SelectionGoal::None,
11343                )
11344            });
11345        })
11346    }
11347
11348    pub fn move_to_end_of_excerpt(
11349        &mut self,
11350        _: &MoveToEndOfExcerpt,
11351        window: &mut Window,
11352        cx: &mut Context<Self>,
11353    ) {
11354        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11355            cx.propagate();
11356            return;
11357        }
11358        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11359        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11360            s.move_with(|map, selection| {
11361                selection.collapse_to(
11362                    movement::end_of_excerpt(
11363                        map,
11364                        selection.head(),
11365                        workspace::searchable::Direction::Next,
11366                    ),
11367                    SelectionGoal::None,
11368                )
11369            });
11370        })
11371    }
11372
11373    pub fn move_to_end_of_previous_excerpt(
11374        &mut self,
11375        _: &MoveToEndOfPreviousExcerpt,
11376        window: &mut Window,
11377        cx: &mut Context<Self>,
11378    ) {
11379        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11380            cx.propagate();
11381            return;
11382        }
11383        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11384        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11385            s.move_with(|map, selection| {
11386                selection.collapse_to(
11387                    movement::end_of_excerpt(
11388                        map,
11389                        selection.head(),
11390                        workspace::searchable::Direction::Prev,
11391                    ),
11392                    SelectionGoal::None,
11393                )
11394            });
11395        })
11396    }
11397
11398    pub fn select_to_start_of_excerpt(
11399        &mut self,
11400        _: &SelectToStartOfExcerpt,
11401        window: &mut Window,
11402        cx: &mut Context<Self>,
11403    ) {
11404        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11405            cx.propagate();
11406            return;
11407        }
11408        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11409        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11410            s.move_heads_with(|map, head, _| {
11411                (
11412                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11413                    SelectionGoal::None,
11414                )
11415            });
11416        })
11417    }
11418
11419    pub fn select_to_start_of_next_excerpt(
11420        &mut self,
11421        _: &SelectToStartOfNextExcerpt,
11422        window: &mut Window,
11423        cx: &mut Context<Self>,
11424    ) {
11425        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11426            cx.propagate();
11427            return;
11428        }
11429        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11430        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11431            s.move_heads_with(|map, head, _| {
11432                (
11433                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11434                    SelectionGoal::None,
11435                )
11436            });
11437        })
11438    }
11439
11440    pub fn select_to_end_of_excerpt(
11441        &mut self,
11442        _: &SelectToEndOfExcerpt,
11443        window: &mut Window,
11444        cx: &mut Context<Self>,
11445    ) {
11446        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11447            cx.propagate();
11448            return;
11449        }
11450        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11451        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11452            s.move_heads_with(|map, head, _| {
11453                (
11454                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11455                    SelectionGoal::None,
11456                )
11457            });
11458        })
11459    }
11460
11461    pub fn select_to_end_of_previous_excerpt(
11462        &mut self,
11463        _: &SelectToEndOfPreviousExcerpt,
11464        window: &mut Window,
11465        cx: &mut Context<Self>,
11466    ) {
11467        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11468            cx.propagate();
11469            return;
11470        }
11471        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11472        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11473            s.move_heads_with(|map, head, _| {
11474                (
11475                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11476                    SelectionGoal::None,
11477                )
11478            });
11479        })
11480    }
11481
11482    pub fn move_to_beginning(
11483        &mut self,
11484        _: &MoveToBeginning,
11485        window: &mut Window,
11486        cx: &mut Context<Self>,
11487    ) {
11488        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11489            cx.propagate();
11490            return;
11491        }
11492        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11493        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11494            s.select_ranges(vec![0..0]);
11495        });
11496    }
11497
11498    pub fn select_to_beginning(
11499        &mut self,
11500        _: &SelectToBeginning,
11501        window: &mut Window,
11502        cx: &mut Context<Self>,
11503    ) {
11504        let mut selection = self.selections.last::<Point>(cx);
11505        selection.set_head(Point::zero(), SelectionGoal::None);
11506        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11507        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11508            s.select(vec![selection]);
11509        });
11510    }
11511
11512    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11513        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11514            cx.propagate();
11515            return;
11516        }
11517        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11518        let cursor = self.buffer.read(cx).read(cx).len();
11519        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11520            s.select_ranges(vec![cursor..cursor])
11521        });
11522    }
11523
11524    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11525        self.nav_history = nav_history;
11526    }
11527
11528    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11529        self.nav_history.as_ref()
11530    }
11531
11532    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11533        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11534    }
11535
11536    fn push_to_nav_history(
11537        &mut self,
11538        cursor_anchor: Anchor,
11539        new_position: Option<Point>,
11540        is_deactivate: bool,
11541        cx: &mut Context<Self>,
11542    ) {
11543        if let Some(nav_history) = self.nav_history.as_mut() {
11544            let buffer = self.buffer.read(cx).read(cx);
11545            let cursor_position = cursor_anchor.to_point(&buffer);
11546            let scroll_state = self.scroll_manager.anchor();
11547            let scroll_top_row = scroll_state.top_row(&buffer);
11548            drop(buffer);
11549
11550            if let Some(new_position) = new_position {
11551                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11552                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11553                    return;
11554                }
11555            }
11556
11557            nav_history.push(
11558                Some(NavigationData {
11559                    cursor_anchor,
11560                    cursor_position,
11561                    scroll_anchor: scroll_state,
11562                    scroll_top_row,
11563                }),
11564                cx,
11565            );
11566            cx.emit(EditorEvent::PushedToNavHistory {
11567                anchor: cursor_anchor,
11568                is_deactivate,
11569            })
11570        }
11571    }
11572
11573    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11574        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11575        let buffer = self.buffer.read(cx).snapshot(cx);
11576        let mut selection = self.selections.first::<usize>(cx);
11577        selection.set_head(buffer.len(), SelectionGoal::None);
11578        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11579            s.select(vec![selection]);
11580        });
11581    }
11582
11583    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11584        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11585        let end = self.buffer.read(cx).read(cx).len();
11586        self.change_selections(None, window, cx, |s| {
11587            s.select_ranges(vec![0..end]);
11588        });
11589    }
11590
11591    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11592        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11593        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11594        let mut selections = self.selections.all::<Point>(cx);
11595        let max_point = display_map.buffer_snapshot.max_point();
11596        for selection in &mut selections {
11597            let rows = selection.spanned_rows(true, &display_map);
11598            selection.start = Point::new(rows.start.0, 0);
11599            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11600            selection.reversed = false;
11601        }
11602        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11603            s.select(selections);
11604        });
11605    }
11606
11607    pub fn split_selection_into_lines(
11608        &mut self,
11609        _: &SplitSelectionIntoLines,
11610        window: &mut Window,
11611        cx: &mut Context<Self>,
11612    ) {
11613        let selections = self
11614            .selections
11615            .all::<Point>(cx)
11616            .into_iter()
11617            .map(|selection| selection.start..selection.end)
11618            .collect::<Vec<_>>();
11619        self.unfold_ranges(&selections, true, true, cx);
11620
11621        let mut new_selection_ranges = Vec::new();
11622        {
11623            let buffer = self.buffer.read(cx).read(cx);
11624            for selection in selections {
11625                for row in selection.start.row..selection.end.row {
11626                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11627                    new_selection_ranges.push(cursor..cursor);
11628                }
11629
11630                let is_multiline_selection = selection.start.row != selection.end.row;
11631                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11632                // so this action feels more ergonomic when paired with other selection operations
11633                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11634                if !should_skip_last {
11635                    new_selection_ranges.push(selection.end..selection.end);
11636                }
11637            }
11638        }
11639        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11640            s.select_ranges(new_selection_ranges);
11641        });
11642    }
11643
11644    pub fn add_selection_above(
11645        &mut self,
11646        _: &AddSelectionAbove,
11647        window: &mut Window,
11648        cx: &mut Context<Self>,
11649    ) {
11650        self.add_selection(true, window, cx);
11651    }
11652
11653    pub fn add_selection_below(
11654        &mut self,
11655        _: &AddSelectionBelow,
11656        window: &mut Window,
11657        cx: &mut Context<Self>,
11658    ) {
11659        self.add_selection(false, window, cx);
11660    }
11661
11662    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11663        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11664
11665        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11666        let mut selections = self.selections.all::<Point>(cx);
11667        let text_layout_details = self.text_layout_details(window);
11668        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11669            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11670            let range = oldest_selection.display_range(&display_map).sorted();
11671
11672            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11673            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11674            let positions = start_x.min(end_x)..start_x.max(end_x);
11675
11676            selections.clear();
11677            let mut stack = Vec::new();
11678            for row in range.start.row().0..=range.end.row().0 {
11679                if let Some(selection) = self.selections.build_columnar_selection(
11680                    &display_map,
11681                    DisplayRow(row),
11682                    &positions,
11683                    oldest_selection.reversed,
11684                    &text_layout_details,
11685                ) {
11686                    stack.push(selection.id);
11687                    selections.push(selection);
11688                }
11689            }
11690
11691            if above {
11692                stack.reverse();
11693            }
11694
11695            AddSelectionsState { above, stack }
11696        });
11697
11698        let last_added_selection = *state.stack.last().unwrap();
11699        let mut new_selections = Vec::new();
11700        if above == state.above {
11701            let end_row = if above {
11702                DisplayRow(0)
11703            } else {
11704                display_map.max_point().row()
11705            };
11706
11707            'outer: for selection in selections {
11708                if selection.id == last_added_selection {
11709                    let range = selection.display_range(&display_map).sorted();
11710                    debug_assert_eq!(range.start.row(), range.end.row());
11711                    let mut row = range.start.row();
11712                    let positions =
11713                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11714                            px(start)..px(end)
11715                        } else {
11716                            let start_x =
11717                                display_map.x_for_display_point(range.start, &text_layout_details);
11718                            let end_x =
11719                                display_map.x_for_display_point(range.end, &text_layout_details);
11720                            start_x.min(end_x)..start_x.max(end_x)
11721                        };
11722
11723                    while row != end_row {
11724                        if above {
11725                            row.0 -= 1;
11726                        } else {
11727                            row.0 += 1;
11728                        }
11729
11730                        if let Some(new_selection) = self.selections.build_columnar_selection(
11731                            &display_map,
11732                            row,
11733                            &positions,
11734                            selection.reversed,
11735                            &text_layout_details,
11736                        ) {
11737                            state.stack.push(new_selection.id);
11738                            if above {
11739                                new_selections.push(new_selection);
11740                                new_selections.push(selection);
11741                            } else {
11742                                new_selections.push(selection);
11743                                new_selections.push(new_selection);
11744                            }
11745
11746                            continue 'outer;
11747                        }
11748                    }
11749                }
11750
11751                new_selections.push(selection);
11752            }
11753        } else {
11754            new_selections = selections;
11755            new_selections.retain(|s| s.id != last_added_selection);
11756            state.stack.pop();
11757        }
11758
11759        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11760            s.select(new_selections);
11761        });
11762        if state.stack.len() > 1 {
11763            self.add_selections_state = Some(state);
11764        }
11765    }
11766
11767    pub fn select_next_match_internal(
11768        &mut self,
11769        display_map: &DisplaySnapshot,
11770        replace_newest: bool,
11771        autoscroll: Option<Autoscroll>,
11772        window: &mut Window,
11773        cx: &mut Context<Self>,
11774    ) -> Result<()> {
11775        fn select_next_match_ranges(
11776            this: &mut Editor,
11777            range: Range<usize>,
11778            replace_newest: bool,
11779            auto_scroll: Option<Autoscroll>,
11780            window: &mut Window,
11781            cx: &mut Context<Editor>,
11782        ) {
11783            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11784            this.change_selections(auto_scroll, window, cx, |s| {
11785                if replace_newest {
11786                    s.delete(s.newest_anchor().id);
11787                }
11788                s.insert_range(range.clone());
11789            });
11790        }
11791
11792        let buffer = &display_map.buffer_snapshot;
11793        let mut selections = self.selections.all::<usize>(cx);
11794        if let Some(mut select_next_state) = self.select_next_state.take() {
11795            let query = &select_next_state.query;
11796            if !select_next_state.done {
11797                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11798                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11799                let mut next_selected_range = None;
11800
11801                let bytes_after_last_selection =
11802                    buffer.bytes_in_range(last_selection.end..buffer.len());
11803                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11804                let query_matches = query
11805                    .stream_find_iter(bytes_after_last_selection)
11806                    .map(|result| (last_selection.end, result))
11807                    .chain(
11808                        query
11809                            .stream_find_iter(bytes_before_first_selection)
11810                            .map(|result| (0, result)),
11811                    );
11812
11813                for (start_offset, query_match) in query_matches {
11814                    let query_match = query_match.unwrap(); // can only fail due to I/O
11815                    let offset_range =
11816                        start_offset + query_match.start()..start_offset + query_match.end();
11817                    let display_range = offset_range.start.to_display_point(display_map)
11818                        ..offset_range.end.to_display_point(display_map);
11819
11820                    if !select_next_state.wordwise
11821                        || (!movement::is_inside_word(display_map, display_range.start)
11822                            && !movement::is_inside_word(display_map, display_range.end))
11823                    {
11824                        // TODO: This is n^2, because we might check all the selections
11825                        if !selections
11826                            .iter()
11827                            .any(|selection| selection.range().overlaps(&offset_range))
11828                        {
11829                            next_selected_range = Some(offset_range);
11830                            break;
11831                        }
11832                    }
11833                }
11834
11835                if let Some(next_selected_range) = next_selected_range {
11836                    select_next_match_ranges(
11837                        self,
11838                        next_selected_range,
11839                        replace_newest,
11840                        autoscroll,
11841                        window,
11842                        cx,
11843                    );
11844                } else {
11845                    select_next_state.done = true;
11846                }
11847            }
11848
11849            self.select_next_state = Some(select_next_state);
11850        } else {
11851            let mut only_carets = true;
11852            let mut same_text_selected = true;
11853            let mut selected_text = None;
11854
11855            let mut selections_iter = selections.iter().peekable();
11856            while let Some(selection) = selections_iter.next() {
11857                if selection.start != selection.end {
11858                    only_carets = false;
11859                }
11860
11861                if same_text_selected {
11862                    if selected_text.is_none() {
11863                        selected_text =
11864                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11865                    }
11866
11867                    if let Some(next_selection) = selections_iter.peek() {
11868                        if next_selection.range().len() == selection.range().len() {
11869                            let next_selected_text = buffer
11870                                .text_for_range(next_selection.range())
11871                                .collect::<String>();
11872                            if Some(next_selected_text) != selected_text {
11873                                same_text_selected = false;
11874                                selected_text = None;
11875                            }
11876                        } else {
11877                            same_text_selected = false;
11878                            selected_text = None;
11879                        }
11880                    }
11881                }
11882            }
11883
11884            if only_carets {
11885                for selection in &mut selections {
11886                    let word_range = movement::surrounding_word(
11887                        display_map,
11888                        selection.start.to_display_point(display_map),
11889                    );
11890                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11891                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11892                    selection.goal = SelectionGoal::None;
11893                    selection.reversed = false;
11894                    select_next_match_ranges(
11895                        self,
11896                        selection.start..selection.end,
11897                        replace_newest,
11898                        autoscroll,
11899                        window,
11900                        cx,
11901                    );
11902                }
11903
11904                if selections.len() == 1 {
11905                    let selection = selections
11906                        .last()
11907                        .expect("ensured that there's only one selection");
11908                    let query = buffer
11909                        .text_for_range(selection.start..selection.end)
11910                        .collect::<String>();
11911                    let is_empty = query.is_empty();
11912                    let select_state = SelectNextState {
11913                        query: AhoCorasick::new(&[query])?,
11914                        wordwise: true,
11915                        done: is_empty,
11916                    };
11917                    self.select_next_state = Some(select_state);
11918                } else {
11919                    self.select_next_state = None;
11920                }
11921            } else if let Some(selected_text) = selected_text {
11922                self.select_next_state = Some(SelectNextState {
11923                    query: AhoCorasick::new(&[selected_text])?,
11924                    wordwise: false,
11925                    done: false,
11926                });
11927                self.select_next_match_internal(
11928                    display_map,
11929                    replace_newest,
11930                    autoscroll,
11931                    window,
11932                    cx,
11933                )?;
11934            }
11935        }
11936        Ok(())
11937    }
11938
11939    pub fn select_all_matches(
11940        &mut self,
11941        _action: &SelectAllMatches,
11942        window: &mut Window,
11943        cx: &mut Context<Self>,
11944    ) -> Result<()> {
11945        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11946
11947        self.push_to_selection_history();
11948        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11949
11950        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11951        let Some(select_next_state) = self.select_next_state.as_mut() else {
11952            return Ok(());
11953        };
11954        if select_next_state.done {
11955            return Ok(());
11956        }
11957
11958        let mut new_selections = Vec::new();
11959
11960        let reversed = self.selections.oldest::<usize>(cx).reversed;
11961        let buffer = &display_map.buffer_snapshot;
11962        let query_matches = select_next_state
11963            .query
11964            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11965
11966        for query_match in query_matches.into_iter() {
11967            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11968            let offset_range = if reversed {
11969                query_match.end()..query_match.start()
11970            } else {
11971                query_match.start()..query_match.end()
11972            };
11973            let display_range = offset_range.start.to_display_point(&display_map)
11974                ..offset_range.end.to_display_point(&display_map);
11975
11976            if !select_next_state.wordwise
11977                || (!movement::is_inside_word(&display_map, display_range.start)
11978                    && !movement::is_inside_word(&display_map, display_range.end))
11979            {
11980                new_selections.push(offset_range.start..offset_range.end);
11981            }
11982        }
11983
11984        select_next_state.done = true;
11985        self.unfold_ranges(&new_selections.clone(), false, false, cx);
11986        self.change_selections(None, window, cx, |selections| {
11987            selections.select_ranges(new_selections)
11988        });
11989
11990        Ok(())
11991    }
11992
11993    pub fn select_next(
11994        &mut self,
11995        action: &SelectNext,
11996        window: &mut Window,
11997        cx: &mut Context<Self>,
11998    ) -> Result<()> {
11999        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12000        self.push_to_selection_history();
12001        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12002        self.select_next_match_internal(
12003            &display_map,
12004            action.replace_newest,
12005            Some(Autoscroll::newest()),
12006            window,
12007            cx,
12008        )?;
12009        Ok(())
12010    }
12011
12012    pub fn select_previous(
12013        &mut self,
12014        action: &SelectPrevious,
12015        window: &mut Window,
12016        cx: &mut Context<Self>,
12017    ) -> Result<()> {
12018        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12019        self.push_to_selection_history();
12020        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12021        let buffer = &display_map.buffer_snapshot;
12022        let mut selections = self.selections.all::<usize>(cx);
12023        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12024            let query = &select_prev_state.query;
12025            if !select_prev_state.done {
12026                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12027                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12028                let mut next_selected_range = None;
12029                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12030                let bytes_before_last_selection =
12031                    buffer.reversed_bytes_in_range(0..last_selection.start);
12032                let bytes_after_first_selection =
12033                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12034                let query_matches = query
12035                    .stream_find_iter(bytes_before_last_selection)
12036                    .map(|result| (last_selection.start, result))
12037                    .chain(
12038                        query
12039                            .stream_find_iter(bytes_after_first_selection)
12040                            .map(|result| (buffer.len(), result)),
12041                    );
12042                for (end_offset, query_match) in query_matches {
12043                    let query_match = query_match.unwrap(); // can only fail due to I/O
12044                    let offset_range =
12045                        end_offset - query_match.end()..end_offset - query_match.start();
12046                    let display_range = offset_range.start.to_display_point(&display_map)
12047                        ..offset_range.end.to_display_point(&display_map);
12048
12049                    if !select_prev_state.wordwise
12050                        || (!movement::is_inside_word(&display_map, display_range.start)
12051                            && !movement::is_inside_word(&display_map, display_range.end))
12052                    {
12053                        next_selected_range = Some(offset_range);
12054                        break;
12055                    }
12056                }
12057
12058                if let Some(next_selected_range) = next_selected_range {
12059                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12060                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12061                        if action.replace_newest {
12062                            s.delete(s.newest_anchor().id);
12063                        }
12064                        s.insert_range(next_selected_range);
12065                    });
12066                } else {
12067                    select_prev_state.done = true;
12068                }
12069            }
12070
12071            self.select_prev_state = Some(select_prev_state);
12072        } else {
12073            let mut only_carets = true;
12074            let mut same_text_selected = true;
12075            let mut selected_text = None;
12076
12077            let mut selections_iter = selections.iter().peekable();
12078            while let Some(selection) = selections_iter.next() {
12079                if selection.start != selection.end {
12080                    only_carets = false;
12081                }
12082
12083                if same_text_selected {
12084                    if selected_text.is_none() {
12085                        selected_text =
12086                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12087                    }
12088
12089                    if let Some(next_selection) = selections_iter.peek() {
12090                        if next_selection.range().len() == selection.range().len() {
12091                            let next_selected_text = buffer
12092                                .text_for_range(next_selection.range())
12093                                .collect::<String>();
12094                            if Some(next_selected_text) != selected_text {
12095                                same_text_selected = false;
12096                                selected_text = None;
12097                            }
12098                        } else {
12099                            same_text_selected = false;
12100                            selected_text = None;
12101                        }
12102                    }
12103                }
12104            }
12105
12106            if only_carets {
12107                for selection in &mut selections {
12108                    let word_range = movement::surrounding_word(
12109                        &display_map,
12110                        selection.start.to_display_point(&display_map),
12111                    );
12112                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12113                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12114                    selection.goal = SelectionGoal::None;
12115                    selection.reversed = false;
12116                }
12117                if selections.len() == 1 {
12118                    let selection = selections
12119                        .last()
12120                        .expect("ensured that there's only one selection");
12121                    let query = buffer
12122                        .text_for_range(selection.start..selection.end)
12123                        .collect::<String>();
12124                    let is_empty = query.is_empty();
12125                    let select_state = SelectNextState {
12126                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12127                        wordwise: true,
12128                        done: is_empty,
12129                    };
12130                    self.select_prev_state = Some(select_state);
12131                } else {
12132                    self.select_prev_state = None;
12133                }
12134
12135                self.unfold_ranges(
12136                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12137                    false,
12138                    true,
12139                    cx,
12140                );
12141                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12142                    s.select(selections);
12143                });
12144            } else if let Some(selected_text) = selected_text {
12145                self.select_prev_state = Some(SelectNextState {
12146                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12147                    wordwise: false,
12148                    done: false,
12149                });
12150                self.select_previous(action, window, cx)?;
12151            }
12152        }
12153        Ok(())
12154    }
12155
12156    pub fn find_next_match(
12157        &mut self,
12158        _: &FindNextMatch,
12159        window: &mut Window,
12160        cx: &mut Context<Self>,
12161    ) -> Result<()> {
12162        let selections = self.selections.disjoint_anchors();
12163        match selections.first() {
12164            Some(first) if selections.len() >= 2 => {
12165                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12166                    s.select_ranges([first.range()]);
12167                });
12168            }
12169            _ => self.select_next(
12170                &SelectNext {
12171                    replace_newest: true,
12172                },
12173                window,
12174                cx,
12175            )?,
12176        }
12177        Ok(())
12178    }
12179
12180    pub fn find_previous_match(
12181        &mut self,
12182        _: &FindPreviousMatch,
12183        window: &mut Window,
12184        cx: &mut Context<Self>,
12185    ) -> Result<()> {
12186        let selections = self.selections.disjoint_anchors();
12187        match selections.last() {
12188            Some(last) if selections.len() >= 2 => {
12189                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12190                    s.select_ranges([last.range()]);
12191                });
12192            }
12193            _ => self.select_previous(
12194                &SelectPrevious {
12195                    replace_newest: true,
12196                },
12197                window,
12198                cx,
12199            )?,
12200        }
12201        Ok(())
12202    }
12203
12204    pub fn toggle_comments(
12205        &mut self,
12206        action: &ToggleComments,
12207        window: &mut Window,
12208        cx: &mut Context<Self>,
12209    ) {
12210        if self.read_only(cx) {
12211            return;
12212        }
12213        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12214        let text_layout_details = &self.text_layout_details(window);
12215        self.transact(window, cx, |this, window, cx| {
12216            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12217            let mut edits = Vec::new();
12218            let mut selection_edit_ranges = Vec::new();
12219            let mut last_toggled_row = None;
12220            let snapshot = this.buffer.read(cx).read(cx);
12221            let empty_str: Arc<str> = Arc::default();
12222            let mut suffixes_inserted = Vec::new();
12223            let ignore_indent = action.ignore_indent;
12224
12225            fn comment_prefix_range(
12226                snapshot: &MultiBufferSnapshot,
12227                row: MultiBufferRow,
12228                comment_prefix: &str,
12229                comment_prefix_whitespace: &str,
12230                ignore_indent: bool,
12231            ) -> Range<Point> {
12232                let indent_size = if ignore_indent {
12233                    0
12234                } else {
12235                    snapshot.indent_size_for_line(row).len
12236                };
12237
12238                let start = Point::new(row.0, indent_size);
12239
12240                let mut line_bytes = snapshot
12241                    .bytes_in_range(start..snapshot.max_point())
12242                    .flatten()
12243                    .copied();
12244
12245                // If this line currently begins with the line comment prefix, then record
12246                // the range containing the prefix.
12247                if line_bytes
12248                    .by_ref()
12249                    .take(comment_prefix.len())
12250                    .eq(comment_prefix.bytes())
12251                {
12252                    // Include any whitespace that matches the comment prefix.
12253                    let matching_whitespace_len = line_bytes
12254                        .zip(comment_prefix_whitespace.bytes())
12255                        .take_while(|(a, b)| a == b)
12256                        .count() as u32;
12257                    let end = Point::new(
12258                        start.row,
12259                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12260                    );
12261                    start..end
12262                } else {
12263                    start..start
12264                }
12265            }
12266
12267            fn comment_suffix_range(
12268                snapshot: &MultiBufferSnapshot,
12269                row: MultiBufferRow,
12270                comment_suffix: &str,
12271                comment_suffix_has_leading_space: bool,
12272            ) -> Range<Point> {
12273                let end = Point::new(row.0, snapshot.line_len(row));
12274                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12275
12276                let mut line_end_bytes = snapshot
12277                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12278                    .flatten()
12279                    .copied();
12280
12281                let leading_space_len = if suffix_start_column > 0
12282                    && line_end_bytes.next() == Some(b' ')
12283                    && comment_suffix_has_leading_space
12284                {
12285                    1
12286                } else {
12287                    0
12288                };
12289
12290                // If this line currently begins with the line comment prefix, then record
12291                // the range containing the prefix.
12292                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12293                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12294                    start..end
12295                } else {
12296                    end..end
12297                }
12298            }
12299
12300            // TODO: Handle selections that cross excerpts
12301            for selection in &mut selections {
12302                let start_column = snapshot
12303                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12304                    .len;
12305                let language = if let Some(language) =
12306                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12307                {
12308                    language
12309                } else {
12310                    continue;
12311                };
12312
12313                selection_edit_ranges.clear();
12314
12315                // If multiple selections contain a given row, avoid processing that
12316                // row more than once.
12317                let mut start_row = MultiBufferRow(selection.start.row);
12318                if last_toggled_row == Some(start_row) {
12319                    start_row = start_row.next_row();
12320                }
12321                let end_row =
12322                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12323                        MultiBufferRow(selection.end.row - 1)
12324                    } else {
12325                        MultiBufferRow(selection.end.row)
12326                    };
12327                last_toggled_row = Some(end_row);
12328
12329                if start_row > end_row {
12330                    continue;
12331                }
12332
12333                // If the language has line comments, toggle those.
12334                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12335
12336                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12337                if ignore_indent {
12338                    full_comment_prefixes = full_comment_prefixes
12339                        .into_iter()
12340                        .map(|s| Arc::from(s.trim_end()))
12341                        .collect();
12342                }
12343
12344                if !full_comment_prefixes.is_empty() {
12345                    let first_prefix = full_comment_prefixes
12346                        .first()
12347                        .expect("prefixes is non-empty");
12348                    let prefix_trimmed_lengths = full_comment_prefixes
12349                        .iter()
12350                        .map(|p| p.trim_end_matches(' ').len())
12351                        .collect::<SmallVec<[usize; 4]>>();
12352
12353                    let mut all_selection_lines_are_comments = true;
12354
12355                    for row in start_row.0..=end_row.0 {
12356                        let row = MultiBufferRow(row);
12357                        if start_row < end_row && snapshot.is_line_blank(row) {
12358                            continue;
12359                        }
12360
12361                        let prefix_range = full_comment_prefixes
12362                            .iter()
12363                            .zip(prefix_trimmed_lengths.iter().copied())
12364                            .map(|(prefix, trimmed_prefix_len)| {
12365                                comment_prefix_range(
12366                                    snapshot.deref(),
12367                                    row,
12368                                    &prefix[..trimmed_prefix_len],
12369                                    &prefix[trimmed_prefix_len..],
12370                                    ignore_indent,
12371                                )
12372                            })
12373                            .max_by_key(|range| range.end.column - range.start.column)
12374                            .expect("prefixes is non-empty");
12375
12376                        if prefix_range.is_empty() {
12377                            all_selection_lines_are_comments = false;
12378                        }
12379
12380                        selection_edit_ranges.push(prefix_range);
12381                    }
12382
12383                    if all_selection_lines_are_comments {
12384                        edits.extend(
12385                            selection_edit_ranges
12386                                .iter()
12387                                .cloned()
12388                                .map(|range| (range, empty_str.clone())),
12389                        );
12390                    } else {
12391                        let min_column = selection_edit_ranges
12392                            .iter()
12393                            .map(|range| range.start.column)
12394                            .min()
12395                            .unwrap_or(0);
12396                        edits.extend(selection_edit_ranges.iter().map(|range| {
12397                            let position = Point::new(range.start.row, min_column);
12398                            (position..position, first_prefix.clone())
12399                        }));
12400                    }
12401                } else if let Some((full_comment_prefix, comment_suffix)) =
12402                    language.block_comment_delimiters()
12403                {
12404                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12405                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12406                    let prefix_range = comment_prefix_range(
12407                        snapshot.deref(),
12408                        start_row,
12409                        comment_prefix,
12410                        comment_prefix_whitespace,
12411                        ignore_indent,
12412                    );
12413                    let suffix_range = comment_suffix_range(
12414                        snapshot.deref(),
12415                        end_row,
12416                        comment_suffix.trim_start_matches(' '),
12417                        comment_suffix.starts_with(' '),
12418                    );
12419
12420                    if prefix_range.is_empty() || suffix_range.is_empty() {
12421                        edits.push((
12422                            prefix_range.start..prefix_range.start,
12423                            full_comment_prefix.clone(),
12424                        ));
12425                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12426                        suffixes_inserted.push((end_row, comment_suffix.len()));
12427                    } else {
12428                        edits.push((prefix_range, empty_str.clone()));
12429                        edits.push((suffix_range, empty_str.clone()));
12430                    }
12431                } else {
12432                    continue;
12433                }
12434            }
12435
12436            drop(snapshot);
12437            this.buffer.update(cx, |buffer, cx| {
12438                buffer.edit(edits, None, cx);
12439            });
12440
12441            // Adjust selections so that they end before any comment suffixes that
12442            // were inserted.
12443            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12444            let mut selections = this.selections.all::<Point>(cx);
12445            let snapshot = this.buffer.read(cx).read(cx);
12446            for selection in &mut selections {
12447                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12448                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12449                        Ordering::Less => {
12450                            suffixes_inserted.next();
12451                            continue;
12452                        }
12453                        Ordering::Greater => break,
12454                        Ordering::Equal => {
12455                            if selection.end.column == snapshot.line_len(row) {
12456                                if selection.is_empty() {
12457                                    selection.start.column -= suffix_len as u32;
12458                                }
12459                                selection.end.column -= suffix_len as u32;
12460                            }
12461                            break;
12462                        }
12463                    }
12464                }
12465            }
12466
12467            drop(snapshot);
12468            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12469                s.select(selections)
12470            });
12471
12472            let selections = this.selections.all::<Point>(cx);
12473            let selections_on_single_row = selections.windows(2).all(|selections| {
12474                selections[0].start.row == selections[1].start.row
12475                    && selections[0].end.row == selections[1].end.row
12476                    && selections[0].start.row == selections[0].end.row
12477            });
12478            let selections_selecting = selections
12479                .iter()
12480                .any(|selection| selection.start != selection.end);
12481            let advance_downwards = action.advance_downwards
12482                && selections_on_single_row
12483                && !selections_selecting
12484                && !matches!(this.mode, EditorMode::SingleLine { .. });
12485
12486            if advance_downwards {
12487                let snapshot = this.buffer.read(cx).snapshot(cx);
12488
12489                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12490                    s.move_cursors_with(|display_snapshot, display_point, _| {
12491                        let mut point = display_point.to_point(display_snapshot);
12492                        point.row += 1;
12493                        point = snapshot.clip_point(point, Bias::Left);
12494                        let display_point = point.to_display_point(display_snapshot);
12495                        let goal = SelectionGoal::HorizontalPosition(
12496                            display_snapshot
12497                                .x_for_display_point(display_point, text_layout_details)
12498                                .into(),
12499                        );
12500                        (display_point, goal)
12501                    })
12502                });
12503            }
12504        });
12505    }
12506
12507    pub fn select_enclosing_symbol(
12508        &mut self,
12509        _: &SelectEnclosingSymbol,
12510        window: &mut Window,
12511        cx: &mut Context<Self>,
12512    ) {
12513        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12514
12515        let buffer = self.buffer.read(cx).snapshot(cx);
12516        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12517
12518        fn update_selection(
12519            selection: &Selection<usize>,
12520            buffer_snap: &MultiBufferSnapshot,
12521        ) -> Option<Selection<usize>> {
12522            let cursor = selection.head();
12523            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12524            for symbol in symbols.iter().rev() {
12525                let start = symbol.range.start.to_offset(buffer_snap);
12526                let end = symbol.range.end.to_offset(buffer_snap);
12527                let new_range = start..end;
12528                if start < selection.start || end > selection.end {
12529                    return Some(Selection {
12530                        id: selection.id,
12531                        start: new_range.start,
12532                        end: new_range.end,
12533                        goal: SelectionGoal::None,
12534                        reversed: selection.reversed,
12535                    });
12536                }
12537            }
12538            None
12539        }
12540
12541        let mut selected_larger_symbol = false;
12542        let new_selections = old_selections
12543            .iter()
12544            .map(|selection| match update_selection(selection, &buffer) {
12545                Some(new_selection) => {
12546                    if new_selection.range() != selection.range() {
12547                        selected_larger_symbol = true;
12548                    }
12549                    new_selection
12550                }
12551                None => selection.clone(),
12552            })
12553            .collect::<Vec<_>>();
12554
12555        if selected_larger_symbol {
12556            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12557                s.select(new_selections);
12558            });
12559        }
12560    }
12561
12562    pub fn select_larger_syntax_node(
12563        &mut self,
12564        _: &SelectLargerSyntaxNode,
12565        window: &mut Window,
12566        cx: &mut Context<Self>,
12567    ) {
12568        let Some(visible_row_count) = self.visible_row_count() else {
12569            return;
12570        };
12571        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12572        if old_selections.is_empty() {
12573            return;
12574        }
12575
12576        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12577
12578        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12579        let buffer = self.buffer.read(cx).snapshot(cx);
12580
12581        let mut selected_larger_node = false;
12582        let mut new_selections = old_selections
12583            .iter()
12584            .map(|selection| {
12585                let old_range = selection.start..selection.end;
12586
12587                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12588                    // manually select word at selection
12589                    if ["string_content", "inline"].contains(&node.kind()) {
12590                        let word_range = {
12591                            let display_point = buffer
12592                                .offset_to_point(old_range.start)
12593                                .to_display_point(&display_map);
12594                            let Range { start, end } =
12595                                movement::surrounding_word(&display_map, display_point);
12596                            start.to_point(&display_map).to_offset(&buffer)
12597                                ..end.to_point(&display_map).to_offset(&buffer)
12598                        };
12599                        // ignore if word is already selected
12600                        if !word_range.is_empty() && old_range != word_range {
12601                            let last_word_range = {
12602                                let display_point = buffer
12603                                    .offset_to_point(old_range.end)
12604                                    .to_display_point(&display_map);
12605                                let Range { start, end } =
12606                                    movement::surrounding_word(&display_map, display_point);
12607                                start.to_point(&display_map).to_offset(&buffer)
12608                                    ..end.to_point(&display_map).to_offset(&buffer)
12609                            };
12610                            // only select word if start and end point belongs to same word
12611                            if word_range == last_word_range {
12612                                selected_larger_node = true;
12613                                return Selection {
12614                                    id: selection.id,
12615                                    start: word_range.start,
12616                                    end: word_range.end,
12617                                    goal: SelectionGoal::None,
12618                                    reversed: selection.reversed,
12619                                };
12620                            }
12621                        }
12622                    }
12623                }
12624
12625                let mut new_range = old_range.clone();
12626                let mut new_node = None;
12627                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12628                {
12629                    new_node = Some(node);
12630                    new_range = match containing_range {
12631                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12632                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12633                    };
12634                    if !display_map.intersects_fold(new_range.start)
12635                        && !display_map.intersects_fold(new_range.end)
12636                    {
12637                        break;
12638                    }
12639                }
12640
12641                if let Some(node) = new_node {
12642                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12643                    // nodes. Parent and grandparent are also logged because this operation will not
12644                    // visit nodes that have the same range as their parent.
12645                    log::info!("Node: {node:?}");
12646                    let parent = node.parent();
12647                    log::info!("Parent: {parent:?}");
12648                    let grandparent = parent.and_then(|x| x.parent());
12649                    log::info!("Grandparent: {grandparent:?}");
12650                }
12651
12652                selected_larger_node |= new_range != old_range;
12653                Selection {
12654                    id: selection.id,
12655                    start: new_range.start,
12656                    end: new_range.end,
12657                    goal: SelectionGoal::None,
12658                    reversed: selection.reversed,
12659                }
12660            })
12661            .collect::<Vec<_>>();
12662
12663        if !selected_larger_node {
12664            return; // don't put this call in the history
12665        }
12666
12667        // scroll based on transformation done to the last selection created by the user
12668        let (last_old, last_new) = old_selections
12669            .last()
12670            .zip(new_selections.last().cloned())
12671            .expect("old_selections isn't empty");
12672
12673        // revert selection
12674        let is_selection_reversed = {
12675            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12676            new_selections.last_mut().expect("checked above").reversed =
12677                should_newest_selection_be_reversed;
12678            should_newest_selection_be_reversed
12679        };
12680
12681        if selected_larger_node {
12682            self.select_syntax_node_history.disable_clearing = true;
12683            self.change_selections(None, window, cx, |s| {
12684                s.select(new_selections.clone());
12685            });
12686            self.select_syntax_node_history.disable_clearing = false;
12687        }
12688
12689        let start_row = last_new.start.to_display_point(&display_map).row().0;
12690        let end_row = last_new.end.to_display_point(&display_map).row().0;
12691        let selection_height = end_row - start_row + 1;
12692        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12693
12694        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12695        let scroll_behavior = if fits_on_the_screen {
12696            self.request_autoscroll(Autoscroll::fit(), cx);
12697            SelectSyntaxNodeScrollBehavior::FitSelection
12698        } else if is_selection_reversed {
12699            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12700            SelectSyntaxNodeScrollBehavior::CursorTop
12701        } else {
12702            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12703            SelectSyntaxNodeScrollBehavior::CursorBottom
12704        };
12705
12706        self.select_syntax_node_history.push((
12707            old_selections,
12708            scroll_behavior,
12709            is_selection_reversed,
12710        ));
12711    }
12712
12713    pub fn select_smaller_syntax_node(
12714        &mut self,
12715        _: &SelectSmallerSyntaxNode,
12716        window: &mut Window,
12717        cx: &mut Context<Self>,
12718    ) {
12719        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12720
12721        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12722            self.select_syntax_node_history.pop()
12723        {
12724            if let Some(selection) = selections.last_mut() {
12725                selection.reversed = is_selection_reversed;
12726            }
12727
12728            self.select_syntax_node_history.disable_clearing = true;
12729            self.change_selections(None, window, cx, |s| {
12730                s.select(selections.to_vec());
12731            });
12732            self.select_syntax_node_history.disable_clearing = false;
12733
12734            match scroll_behavior {
12735                SelectSyntaxNodeScrollBehavior::CursorTop => {
12736                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12737                }
12738                SelectSyntaxNodeScrollBehavior::FitSelection => {
12739                    self.request_autoscroll(Autoscroll::fit(), cx);
12740                }
12741                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12742                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12743                }
12744            }
12745        }
12746    }
12747
12748    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12749        if !EditorSettings::get_global(cx).gutter.runnables {
12750            self.clear_tasks();
12751            return Task::ready(());
12752        }
12753        let project = self.project.as_ref().map(Entity::downgrade);
12754        let task_sources = self.lsp_task_sources(cx);
12755        cx.spawn_in(window, async move |editor, cx| {
12756            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12757            let Some(project) = project.and_then(|p| p.upgrade()) else {
12758                return;
12759            };
12760            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12761                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12762            }) else {
12763                return;
12764            };
12765
12766            let hide_runnables = project
12767                .update(cx, |project, cx| {
12768                    // Do not display any test indicators in non-dev server remote projects.
12769                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12770                })
12771                .unwrap_or(true);
12772            if hide_runnables {
12773                return;
12774            }
12775            let new_rows =
12776                cx.background_spawn({
12777                    let snapshot = display_snapshot.clone();
12778                    async move {
12779                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12780                    }
12781                })
12782                    .await;
12783            let Ok(lsp_tasks) =
12784                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12785            else {
12786                return;
12787            };
12788            let lsp_tasks = lsp_tasks.await;
12789
12790            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12791                lsp_tasks
12792                    .into_iter()
12793                    .flat_map(|(kind, tasks)| {
12794                        tasks.into_iter().filter_map(move |(location, task)| {
12795                            Some((kind.clone(), location?, task))
12796                        })
12797                    })
12798                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12799                        let buffer = location.target.buffer;
12800                        let buffer_snapshot = buffer.read(cx).snapshot();
12801                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12802                            |(excerpt_id, snapshot, _)| {
12803                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
12804                                    display_snapshot
12805                                        .buffer_snapshot
12806                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
12807                                } else {
12808                                    None
12809                                }
12810                            },
12811                        );
12812                        if let Some(offset) = offset {
12813                            let task_buffer_range =
12814                                location.target.range.to_point(&buffer_snapshot);
12815                            let context_buffer_range =
12816                                task_buffer_range.to_offset(&buffer_snapshot);
12817                            let context_range = BufferOffset(context_buffer_range.start)
12818                                ..BufferOffset(context_buffer_range.end);
12819
12820                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12821                                .or_insert_with(|| RunnableTasks {
12822                                    templates: Vec::new(),
12823                                    offset,
12824                                    column: task_buffer_range.start.column,
12825                                    extra_variables: HashMap::default(),
12826                                    context_range,
12827                                })
12828                                .templates
12829                                .push((kind, task.original_task().clone()));
12830                        }
12831
12832                        acc
12833                    })
12834            }) else {
12835                return;
12836            };
12837
12838            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12839            editor
12840                .update(cx, |editor, _| {
12841                    editor.clear_tasks();
12842                    for (key, mut value) in rows {
12843                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12844                            value.templates.extend(lsp_tasks.templates);
12845                        }
12846
12847                        editor.insert_tasks(key, value);
12848                    }
12849                    for (key, value) in lsp_tasks_by_rows {
12850                        editor.insert_tasks(key, value);
12851                    }
12852                })
12853                .ok();
12854        })
12855    }
12856    fn fetch_runnable_ranges(
12857        snapshot: &DisplaySnapshot,
12858        range: Range<Anchor>,
12859    ) -> Vec<language::RunnableRange> {
12860        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12861    }
12862
12863    fn runnable_rows(
12864        project: Entity<Project>,
12865        snapshot: DisplaySnapshot,
12866        runnable_ranges: Vec<RunnableRange>,
12867        mut cx: AsyncWindowContext,
12868    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12869        runnable_ranges
12870            .into_iter()
12871            .filter_map(|mut runnable| {
12872                let tasks = cx
12873                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12874                    .ok()?;
12875                if tasks.is_empty() {
12876                    return None;
12877                }
12878
12879                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12880
12881                let row = snapshot
12882                    .buffer_snapshot
12883                    .buffer_line_for_row(MultiBufferRow(point.row))?
12884                    .1
12885                    .start
12886                    .row;
12887
12888                let context_range =
12889                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12890                Some((
12891                    (runnable.buffer_id, row),
12892                    RunnableTasks {
12893                        templates: tasks,
12894                        offset: snapshot
12895                            .buffer_snapshot
12896                            .anchor_before(runnable.run_range.start),
12897                        context_range,
12898                        column: point.column,
12899                        extra_variables: runnable.extra_captures,
12900                    },
12901                ))
12902            })
12903            .collect()
12904    }
12905
12906    fn templates_with_tags(
12907        project: &Entity<Project>,
12908        runnable: &mut Runnable,
12909        cx: &mut App,
12910    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12911        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12912            let (worktree_id, file) = project
12913                .buffer_for_id(runnable.buffer, cx)
12914                .and_then(|buffer| buffer.read(cx).file())
12915                .map(|file| (file.worktree_id(cx), file.clone()))
12916                .unzip();
12917
12918            (
12919                project.task_store().read(cx).task_inventory().cloned(),
12920                worktree_id,
12921                file,
12922            )
12923        });
12924
12925        let mut templates_with_tags = mem::take(&mut runnable.tags)
12926            .into_iter()
12927            .flat_map(|RunnableTag(tag)| {
12928                inventory
12929                    .as_ref()
12930                    .into_iter()
12931                    .flat_map(|inventory| {
12932                        inventory.read(cx).list_tasks(
12933                            file.clone(),
12934                            Some(runnable.language.clone()),
12935                            worktree_id,
12936                            cx,
12937                        )
12938                    })
12939                    .filter(move |(_, template)| {
12940                        template.tags.iter().any(|source_tag| source_tag == &tag)
12941                    })
12942            })
12943            .sorted_by_key(|(kind, _)| kind.to_owned())
12944            .collect::<Vec<_>>();
12945        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12946            // Strongest source wins; if we have worktree tag binding, prefer that to
12947            // global and language bindings;
12948            // if we have a global binding, prefer that to language binding.
12949            let first_mismatch = templates_with_tags
12950                .iter()
12951                .position(|(tag_source, _)| tag_source != leading_tag_source);
12952            if let Some(index) = first_mismatch {
12953                templates_with_tags.truncate(index);
12954            }
12955        }
12956
12957        templates_with_tags
12958    }
12959
12960    pub fn move_to_enclosing_bracket(
12961        &mut self,
12962        _: &MoveToEnclosingBracket,
12963        window: &mut Window,
12964        cx: &mut Context<Self>,
12965    ) {
12966        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12967        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12968            s.move_offsets_with(|snapshot, selection| {
12969                let Some(enclosing_bracket_ranges) =
12970                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12971                else {
12972                    return;
12973                };
12974
12975                let mut best_length = usize::MAX;
12976                let mut best_inside = false;
12977                let mut best_in_bracket_range = false;
12978                let mut best_destination = None;
12979                for (open, close) in enclosing_bracket_ranges {
12980                    let close = close.to_inclusive();
12981                    let length = close.end() - open.start;
12982                    let inside = selection.start >= open.end && selection.end <= *close.start();
12983                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12984                        || close.contains(&selection.head());
12985
12986                    // If best is next to a bracket and current isn't, skip
12987                    if !in_bracket_range && best_in_bracket_range {
12988                        continue;
12989                    }
12990
12991                    // Prefer smaller lengths unless best is inside and current isn't
12992                    if length > best_length && (best_inside || !inside) {
12993                        continue;
12994                    }
12995
12996                    best_length = length;
12997                    best_inside = inside;
12998                    best_in_bracket_range = in_bracket_range;
12999                    best_destination = Some(
13000                        if close.contains(&selection.start) && close.contains(&selection.end) {
13001                            if inside { open.end } else { open.start }
13002                        } else if inside {
13003                            *close.start()
13004                        } else {
13005                            *close.end()
13006                        },
13007                    );
13008                }
13009
13010                if let Some(destination) = best_destination {
13011                    selection.collapse_to(destination, SelectionGoal::None);
13012                }
13013            })
13014        });
13015    }
13016
13017    pub fn undo_selection(
13018        &mut self,
13019        _: &UndoSelection,
13020        window: &mut Window,
13021        cx: &mut Context<Self>,
13022    ) {
13023        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13024        self.end_selection(window, cx);
13025        self.selection_history.mode = SelectionHistoryMode::Undoing;
13026        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13027            self.change_selections(None, window, cx, |s| {
13028                s.select_anchors(entry.selections.to_vec())
13029            });
13030            self.select_next_state = entry.select_next_state;
13031            self.select_prev_state = entry.select_prev_state;
13032            self.add_selections_state = entry.add_selections_state;
13033            self.request_autoscroll(Autoscroll::newest(), cx);
13034        }
13035        self.selection_history.mode = SelectionHistoryMode::Normal;
13036    }
13037
13038    pub fn redo_selection(
13039        &mut self,
13040        _: &RedoSelection,
13041        window: &mut Window,
13042        cx: &mut Context<Self>,
13043    ) {
13044        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13045        self.end_selection(window, cx);
13046        self.selection_history.mode = SelectionHistoryMode::Redoing;
13047        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13048            self.change_selections(None, window, cx, |s| {
13049                s.select_anchors(entry.selections.to_vec())
13050            });
13051            self.select_next_state = entry.select_next_state;
13052            self.select_prev_state = entry.select_prev_state;
13053            self.add_selections_state = entry.add_selections_state;
13054            self.request_autoscroll(Autoscroll::newest(), cx);
13055        }
13056        self.selection_history.mode = SelectionHistoryMode::Normal;
13057    }
13058
13059    pub fn expand_excerpts(
13060        &mut self,
13061        action: &ExpandExcerpts,
13062        _: &mut Window,
13063        cx: &mut Context<Self>,
13064    ) {
13065        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13066    }
13067
13068    pub fn expand_excerpts_down(
13069        &mut self,
13070        action: &ExpandExcerptsDown,
13071        _: &mut Window,
13072        cx: &mut Context<Self>,
13073    ) {
13074        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13075    }
13076
13077    pub fn expand_excerpts_up(
13078        &mut self,
13079        action: &ExpandExcerptsUp,
13080        _: &mut Window,
13081        cx: &mut Context<Self>,
13082    ) {
13083        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13084    }
13085
13086    pub fn expand_excerpts_for_direction(
13087        &mut self,
13088        lines: u32,
13089        direction: ExpandExcerptDirection,
13090
13091        cx: &mut Context<Self>,
13092    ) {
13093        let selections = self.selections.disjoint_anchors();
13094
13095        let lines = if lines == 0 {
13096            EditorSettings::get_global(cx).expand_excerpt_lines
13097        } else {
13098            lines
13099        };
13100
13101        self.buffer.update(cx, |buffer, cx| {
13102            let snapshot = buffer.snapshot(cx);
13103            let mut excerpt_ids = selections
13104                .iter()
13105                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13106                .collect::<Vec<_>>();
13107            excerpt_ids.sort();
13108            excerpt_ids.dedup();
13109            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13110        })
13111    }
13112
13113    pub fn expand_excerpt(
13114        &mut self,
13115        excerpt: ExcerptId,
13116        direction: ExpandExcerptDirection,
13117        window: &mut Window,
13118        cx: &mut Context<Self>,
13119    ) {
13120        let current_scroll_position = self.scroll_position(cx);
13121        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13122        let mut should_scroll_up = false;
13123
13124        if direction == ExpandExcerptDirection::Down {
13125            let multi_buffer = self.buffer.read(cx);
13126            let snapshot = multi_buffer.snapshot(cx);
13127            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13128                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13129                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13130                        let buffer_snapshot = buffer.read(cx).snapshot();
13131                        let excerpt_end_row =
13132                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13133                        let last_row = buffer_snapshot.max_point().row;
13134                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13135                        should_scroll_up = lines_below >= lines_to_expand;
13136                    }
13137                }
13138            }
13139        }
13140
13141        self.buffer.update(cx, |buffer, cx| {
13142            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13143        });
13144
13145        if should_scroll_up {
13146            let new_scroll_position =
13147                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13148            self.set_scroll_position(new_scroll_position, window, cx);
13149        }
13150    }
13151
13152    pub fn go_to_singleton_buffer_point(
13153        &mut self,
13154        point: Point,
13155        window: &mut Window,
13156        cx: &mut Context<Self>,
13157    ) {
13158        self.go_to_singleton_buffer_range(point..point, window, cx);
13159    }
13160
13161    pub fn go_to_singleton_buffer_range(
13162        &mut self,
13163        range: Range<Point>,
13164        window: &mut Window,
13165        cx: &mut Context<Self>,
13166    ) {
13167        let multibuffer = self.buffer().read(cx);
13168        let Some(buffer) = multibuffer.as_singleton() else {
13169            return;
13170        };
13171        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13172            return;
13173        };
13174        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13175            return;
13176        };
13177        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13178            s.select_anchor_ranges([start..end])
13179        });
13180    }
13181
13182    pub fn go_to_diagnostic(
13183        &mut self,
13184        _: &GoToDiagnostic,
13185        window: &mut Window,
13186        cx: &mut Context<Self>,
13187    ) {
13188        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13189        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13190    }
13191
13192    pub fn go_to_prev_diagnostic(
13193        &mut self,
13194        _: &GoToPreviousDiagnostic,
13195        window: &mut Window,
13196        cx: &mut Context<Self>,
13197    ) {
13198        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13199        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13200    }
13201
13202    pub fn go_to_diagnostic_impl(
13203        &mut self,
13204        direction: Direction,
13205        window: &mut Window,
13206        cx: &mut Context<Self>,
13207    ) {
13208        let buffer = self.buffer.read(cx).snapshot(cx);
13209        let selection = self.selections.newest::<usize>(cx);
13210
13211        let mut active_group_id = None;
13212        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13213            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13214                active_group_id = Some(active_group.group_id);
13215            }
13216        }
13217
13218        fn filtered(
13219            snapshot: EditorSnapshot,
13220            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13221        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13222            diagnostics
13223                .filter(|entry| entry.range.start != entry.range.end)
13224                .filter(|entry| !entry.diagnostic.is_unnecessary)
13225                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13226        }
13227
13228        let snapshot = self.snapshot(window, cx);
13229        let before = filtered(
13230            snapshot.clone(),
13231            buffer
13232                .diagnostics_in_range(0..selection.start)
13233                .filter(|entry| entry.range.start <= selection.start),
13234        );
13235        let after = filtered(
13236            snapshot,
13237            buffer
13238                .diagnostics_in_range(selection.start..buffer.len())
13239                .filter(|entry| entry.range.start >= selection.start),
13240        );
13241
13242        let mut found: Option<DiagnosticEntry<usize>> = None;
13243        if direction == Direction::Prev {
13244            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13245            {
13246                for diagnostic in prev_diagnostics.into_iter().rev() {
13247                    if diagnostic.range.start != selection.start
13248                        || active_group_id
13249                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13250                    {
13251                        found = Some(diagnostic);
13252                        break 'outer;
13253                    }
13254                }
13255            }
13256        } else {
13257            for diagnostic in after.chain(before) {
13258                if diagnostic.range.start != selection.start
13259                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13260                {
13261                    found = Some(diagnostic);
13262                    break;
13263                }
13264            }
13265        }
13266        let Some(next_diagnostic) = found else {
13267            return;
13268        };
13269
13270        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13271            return;
13272        };
13273        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13274            s.select_ranges(vec![
13275                next_diagnostic.range.start..next_diagnostic.range.start,
13276            ])
13277        });
13278        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13279        self.refresh_inline_completion(false, true, window, cx);
13280    }
13281
13282    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13283        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13284        let snapshot = self.snapshot(window, cx);
13285        let selection = self.selections.newest::<Point>(cx);
13286        self.go_to_hunk_before_or_after_position(
13287            &snapshot,
13288            selection.head(),
13289            Direction::Next,
13290            window,
13291            cx,
13292        );
13293    }
13294
13295    pub fn go_to_hunk_before_or_after_position(
13296        &mut self,
13297        snapshot: &EditorSnapshot,
13298        position: Point,
13299        direction: Direction,
13300        window: &mut Window,
13301        cx: &mut Context<Editor>,
13302    ) {
13303        let row = if direction == Direction::Next {
13304            self.hunk_after_position(snapshot, position)
13305                .map(|hunk| hunk.row_range.start)
13306        } else {
13307            self.hunk_before_position(snapshot, position)
13308        };
13309
13310        if let Some(row) = row {
13311            let destination = Point::new(row.0, 0);
13312            let autoscroll = Autoscroll::center();
13313
13314            self.unfold_ranges(&[destination..destination], false, false, cx);
13315            self.change_selections(Some(autoscroll), window, cx, |s| {
13316                s.select_ranges([destination..destination]);
13317            });
13318        }
13319    }
13320
13321    fn hunk_after_position(
13322        &mut self,
13323        snapshot: &EditorSnapshot,
13324        position: Point,
13325    ) -> Option<MultiBufferDiffHunk> {
13326        snapshot
13327            .buffer_snapshot
13328            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13329            .find(|hunk| hunk.row_range.start.0 > position.row)
13330            .or_else(|| {
13331                snapshot
13332                    .buffer_snapshot
13333                    .diff_hunks_in_range(Point::zero()..position)
13334                    .find(|hunk| hunk.row_range.end.0 < position.row)
13335            })
13336    }
13337
13338    fn go_to_prev_hunk(
13339        &mut self,
13340        _: &GoToPreviousHunk,
13341        window: &mut Window,
13342        cx: &mut Context<Self>,
13343    ) {
13344        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13345        let snapshot = self.snapshot(window, cx);
13346        let selection = self.selections.newest::<Point>(cx);
13347        self.go_to_hunk_before_or_after_position(
13348            &snapshot,
13349            selection.head(),
13350            Direction::Prev,
13351            window,
13352            cx,
13353        );
13354    }
13355
13356    fn hunk_before_position(
13357        &mut self,
13358        snapshot: &EditorSnapshot,
13359        position: Point,
13360    ) -> Option<MultiBufferRow> {
13361        snapshot
13362            .buffer_snapshot
13363            .diff_hunk_before(position)
13364            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13365    }
13366
13367    fn go_to_line<T: 'static>(
13368        &mut self,
13369        position: Anchor,
13370        highlight_color: Option<Hsla>,
13371        window: &mut Window,
13372        cx: &mut Context<Self>,
13373    ) {
13374        let snapshot = self.snapshot(window, cx).display_snapshot;
13375        let position = position.to_point(&snapshot.buffer_snapshot);
13376        let start = snapshot
13377            .buffer_snapshot
13378            .clip_point(Point::new(position.row, 0), Bias::Left);
13379        let end = start + Point::new(1, 0);
13380        let start = snapshot.buffer_snapshot.anchor_before(start);
13381        let end = snapshot.buffer_snapshot.anchor_before(end);
13382
13383        self.highlight_rows::<T>(
13384            start..end,
13385            highlight_color
13386                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13387            false,
13388            cx,
13389        );
13390        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13391    }
13392
13393    pub fn go_to_definition(
13394        &mut self,
13395        _: &GoToDefinition,
13396        window: &mut Window,
13397        cx: &mut Context<Self>,
13398    ) -> Task<Result<Navigated>> {
13399        let definition =
13400            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13401        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13402        cx.spawn_in(window, async move |editor, cx| {
13403            if definition.await? == Navigated::Yes {
13404                return Ok(Navigated::Yes);
13405            }
13406            match fallback_strategy {
13407                GoToDefinitionFallback::None => Ok(Navigated::No),
13408                GoToDefinitionFallback::FindAllReferences => {
13409                    match editor.update_in(cx, |editor, window, cx| {
13410                        editor.find_all_references(&FindAllReferences, window, cx)
13411                    })? {
13412                        Some(references) => references.await,
13413                        None => Ok(Navigated::No),
13414                    }
13415                }
13416            }
13417        })
13418    }
13419
13420    pub fn go_to_declaration(
13421        &mut self,
13422        _: &GoToDeclaration,
13423        window: &mut Window,
13424        cx: &mut Context<Self>,
13425    ) -> Task<Result<Navigated>> {
13426        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13427    }
13428
13429    pub fn go_to_declaration_split(
13430        &mut self,
13431        _: &GoToDeclaration,
13432        window: &mut Window,
13433        cx: &mut Context<Self>,
13434    ) -> Task<Result<Navigated>> {
13435        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13436    }
13437
13438    pub fn go_to_implementation(
13439        &mut self,
13440        _: &GoToImplementation,
13441        window: &mut Window,
13442        cx: &mut Context<Self>,
13443    ) -> Task<Result<Navigated>> {
13444        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13445    }
13446
13447    pub fn go_to_implementation_split(
13448        &mut self,
13449        _: &GoToImplementationSplit,
13450        window: &mut Window,
13451        cx: &mut Context<Self>,
13452    ) -> Task<Result<Navigated>> {
13453        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13454    }
13455
13456    pub fn go_to_type_definition(
13457        &mut self,
13458        _: &GoToTypeDefinition,
13459        window: &mut Window,
13460        cx: &mut Context<Self>,
13461    ) -> Task<Result<Navigated>> {
13462        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13463    }
13464
13465    pub fn go_to_definition_split(
13466        &mut self,
13467        _: &GoToDefinitionSplit,
13468        window: &mut Window,
13469        cx: &mut Context<Self>,
13470    ) -> Task<Result<Navigated>> {
13471        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13472    }
13473
13474    pub fn go_to_type_definition_split(
13475        &mut self,
13476        _: &GoToTypeDefinitionSplit,
13477        window: &mut Window,
13478        cx: &mut Context<Self>,
13479    ) -> Task<Result<Navigated>> {
13480        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13481    }
13482
13483    fn go_to_definition_of_kind(
13484        &mut self,
13485        kind: GotoDefinitionKind,
13486        split: bool,
13487        window: &mut Window,
13488        cx: &mut Context<Self>,
13489    ) -> Task<Result<Navigated>> {
13490        let Some(provider) = self.semantics_provider.clone() else {
13491            return Task::ready(Ok(Navigated::No));
13492        };
13493        let head = self.selections.newest::<usize>(cx).head();
13494        let buffer = self.buffer.read(cx);
13495        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13496            text_anchor
13497        } else {
13498            return Task::ready(Ok(Navigated::No));
13499        };
13500
13501        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13502            return Task::ready(Ok(Navigated::No));
13503        };
13504
13505        cx.spawn_in(window, async move |editor, cx| {
13506            let definitions = definitions.await?;
13507            let navigated = editor
13508                .update_in(cx, |editor, window, cx| {
13509                    editor.navigate_to_hover_links(
13510                        Some(kind),
13511                        definitions
13512                            .into_iter()
13513                            .filter(|location| {
13514                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13515                            })
13516                            .map(HoverLink::Text)
13517                            .collect::<Vec<_>>(),
13518                        split,
13519                        window,
13520                        cx,
13521                    )
13522                })?
13523                .await?;
13524            anyhow::Ok(navigated)
13525        })
13526    }
13527
13528    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13529        let selection = self.selections.newest_anchor();
13530        let head = selection.head();
13531        let tail = selection.tail();
13532
13533        let Some((buffer, start_position)) =
13534            self.buffer.read(cx).text_anchor_for_position(head, cx)
13535        else {
13536            return;
13537        };
13538
13539        let end_position = if head != tail {
13540            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13541                return;
13542            };
13543            Some(pos)
13544        } else {
13545            None
13546        };
13547
13548        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13549            let url = if let Some(end_pos) = end_position {
13550                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13551            } else {
13552                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13553            };
13554
13555            if let Some(url) = url {
13556                editor.update(cx, |_, cx| {
13557                    cx.open_url(&url);
13558                })
13559            } else {
13560                Ok(())
13561            }
13562        });
13563
13564        url_finder.detach();
13565    }
13566
13567    pub fn open_selected_filename(
13568        &mut self,
13569        _: &OpenSelectedFilename,
13570        window: &mut Window,
13571        cx: &mut Context<Self>,
13572    ) {
13573        let Some(workspace) = self.workspace() else {
13574            return;
13575        };
13576
13577        let position = self.selections.newest_anchor().head();
13578
13579        let Some((buffer, buffer_position)) =
13580            self.buffer.read(cx).text_anchor_for_position(position, cx)
13581        else {
13582            return;
13583        };
13584
13585        let project = self.project.clone();
13586
13587        cx.spawn_in(window, async move |_, cx| {
13588            let result = find_file(&buffer, project, buffer_position, cx).await;
13589
13590            if let Some((_, path)) = result {
13591                workspace
13592                    .update_in(cx, |workspace, window, cx| {
13593                        workspace.open_resolved_path(path, window, cx)
13594                    })?
13595                    .await?;
13596            }
13597            anyhow::Ok(())
13598        })
13599        .detach();
13600    }
13601
13602    pub(crate) fn navigate_to_hover_links(
13603        &mut self,
13604        kind: Option<GotoDefinitionKind>,
13605        mut definitions: Vec<HoverLink>,
13606        split: bool,
13607        window: &mut Window,
13608        cx: &mut Context<Editor>,
13609    ) -> Task<Result<Navigated>> {
13610        // If there is one definition, just open it directly
13611        if definitions.len() == 1 {
13612            let definition = definitions.pop().unwrap();
13613
13614            enum TargetTaskResult {
13615                Location(Option<Location>),
13616                AlreadyNavigated,
13617            }
13618
13619            let target_task = match definition {
13620                HoverLink::Text(link) => {
13621                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13622                }
13623                HoverLink::InlayHint(lsp_location, server_id) => {
13624                    let computation =
13625                        self.compute_target_location(lsp_location, server_id, window, cx);
13626                    cx.background_spawn(async move {
13627                        let location = computation.await?;
13628                        Ok(TargetTaskResult::Location(location))
13629                    })
13630                }
13631                HoverLink::Url(url) => {
13632                    cx.open_url(&url);
13633                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13634                }
13635                HoverLink::File(path) => {
13636                    if let Some(workspace) = self.workspace() {
13637                        cx.spawn_in(window, async move |_, cx| {
13638                            workspace
13639                                .update_in(cx, |workspace, window, cx| {
13640                                    workspace.open_resolved_path(path, window, cx)
13641                                })?
13642                                .await
13643                                .map(|_| TargetTaskResult::AlreadyNavigated)
13644                        })
13645                    } else {
13646                        Task::ready(Ok(TargetTaskResult::Location(None)))
13647                    }
13648                }
13649            };
13650            cx.spawn_in(window, async move |editor, cx| {
13651                let target = match target_task.await.context("target resolution task")? {
13652                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13653                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13654                    TargetTaskResult::Location(Some(target)) => target,
13655                };
13656
13657                editor.update_in(cx, |editor, window, cx| {
13658                    let Some(workspace) = editor.workspace() else {
13659                        return Navigated::No;
13660                    };
13661                    let pane = workspace.read(cx).active_pane().clone();
13662
13663                    let range = target.range.to_point(target.buffer.read(cx));
13664                    let range = editor.range_for_match(&range);
13665                    let range = collapse_multiline_range(range);
13666
13667                    if !split
13668                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13669                    {
13670                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13671                    } else {
13672                        window.defer(cx, move |window, cx| {
13673                            let target_editor: Entity<Self> =
13674                                workspace.update(cx, |workspace, cx| {
13675                                    let pane = if split {
13676                                        workspace.adjacent_pane(window, cx)
13677                                    } else {
13678                                        workspace.active_pane().clone()
13679                                    };
13680
13681                                    workspace.open_project_item(
13682                                        pane,
13683                                        target.buffer.clone(),
13684                                        true,
13685                                        true,
13686                                        window,
13687                                        cx,
13688                                    )
13689                                });
13690                            target_editor.update(cx, |target_editor, cx| {
13691                                // When selecting a definition in a different buffer, disable the nav history
13692                                // to avoid creating a history entry at the previous cursor location.
13693                                pane.update(cx, |pane, _| pane.disable_history());
13694                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13695                                pane.update(cx, |pane, _| pane.enable_history());
13696                            });
13697                        });
13698                    }
13699                    Navigated::Yes
13700                })
13701            })
13702        } else if !definitions.is_empty() {
13703            cx.spawn_in(window, async move |editor, cx| {
13704                let (title, location_tasks, workspace) = editor
13705                    .update_in(cx, |editor, window, cx| {
13706                        let tab_kind = match kind {
13707                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13708                            _ => "Definitions",
13709                        };
13710                        let title = definitions
13711                            .iter()
13712                            .find_map(|definition| match definition {
13713                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13714                                    let buffer = origin.buffer.read(cx);
13715                                    format!(
13716                                        "{} for {}",
13717                                        tab_kind,
13718                                        buffer
13719                                            .text_for_range(origin.range.clone())
13720                                            .collect::<String>()
13721                                    )
13722                                }),
13723                                HoverLink::InlayHint(_, _) => None,
13724                                HoverLink::Url(_) => None,
13725                                HoverLink::File(_) => None,
13726                            })
13727                            .unwrap_or(tab_kind.to_string());
13728                        let location_tasks = definitions
13729                            .into_iter()
13730                            .map(|definition| match definition {
13731                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13732                                HoverLink::InlayHint(lsp_location, server_id) => editor
13733                                    .compute_target_location(lsp_location, server_id, window, cx),
13734                                HoverLink::Url(_) => Task::ready(Ok(None)),
13735                                HoverLink::File(_) => Task::ready(Ok(None)),
13736                            })
13737                            .collect::<Vec<_>>();
13738                        (title, location_tasks, editor.workspace().clone())
13739                    })
13740                    .context("location tasks preparation")?;
13741
13742                let locations = future::join_all(location_tasks)
13743                    .await
13744                    .into_iter()
13745                    .filter_map(|location| location.transpose())
13746                    .collect::<Result<_>>()
13747                    .context("location tasks")?;
13748
13749                let Some(workspace) = workspace else {
13750                    return Ok(Navigated::No);
13751                };
13752                let opened = workspace
13753                    .update_in(cx, |workspace, window, cx| {
13754                        Self::open_locations_in_multibuffer(
13755                            workspace,
13756                            locations,
13757                            title,
13758                            split,
13759                            MultibufferSelectionMode::First,
13760                            window,
13761                            cx,
13762                        )
13763                    })
13764                    .ok();
13765
13766                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13767            })
13768        } else {
13769            Task::ready(Ok(Navigated::No))
13770        }
13771    }
13772
13773    fn compute_target_location(
13774        &self,
13775        lsp_location: lsp::Location,
13776        server_id: LanguageServerId,
13777        window: &mut Window,
13778        cx: &mut Context<Self>,
13779    ) -> Task<anyhow::Result<Option<Location>>> {
13780        let Some(project) = self.project.clone() else {
13781            return Task::ready(Ok(None));
13782        };
13783
13784        cx.spawn_in(window, async move |editor, cx| {
13785            let location_task = editor.update(cx, |_, cx| {
13786                project.update(cx, |project, cx| {
13787                    let language_server_name = project
13788                        .language_server_statuses(cx)
13789                        .find(|(id, _)| server_id == *id)
13790                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13791                    language_server_name.map(|language_server_name| {
13792                        project.open_local_buffer_via_lsp(
13793                            lsp_location.uri.clone(),
13794                            server_id,
13795                            language_server_name,
13796                            cx,
13797                        )
13798                    })
13799                })
13800            })?;
13801            let location = match location_task {
13802                Some(task) => Some({
13803                    let target_buffer_handle = task.await.context("open local buffer")?;
13804                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13805                        let target_start = target_buffer
13806                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13807                        let target_end = target_buffer
13808                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13809                        target_buffer.anchor_after(target_start)
13810                            ..target_buffer.anchor_before(target_end)
13811                    })?;
13812                    Location {
13813                        buffer: target_buffer_handle,
13814                        range,
13815                    }
13816                }),
13817                None => None,
13818            };
13819            Ok(location)
13820        })
13821    }
13822
13823    pub fn find_all_references(
13824        &mut self,
13825        _: &FindAllReferences,
13826        window: &mut Window,
13827        cx: &mut Context<Self>,
13828    ) -> Option<Task<Result<Navigated>>> {
13829        let selection = self.selections.newest::<usize>(cx);
13830        let multi_buffer = self.buffer.read(cx);
13831        let head = selection.head();
13832
13833        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13834        let head_anchor = multi_buffer_snapshot.anchor_at(
13835            head,
13836            if head < selection.tail() {
13837                Bias::Right
13838            } else {
13839                Bias::Left
13840            },
13841        );
13842
13843        match self
13844            .find_all_references_task_sources
13845            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13846        {
13847            Ok(_) => {
13848                log::info!(
13849                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13850                );
13851                return None;
13852            }
13853            Err(i) => {
13854                self.find_all_references_task_sources.insert(i, head_anchor);
13855            }
13856        }
13857
13858        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13859        let workspace = self.workspace()?;
13860        let project = workspace.read(cx).project().clone();
13861        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13862        Some(cx.spawn_in(window, async move |editor, cx| {
13863            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13864                if let Ok(i) = editor
13865                    .find_all_references_task_sources
13866                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13867                {
13868                    editor.find_all_references_task_sources.remove(i);
13869                }
13870            });
13871
13872            let locations = references.await?;
13873            if locations.is_empty() {
13874                return anyhow::Ok(Navigated::No);
13875            }
13876
13877            workspace.update_in(cx, |workspace, window, cx| {
13878                let title = locations
13879                    .first()
13880                    .as_ref()
13881                    .map(|location| {
13882                        let buffer = location.buffer.read(cx);
13883                        format!(
13884                            "References to `{}`",
13885                            buffer
13886                                .text_for_range(location.range.clone())
13887                                .collect::<String>()
13888                        )
13889                    })
13890                    .unwrap();
13891                Self::open_locations_in_multibuffer(
13892                    workspace,
13893                    locations,
13894                    title,
13895                    false,
13896                    MultibufferSelectionMode::First,
13897                    window,
13898                    cx,
13899                );
13900                Navigated::Yes
13901            })
13902        }))
13903    }
13904
13905    /// Opens a multibuffer with the given project locations in it
13906    pub fn open_locations_in_multibuffer(
13907        workspace: &mut Workspace,
13908        mut locations: Vec<Location>,
13909        title: String,
13910        split: bool,
13911        multibuffer_selection_mode: MultibufferSelectionMode,
13912        window: &mut Window,
13913        cx: &mut Context<Workspace>,
13914    ) {
13915        // If there are multiple definitions, open them in a multibuffer
13916        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13917        let mut locations = locations.into_iter().peekable();
13918        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13919        let capability = workspace.project().read(cx).capability();
13920
13921        let excerpt_buffer = cx.new(|cx| {
13922            let mut multibuffer = MultiBuffer::new(capability);
13923            while let Some(location) = locations.next() {
13924                let buffer = location.buffer.read(cx);
13925                let mut ranges_for_buffer = Vec::new();
13926                let range = location.range.to_point(buffer);
13927                ranges_for_buffer.push(range.clone());
13928
13929                while let Some(next_location) = locations.peek() {
13930                    if next_location.buffer == location.buffer {
13931                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13932                        locations.next();
13933                    } else {
13934                        break;
13935                    }
13936                }
13937
13938                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13939                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13940                    PathKey::for_buffer(&location.buffer, cx),
13941                    location.buffer.clone(),
13942                    ranges_for_buffer,
13943                    DEFAULT_MULTIBUFFER_CONTEXT,
13944                    cx,
13945                );
13946                ranges.extend(new_ranges)
13947            }
13948
13949            multibuffer.with_title(title)
13950        });
13951
13952        let editor = cx.new(|cx| {
13953            Editor::for_multibuffer(
13954                excerpt_buffer,
13955                Some(workspace.project().clone()),
13956                window,
13957                cx,
13958            )
13959        });
13960        editor.update(cx, |editor, cx| {
13961            match multibuffer_selection_mode {
13962                MultibufferSelectionMode::First => {
13963                    if let Some(first_range) = ranges.first() {
13964                        editor.change_selections(None, window, cx, |selections| {
13965                            selections.clear_disjoint();
13966                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13967                        });
13968                    }
13969                    editor.highlight_background::<Self>(
13970                        &ranges,
13971                        |theme| theme.editor_highlighted_line_background,
13972                        cx,
13973                    );
13974                }
13975                MultibufferSelectionMode::All => {
13976                    editor.change_selections(None, window, cx, |selections| {
13977                        selections.clear_disjoint();
13978                        selections.select_anchor_ranges(ranges);
13979                    });
13980                }
13981            }
13982            editor.register_buffers_with_language_servers(cx);
13983        });
13984
13985        let item = Box::new(editor);
13986        let item_id = item.item_id();
13987
13988        if split {
13989            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13990        } else {
13991            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13992                let (preview_item_id, preview_item_idx) =
13993                    workspace.active_pane().update(cx, |pane, _| {
13994                        (pane.preview_item_id(), pane.preview_item_idx())
13995                    });
13996
13997                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13998
13999                if let Some(preview_item_id) = preview_item_id {
14000                    workspace.active_pane().update(cx, |pane, cx| {
14001                        pane.remove_item(preview_item_id, false, false, window, cx);
14002                    });
14003                }
14004            } else {
14005                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14006            }
14007        }
14008        workspace.active_pane().update(cx, |pane, cx| {
14009            pane.set_preview_item_id(Some(item_id), cx);
14010        });
14011    }
14012
14013    pub fn rename(
14014        &mut self,
14015        _: &Rename,
14016        window: &mut Window,
14017        cx: &mut Context<Self>,
14018    ) -> Option<Task<Result<()>>> {
14019        use language::ToOffset as _;
14020
14021        let provider = self.semantics_provider.clone()?;
14022        let selection = self.selections.newest_anchor().clone();
14023        let (cursor_buffer, cursor_buffer_position) = self
14024            .buffer
14025            .read(cx)
14026            .text_anchor_for_position(selection.head(), cx)?;
14027        let (tail_buffer, cursor_buffer_position_end) = self
14028            .buffer
14029            .read(cx)
14030            .text_anchor_for_position(selection.tail(), cx)?;
14031        if tail_buffer != cursor_buffer {
14032            return None;
14033        }
14034
14035        let snapshot = cursor_buffer.read(cx).snapshot();
14036        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14037        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14038        let prepare_rename = provider
14039            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14040            .unwrap_or_else(|| Task::ready(Ok(None)));
14041        drop(snapshot);
14042
14043        Some(cx.spawn_in(window, async move |this, cx| {
14044            let rename_range = if let Some(range) = prepare_rename.await? {
14045                Some(range)
14046            } else {
14047                this.update(cx, |this, cx| {
14048                    let buffer = this.buffer.read(cx).snapshot(cx);
14049                    let mut buffer_highlights = this
14050                        .document_highlights_for_position(selection.head(), &buffer)
14051                        .filter(|highlight| {
14052                            highlight.start.excerpt_id == selection.head().excerpt_id
14053                                && highlight.end.excerpt_id == selection.head().excerpt_id
14054                        });
14055                    buffer_highlights
14056                        .next()
14057                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14058                })?
14059            };
14060            if let Some(rename_range) = rename_range {
14061                this.update_in(cx, |this, window, cx| {
14062                    let snapshot = cursor_buffer.read(cx).snapshot();
14063                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14064                    let cursor_offset_in_rename_range =
14065                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14066                    let cursor_offset_in_rename_range_end =
14067                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14068
14069                    this.take_rename(false, window, cx);
14070                    let buffer = this.buffer.read(cx).read(cx);
14071                    let cursor_offset = selection.head().to_offset(&buffer);
14072                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14073                    let rename_end = rename_start + rename_buffer_range.len();
14074                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14075                    let mut old_highlight_id = None;
14076                    let old_name: Arc<str> = buffer
14077                        .chunks(rename_start..rename_end, true)
14078                        .map(|chunk| {
14079                            if old_highlight_id.is_none() {
14080                                old_highlight_id = chunk.syntax_highlight_id;
14081                            }
14082                            chunk.text
14083                        })
14084                        .collect::<String>()
14085                        .into();
14086
14087                    drop(buffer);
14088
14089                    // Position the selection in the rename editor so that it matches the current selection.
14090                    this.show_local_selections = false;
14091                    let rename_editor = cx.new(|cx| {
14092                        let mut editor = Editor::single_line(window, cx);
14093                        editor.buffer.update(cx, |buffer, cx| {
14094                            buffer.edit([(0..0, old_name.clone())], None, cx)
14095                        });
14096                        let rename_selection_range = match cursor_offset_in_rename_range
14097                            .cmp(&cursor_offset_in_rename_range_end)
14098                        {
14099                            Ordering::Equal => {
14100                                editor.select_all(&SelectAll, window, cx);
14101                                return editor;
14102                            }
14103                            Ordering::Less => {
14104                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14105                            }
14106                            Ordering::Greater => {
14107                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14108                            }
14109                        };
14110                        if rename_selection_range.end > old_name.len() {
14111                            editor.select_all(&SelectAll, window, cx);
14112                        } else {
14113                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14114                                s.select_ranges([rename_selection_range]);
14115                            });
14116                        }
14117                        editor
14118                    });
14119                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14120                        if e == &EditorEvent::Focused {
14121                            cx.emit(EditorEvent::FocusedIn)
14122                        }
14123                    })
14124                    .detach();
14125
14126                    let write_highlights =
14127                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14128                    let read_highlights =
14129                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14130                    let ranges = write_highlights
14131                        .iter()
14132                        .flat_map(|(_, ranges)| ranges.iter())
14133                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14134                        .cloned()
14135                        .collect();
14136
14137                    this.highlight_text::<Rename>(
14138                        ranges,
14139                        HighlightStyle {
14140                            fade_out: Some(0.6),
14141                            ..Default::default()
14142                        },
14143                        cx,
14144                    );
14145                    let rename_focus_handle = rename_editor.focus_handle(cx);
14146                    window.focus(&rename_focus_handle);
14147                    let block_id = this.insert_blocks(
14148                        [BlockProperties {
14149                            style: BlockStyle::Flex,
14150                            placement: BlockPlacement::Below(range.start),
14151                            height: Some(1),
14152                            render: Arc::new({
14153                                let rename_editor = rename_editor.clone();
14154                                move |cx: &mut BlockContext| {
14155                                    let mut text_style = cx.editor_style.text.clone();
14156                                    if let Some(highlight_style) = old_highlight_id
14157                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14158                                    {
14159                                        text_style = text_style.highlight(highlight_style);
14160                                    }
14161                                    div()
14162                                        .block_mouse_down()
14163                                        .pl(cx.anchor_x)
14164                                        .child(EditorElement::new(
14165                                            &rename_editor,
14166                                            EditorStyle {
14167                                                background: cx.theme().system().transparent,
14168                                                local_player: cx.editor_style.local_player,
14169                                                text: text_style,
14170                                                scrollbar_width: cx.editor_style.scrollbar_width,
14171                                                syntax: cx.editor_style.syntax.clone(),
14172                                                status: cx.editor_style.status.clone(),
14173                                                inlay_hints_style: HighlightStyle {
14174                                                    font_weight: Some(FontWeight::BOLD),
14175                                                    ..make_inlay_hints_style(cx.app)
14176                                                },
14177                                                inline_completion_styles: make_suggestion_styles(
14178                                                    cx.app,
14179                                                ),
14180                                                ..EditorStyle::default()
14181                                            },
14182                                        ))
14183                                        .into_any_element()
14184                                }
14185                            }),
14186                            priority: 0,
14187                        }],
14188                        Some(Autoscroll::fit()),
14189                        cx,
14190                    )[0];
14191                    this.pending_rename = Some(RenameState {
14192                        range,
14193                        old_name,
14194                        editor: rename_editor,
14195                        block_id,
14196                    });
14197                })?;
14198            }
14199
14200            Ok(())
14201        }))
14202    }
14203
14204    pub fn confirm_rename(
14205        &mut self,
14206        _: &ConfirmRename,
14207        window: &mut Window,
14208        cx: &mut Context<Self>,
14209    ) -> Option<Task<Result<()>>> {
14210        let rename = self.take_rename(false, window, cx)?;
14211        let workspace = self.workspace()?.downgrade();
14212        let (buffer, start) = self
14213            .buffer
14214            .read(cx)
14215            .text_anchor_for_position(rename.range.start, cx)?;
14216        let (end_buffer, _) = self
14217            .buffer
14218            .read(cx)
14219            .text_anchor_for_position(rename.range.end, cx)?;
14220        if buffer != end_buffer {
14221            return None;
14222        }
14223
14224        let old_name = rename.old_name;
14225        let new_name = rename.editor.read(cx).text(cx);
14226
14227        let rename = self.semantics_provider.as_ref()?.perform_rename(
14228            &buffer,
14229            start,
14230            new_name.clone(),
14231            cx,
14232        )?;
14233
14234        Some(cx.spawn_in(window, async move |editor, cx| {
14235            let project_transaction = rename.await?;
14236            Self::open_project_transaction(
14237                &editor,
14238                workspace,
14239                project_transaction,
14240                format!("Rename: {}{}", old_name, new_name),
14241                cx,
14242            )
14243            .await?;
14244
14245            editor.update(cx, |editor, cx| {
14246                editor.refresh_document_highlights(cx);
14247            })?;
14248            Ok(())
14249        }))
14250    }
14251
14252    fn take_rename(
14253        &mut self,
14254        moving_cursor: bool,
14255        window: &mut Window,
14256        cx: &mut Context<Self>,
14257    ) -> Option<RenameState> {
14258        let rename = self.pending_rename.take()?;
14259        if rename.editor.focus_handle(cx).is_focused(window) {
14260            window.focus(&self.focus_handle);
14261        }
14262
14263        self.remove_blocks(
14264            [rename.block_id].into_iter().collect(),
14265            Some(Autoscroll::fit()),
14266            cx,
14267        );
14268        self.clear_highlights::<Rename>(cx);
14269        self.show_local_selections = true;
14270
14271        if moving_cursor {
14272            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14273                editor.selections.newest::<usize>(cx).head()
14274            });
14275
14276            // Update the selection to match the position of the selection inside
14277            // the rename editor.
14278            let snapshot = self.buffer.read(cx).read(cx);
14279            let rename_range = rename.range.to_offset(&snapshot);
14280            let cursor_in_editor = snapshot
14281                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14282                .min(rename_range.end);
14283            drop(snapshot);
14284
14285            self.change_selections(None, window, cx, |s| {
14286                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14287            });
14288        } else {
14289            self.refresh_document_highlights(cx);
14290        }
14291
14292        Some(rename)
14293    }
14294
14295    pub fn pending_rename(&self) -> Option<&RenameState> {
14296        self.pending_rename.as_ref()
14297    }
14298
14299    fn format(
14300        &mut self,
14301        _: &Format,
14302        window: &mut Window,
14303        cx: &mut Context<Self>,
14304    ) -> Option<Task<Result<()>>> {
14305        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14306
14307        let project = match &self.project {
14308            Some(project) => project.clone(),
14309            None => return None,
14310        };
14311
14312        Some(self.perform_format(
14313            project,
14314            FormatTrigger::Manual,
14315            FormatTarget::Buffers,
14316            window,
14317            cx,
14318        ))
14319    }
14320
14321    fn format_selections(
14322        &mut self,
14323        _: &FormatSelections,
14324        window: &mut Window,
14325        cx: &mut Context<Self>,
14326    ) -> Option<Task<Result<()>>> {
14327        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14328
14329        let project = match &self.project {
14330            Some(project) => project.clone(),
14331            None => return None,
14332        };
14333
14334        let ranges = self
14335            .selections
14336            .all_adjusted(cx)
14337            .into_iter()
14338            .map(|selection| selection.range())
14339            .collect_vec();
14340
14341        Some(self.perform_format(
14342            project,
14343            FormatTrigger::Manual,
14344            FormatTarget::Ranges(ranges),
14345            window,
14346            cx,
14347        ))
14348    }
14349
14350    fn perform_format(
14351        &mut self,
14352        project: Entity<Project>,
14353        trigger: FormatTrigger,
14354        target: FormatTarget,
14355        window: &mut Window,
14356        cx: &mut Context<Self>,
14357    ) -> Task<Result<()>> {
14358        let buffer = self.buffer.clone();
14359        let (buffers, target) = match target {
14360            FormatTarget::Buffers => {
14361                let mut buffers = buffer.read(cx).all_buffers();
14362                if trigger == FormatTrigger::Save {
14363                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14364                }
14365                (buffers, LspFormatTarget::Buffers)
14366            }
14367            FormatTarget::Ranges(selection_ranges) => {
14368                let multi_buffer = buffer.read(cx);
14369                let snapshot = multi_buffer.read(cx);
14370                let mut buffers = HashSet::default();
14371                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14372                    BTreeMap::new();
14373                for selection_range in selection_ranges {
14374                    for (buffer, buffer_range, _) in
14375                        snapshot.range_to_buffer_ranges(selection_range)
14376                    {
14377                        let buffer_id = buffer.remote_id();
14378                        let start = buffer.anchor_before(buffer_range.start);
14379                        let end = buffer.anchor_after(buffer_range.end);
14380                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14381                        buffer_id_to_ranges
14382                            .entry(buffer_id)
14383                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14384                            .or_insert_with(|| vec![start..end]);
14385                    }
14386                }
14387                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14388            }
14389        };
14390
14391        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14392        let selections_prev = transaction_id_prev
14393            .and_then(|transaction_id_prev| {
14394                // default to selections as they were after the last edit, if we have them,
14395                // instead of how they are now.
14396                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14397                // will take you back to where you made the last edit, instead of staying where you scrolled
14398                self.selection_history
14399                    .transaction(transaction_id_prev)
14400                    .map(|t| t.0.clone())
14401            })
14402            .unwrap_or_else(|| {
14403                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14404                self.selections.disjoint_anchors()
14405            });
14406
14407        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14408        let format = project.update(cx, |project, cx| {
14409            project.format(buffers, target, true, trigger, cx)
14410        });
14411
14412        cx.spawn_in(window, async move |editor, cx| {
14413            let transaction = futures::select_biased! {
14414                transaction = format.log_err().fuse() => transaction,
14415                () = timeout => {
14416                    log::warn!("timed out waiting for formatting");
14417                    None
14418                }
14419            };
14420
14421            buffer
14422                .update(cx, |buffer, cx| {
14423                    if let Some(transaction) = transaction {
14424                        if !buffer.is_singleton() {
14425                            buffer.push_transaction(&transaction.0, cx);
14426                        }
14427                    }
14428                    cx.notify();
14429                })
14430                .ok();
14431
14432            if let Some(transaction_id_now) =
14433                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14434            {
14435                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14436                if has_new_transaction {
14437                    _ = editor.update(cx, |editor, _| {
14438                        editor
14439                            .selection_history
14440                            .insert_transaction(transaction_id_now, selections_prev);
14441                    });
14442                }
14443            }
14444
14445            Ok(())
14446        })
14447    }
14448
14449    fn organize_imports(
14450        &mut self,
14451        _: &OrganizeImports,
14452        window: &mut Window,
14453        cx: &mut Context<Self>,
14454    ) -> Option<Task<Result<()>>> {
14455        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14456        let project = match &self.project {
14457            Some(project) => project.clone(),
14458            None => return None,
14459        };
14460        Some(self.perform_code_action_kind(
14461            project,
14462            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14463            window,
14464            cx,
14465        ))
14466    }
14467
14468    fn perform_code_action_kind(
14469        &mut self,
14470        project: Entity<Project>,
14471        kind: CodeActionKind,
14472        window: &mut Window,
14473        cx: &mut Context<Self>,
14474    ) -> Task<Result<()>> {
14475        let buffer = self.buffer.clone();
14476        let buffers = buffer.read(cx).all_buffers();
14477        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14478        let apply_action = project.update(cx, |project, cx| {
14479            project.apply_code_action_kind(buffers, kind, true, cx)
14480        });
14481        cx.spawn_in(window, async move |_, cx| {
14482            let transaction = futures::select_biased! {
14483                () = timeout => {
14484                    log::warn!("timed out waiting for executing code action");
14485                    None
14486                }
14487                transaction = apply_action.log_err().fuse() => transaction,
14488            };
14489            buffer
14490                .update(cx, |buffer, cx| {
14491                    // check if we need this
14492                    if let Some(transaction) = transaction {
14493                        if !buffer.is_singleton() {
14494                            buffer.push_transaction(&transaction.0, cx);
14495                        }
14496                    }
14497                    cx.notify();
14498                })
14499                .ok();
14500            Ok(())
14501        })
14502    }
14503
14504    fn restart_language_server(
14505        &mut self,
14506        _: &RestartLanguageServer,
14507        _: &mut Window,
14508        cx: &mut Context<Self>,
14509    ) {
14510        if let Some(project) = self.project.clone() {
14511            self.buffer.update(cx, |multi_buffer, cx| {
14512                project.update(cx, |project, cx| {
14513                    project.restart_language_servers_for_buffers(
14514                        multi_buffer.all_buffers().into_iter().collect(),
14515                        cx,
14516                    );
14517                });
14518            })
14519        }
14520    }
14521
14522    fn stop_language_server(
14523        &mut self,
14524        _: &StopLanguageServer,
14525        _: &mut Window,
14526        cx: &mut Context<Self>,
14527    ) {
14528        if let Some(project) = self.project.clone() {
14529            self.buffer.update(cx, |multi_buffer, cx| {
14530                project.update(cx, |project, cx| {
14531                    project.stop_language_servers_for_buffers(
14532                        multi_buffer.all_buffers().into_iter().collect(),
14533                        cx,
14534                    );
14535                    cx.emit(project::Event::RefreshInlayHints);
14536                });
14537            });
14538        }
14539    }
14540
14541    fn cancel_language_server_work(
14542        workspace: &mut Workspace,
14543        _: &actions::CancelLanguageServerWork,
14544        _: &mut Window,
14545        cx: &mut Context<Workspace>,
14546    ) {
14547        let project = workspace.project();
14548        let buffers = workspace
14549            .active_item(cx)
14550            .and_then(|item| item.act_as::<Editor>(cx))
14551            .map_or(HashSet::default(), |editor| {
14552                editor.read(cx).buffer.read(cx).all_buffers()
14553            });
14554        project.update(cx, |project, cx| {
14555            project.cancel_language_server_work_for_buffers(buffers, cx);
14556        });
14557    }
14558
14559    fn show_character_palette(
14560        &mut self,
14561        _: &ShowCharacterPalette,
14562        window: &mut Window,
14563        _: &mut Context<Self>,
14564    ) {
14565        window.show_character_palette();
14566    }
14567
14568    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14569        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14570            let buffer = self.buffer.read(cx).snapshot(cx);
14571            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14572            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14573            let is_valid = buffer
14574                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14575                .any(|entry| {
14576                    entry.diagnostic.is_primary
14577                        && !entry.range.is_empty()
14578                        && entry.range.start == primary_range_start
14579                        && entry.diagnostic.message == active_diagnostics.active_message
14580                });
14581
14582            if !is_valid {
14583                self.dismiss_diagnostics(cx);
14584            }
14585        }
14586    }
14587
14588    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14589        match &self.active_diagnostics {
14590            ActiveDiagnostic::Group(group) => Some(group),
14591            _ => None,
14592        }
14593    }
14594
14595    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14596        self.dismiss_diagnostics(cx);
14597        self.active_diagnostics = ActiveDiagnostic::All;
14598    }
14599
14600    fn activate_diagnostics(
14601        &mut self,
14602        buffer_id: BufferId,
14603        diagnostic: DiagnosticEntry<usize>,
14604        window: &mut Window,
14605        cx: &mut Context<Self>,
14606    ) {
14607        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14608            return;
14609        }
14610        self.dismiss_diagnostics(cx);
14611        let snapshot = self.snapshot(window, cx);
14612        let Some(diagnostic_renderer) = cx
14613            .try_global::<GlobalDiagnosticRenderer>()
14614            .map(|g| g.0.clone())
14615        else {
14616            return;
14617        };
14618        let buffer = self.buffer.read(cx).snapshot(cx);
14619
14620        let diagnostic_group = buffer
14621            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14622            .collect::<Vec<_>>();
14623
14624        let blocks = diagnostic_renderer.render_group(
14625            diagnostic_group,
14626            buffer_id,
14627            snapshot,
14628            cx.weak_entity(),
14629            cx,
14630        );
14631
14632        let blocks = self.display_map.update(cx, |display_map, cx| {
14633            display_map.insert_blocks(blocks, cx).into_iter().collect()
14634        });
14635        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14636            active_range: buffer.anchor_before(diagnostic.range.start)
14637                ..buffer.anchor_after(diagnostic.range.end),
14638            active_message: diagnostic.diagnostic.message.clone(),
14639            group_id: diagnostic.diagnostic.group_id,
14640            blocks,
14641        });
14642        cx.notify();
14643    }
14644
14645    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14646        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14647            return;
14648        };
14649
14650        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14651        if let ActiveDiagnostic::Group(group) = prev {
14652            self.display_map.update(cx, |display_map, cx| {
14653                display_map.remove_blocks(group.blocks, cx);
14654            });
14655            cx.notify();
14656        }
14657    }
14658
14659    /// Disable inline diagnostics rendering for this editor.
14660    pub fn disable_inline_diagnostics(&mut self) {
14661        self.inline_diagnostics_enabled = false;
14662        self.inline_diagnostics_update = Task::ready(());
14663        self.inline_diagnostics.clear();
14664    }
14665
14666    pub fn inline_diagnostics_enabled(&self) -> bool {
14667        self.inline_diagnostics_enabled
14668    }
14669
14670    pub fn show_inline_diagnostics(&self) -> bool {
14671        self.show_inline_diagnostics
14672    }
14673
14674    pub fn toggle_inline_diagnostics(
14675        &mut self,
14676        _: &ToggleInlineDiagnostics,
14677        window: &mut Window,
14678        cx: &mut Context<Editor>,
14679    ) {
14680        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14681        self.refresh_inline_diagnostics(false, window, cx);
14682    }
14683
14684    fn refresh_inline_diagnostics(
14685        &mut self,
14686        debounce: bool,
14687        window: &mut Window,
14688        cx: &mut Context<Self>,
14689    ) {
14690        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14691            self.inline_diagnostics_update = Task::ready(());
14692            self.inline_diagnostics.clear();
14693            return;
14694        }
14695
14696        let debounce_ms = ProjectSettings::get_global(cx)
14697            .diagnostics
14698            .inline
14699            .update_debounce_ms;
14700        let debounce = if debounce && debounce_ms > 0 {
14701            Some(Duration::from_millis(debounce_ms))
14702        } else {
14703            None
14704        };
14705        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14706            let editor = editor.upgrade().unwrap();
14707
14708            if let Some(debounce) = debounce {
14709                cx.background_executor().timer(debounce).await;
14710            }
14711            let Some(snapshot) = editor
14712                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14713                .ok()
14714            else {
14715                return;
14716            };
14717
14718            let new_inline_diagnostics = cx
14719                .background_spawn(async move {
14720                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14721                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14722                        let message = diagnostic_entry
14723                            .diagnostic
14724                            .message
14725                            .split_once('\n')
14726                            .map(|(line, _)| line)
14727                            .map(SharedString::new)
14728                            .unwrap_or_else(|| {
14729                                SharedString::from(diagnostic_entry.diagnostic.message)
14730                            });
14731                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14732                        let (Ok(i) | Err(i)) = inline_diagnostics
14733                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14734                        inline_diagnostics.insert(
14735                            i,
14736                            (
14737                                start_anchor,
14738                                InlineDiagnostic {
14739                                    message,
14740                                    group_id: diagnostic_entry.diagnostic.group_id,
14741                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14742                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14743                                    severity: diagnostic_entry.diagnostic.severity,
14744                                },
14745                            ),
14746                        );
14747                    }
14748                    inline_diagnostics
14749                })
14750                .await;
14751
14752            editor
14753                .update(cx, |editor, cx| {
14754                    editor.inline_diagnostics = new_inline_diagnostics;
14755                    cx.notify();
14756                })
14757                .ok();
14758        });
14759    }
14760
14761    pub fn set_selections_from_remote(
14762        &mut self,
14763        selections: Vec<Selection<Anchor>>,
14764        pending_selection: Option<Selection<Anchor>>,
14765        window: &mut Window,
14766        cx: &mut Context<Self>,
14767    ) {
14768        let old_cursor_position = self.selections.newest_anchor().head();
14769        self.selections.change_with(cx, |s| {
14770            s.select_anchors(selections);
14771            if let Some(pending_selection) = pending_selection {
14772                s.set_pending(pending_selection, SelectMode::Character);
14773            } else {
14774                s.clear_pending();
14775            }
14776        });
14777        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14778    }
14779
14780    fn push_to_selection_history(&mut self) {
14781        self.selection_history.push(SelectionHistoryEntry {
14782            selections: self.selections.disjoint_anchors(),
14783            select_next_state: self.select_next_state.clone(),
14784            select_prev_state: self.select_prev_state.clone(),
14785            add_selections_state: self.add_selections_state.clone(),
14786        });
14787    }
14788
14789    pub fn transact(
14790        &mut self,
14791        window: &mut Window,
14792        cx: &mut Context<Self>,
14793        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14794    ) -> Option<TransactionId> {
14795        self.start_transaction_at(Instant::now(), window, cx);
14796        update(self, window, cx);
14797        self.end_transaction_at(Instant::now(), cx)
14798    }
14799
14800    pub fn start_transaction_at(
14801        &mut self,
14802        now: Instant,
14803        window: &mut Window,
14804        cx: &mut Context<Self>,
14805    ) {
14806        self.end_selection(window, cx);
14807        if let Some(tx_id) = self
14808            .buffer
14809            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14810        {
14811            self.selection_history
14812                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14813            cx.emit(EditorEvent::TransactionBegun {
14814                transaction_id: tx_id,
14815            })
14816        }
14817    }
14818
14819    pub fn end_transaction_at(
14820        &mut self,
14821        now: Instant,
14822        cx: &mut Context<Self>,
14823    ) -> Option<TransactionId> {
14824        if let Some(transaction_id) = self
14825            .buffer
14826            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14827        {
14828            if let Some((_, end_selections)) =
14829                self.selection_history.transaction_mut(transaction_id)
14830            {
14831                *end_selections = Some(self.selections.disjoint_anchors());
14832            } else {
14833                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14834            }
14835
14836            cx.emit(EditorEvent::Edited { transaction_id });
14837            Some(transaction_id)
14838        } else {
14839            None
14840        }
14841    }
14842
14843    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14844        if self.selection_mark_mode {
14845            self.change_selections(None, window, cx, |s| {
14846                s.move_with(|_, sel| {
14847                    sel.collapse_to(sel.head(), SelectionGoal::None);
14848                });
14849            })
14850        }
14851        self.selection_mark_mode = true;
14852        cx.notify();
14853    }
14854
14855    pub fn swap_selection_ends(
14856        &mut self,
14857        _: &actions::SwapSelectionEnds,
14858        window: &mut Window,
14859        cx: &mut Context<Self>,
14860    ) {
14861        self.change_selections(None, window, cx, |s| {
14862            s.move_with(|_, sel| {
14863                if sel.start != sel.end {
14864                    sel.reversed = !sel.reversed
14865                }
14866            });
14867        });
14868        self.request_autoscroll(Autoscroll::newest(), cx);
14869        cx.notify();
14870    }
14871
14872    pub fn toggle_fold(
14873        &mut self,
14874        _: &actions::ToggleFold,
14875        window: &mut Window,
14876        cx: &mut Context<Self>,
14877    ) {
14878        if self.is_singleton(cx) {
14879            let selection = self.selections.newest::<Point>(cx);
14880
14881            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14882            let range = if selection.is_empty() {
14883                let point = selection.head().to_display_point(&display_map);
14884                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14885                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14886                    .to_point(&display_map);
14887                start..end
14888            } else {
14889                selection.range()
14890            };
14891            if display_map.folds_in_range(range).next().is_some() {
14892                self.unfold_lines(&Default::default(), window, cx)
14893            } else {
14894                self.fold(&Default::default(), window, cx)
14895            }
14896        } else {
14897            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14898            let buffer_ids: HashSet<_> = self
14899                .selections
14900                .disjoint_anchor_ranges()
14901                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14902                .collect();
14903
14904            let should_unfold = buffer_ids
14905                .iter()
14906                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14907
14908            for buffer_id in buffer_ids {
14909                if should_unfold {
14910                    self.unfold_buffer(buffer_id, cx);
14911                } else {
14912                    self.fold_buffer(buffer_id, cx);
14913                }
14914            }
14915        }
14916    }
14917
14918    pub fn toggle_fold_recursive(
14919        &mut self,
14920        _: &actions::ToggleFoldRecursive,
14921        window: &mut Window,
14922        cx: &mut Context<Self>,
14923    ) {
14924        let selection = self.selections.newest::<Point>(cx);
14925
14926        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14927        let range = if selection.is_empty() {
14928            let point = selection.head().to_display_point(&display_map);
14929            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14930            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14931                .to_point(&display_map);
14932            start..end
14933        } else {
14934            selection.range()
14935        };
14936        if display_map.folds_in_range(range).next().is_some() {
14937            self.unfold_recursive(&Default::default(), window, cx)
14938        } else {
14939            self.fold_recursive(&Default::default(), window, cx)
14940        }
14941    }
14942
14943    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14944        if self.is_singleton(cx) {
14945            let mut to_fold = Vec::new();
14946            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14947            let selections = self.selections.all_adjusted(cx);
14948
14949            for selection in selections {
14950                let range = selection.range().sorted();
14951                let buffer_start_row = range.start.row;
14952
14953                if range.start.row != range.end.row {
14954                    let mut found = false;
14955                    let mut row = range.start.row;
14956                    while row <= range.end.row {
14957                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14958                        {
14959                            found = true;
14960                            row = crease.range().end.row + 1;
14961                            to_fold.push(crease);
14962                        } else {
14963                            row += 1
14964                        }
14965                    }
14966                    if found {
14967                        continue;
14968                    }
14969                }
14970
14971                for row in (0..=range.start.row).rev() {
14972                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14973                        if crease.range().end.row >= buffer_start_row {
14974                            to_fold.push(crease);
14975                            if row <= range.start.row {
14976                                break;
14977                            }
14978                        }
14979                    }
14980                }
14981            }
14982
14983            self.fold_creases(to_fold, true, window, cx);
14984        } else {
14985            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14986            let buffer_ids = self
14987                .selections
14988                .disjoint_anchor_ranges()
14989                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14990                .collect::<HashSet<_>>();
14991            for buffer_id in buffer_ids {
14992                self.fold_buffer(buffer_id, cx);
14993            }
14994        }
14995    }
14996
14997    fn fold_at_level(
14998        &mut self,
14999        fold_at: &FoldAtLevel,
15000        window: &mut Window,
15001        cx: &mut Context<Self>,
15002    ) {
15003        if !self.buffer.read(cx).is_singleton() {
15004            return;
15005        }
15006
15007        let fold_at_level = fold_at.0;
15008        let snapshot = self.buffer.read(cx).snapshot(cx);
15009        let mut to_fold = Vec::new();
15010        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15011
15012        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15013            while start_row < end_row {
15014                match self
15015                    .snapshot(window, cx)
15016                    .crease_for_buffer_row(MultiBufferRow(start_row))
15017                {
15018                    Some(crease) => {
15019                        let nested_start_row = crease.range().start.row + 1;
15020                        let nested_end_row = crease.range().end.row;
15021
15022                        if current_level < fold_at_level {
15023                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15024                        } else if current_level == fold_at_level {
15025                            to_fold.push(crease);
15026                        }
15027
15028                        start_row = nested_end_row + 1;
15029                    }
15030                    None => start_row += 1,
15031                }
15032            }
15033        }
15034
15035        self.fold_creases(to_fold, true, window, cx);
15036    }
15037
15038    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15039        if self.buffer.read(cx).is_singleton() {
15040            let mut fold_ranges = Vec::new();
15041            let snapshot = self.buffer.read(cx).snapshot(cx);
15042
15043            for row in 0..snapshot.max_row().0 {
15044                if let Some(foldable_range) = self
15045                    .snapshot(window, cx)
15046                    .crease_for_buffer_row(MultiBufferRow(row))
15047                {
15048                    fold_ranges.push(foldable_range);
15049                }
15050            }
15051
15052            self.fold_creases(fold_ranges, true, window, cx);
15053        } else {
15054            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15055                editor
15056                    .update_in(cx, |editor, _, cx| {
15057                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15058                            editor.fold_buffer(buffer_id, cx);
15059                        }
15060                    })
15061                    .ok();
15062            });
15063        }
15064    }
15065
15066    pub fn fold_function_bodies(
15067        &mut self,
15068        _: &actions::FoldFunctionBodies,
15069        window: &mut Window,
15070        cx: &mut Context<Self>,
15071    ) {
15072        let snapshot = self.buffer.read(cx).snapshot(cx);
15073
15074        let ranges = snapshot
15075            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15076            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15077            .collect::<Vec<_>>();
15078
15079        let creases = ranges
15080            .into_iter()
15081            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15082            .collect();
15083
15084        self.fold_creases(creases, true, window, cx);
15085    }
15086
15087    pub fn fold_recursive(
15088        &mut self,
15089        _: &actions::FoldRecursive,
15090        window: &mut Window,
15091        cx: &mut Context<Self>,
15092    ) {
15093        let mut to_fold = Vec::new();
15094        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15095        let selections = self.selections.all_adjusted(cx);
15096
15097        for selection in selections {
15098            let range = selection.range().sorted();
15099            let buffer_start_row = range.start.row;
15100
15101            if range.start.row != range.end.row {
15102                let mut found = false;
15103                for row in range.start.row..=range.end.row {
15104                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15105                        found = true;
15106                        to_fold.push(crease);
15107                    }
15108                }
15109                if found {
15110                    continue;
15111                }
15112            }
15113
15114            for row in (0..=range.start.row).rev() {
15115                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15116                    if crease.range().end.row >= buffer_start_row {
15117                        to_fold.push(crease);
15118                    } else {
15119                        break;
15120                    }
15121                }
15122            }
15123        }
15124
15125        self.fold_creases(to_fold, true, window, cx);
15126    }
15127
15128    pub fn fold_at(
15129        &mut self,
15130        buffer_row: MultiBufferRow,
15131        window: &mut Window,
15132        cx: &mut Context<Self>,
15133    ) {
15134        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15135
15136        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15137            let autoscroll = self
15138                .selections
15139                .all::<Point>(cx)
15140                .iter()
15141                .any(|selection| crease.range().overlaps(&selection.range()));
15142
15143            self.fold_creases(vec![crease], autoscroll, window, cx);
15144        }
15145    }
15146
15147    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15148        if self.is_singleton(cx) {
15149            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15150            let buffer = &display_map.buffer_snapshot;
15151            let selections = self.selections.all::<Point>(cx);
15152            let ranges = selections
15153                .iter()
15154                .map(|s| {
15155                    let range = s.display_range(&display_map).sorted();
15156                    let mut start = range.start.to_point(&display_map);
15157                    let mut end = range.end.to_point(&display_map);
15158                    start.column = 0;
15159                    end.column = buffer.line_len(MultiBufferRow(end.row));
15160                    start..end
15161                })
15162                .collect::<Vec<_>>();
15163
15164            self.unfold_ranges(&ranges, true, true, cx);
15165        } else {
15166            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15167            let buffer_ids = self
15168                .selections
15169                .disjoint_anchor_ranges()
15170                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15171                .collect::<HashSet<_>>();
15172            for buffer_id in buffer_ids {
15173                self.unfold_buffer(buffer_id, cx);
15174            }
15175        }
15176    }
15177
15178    pub fn unfold_recursive(
15179        &mut self,
15180        _: &UnfoldRecursive,
15181        _window: &mut Window,
15182        cx: &mut Context<Self>,
15183    ) {
15184        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15185        let selections = self.selections.all::<Point>(cx);
15186        let ranges = selections
15187            .iter()
15188            .map(|s| {
15189                let mut range = s.display_range(&display_map).sorted();
15190                *range.start.column_mut() = 0;
15191                *range.end.column_mut() = display_map.line_len(range.end.row());
15192                let start = range.start.to_point(&display_map);
15193                let end = range.end.to_point(&display_map);
15194                start..end
15195            })
15196            .collect::<Vec<_>>();
15197
15198        self.unfold_ranges(&ranges, true, true, cx);
15199    }
15200
15201    pub fn unfold_at(
15202        &mut self,
15203        buffer_row: MultiBufferRow,
15204        _window: &mut Window,
15205        cx: &mut Context<Self>,
15206    ) {
15207        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15208
15209        let intersection_range = Point::new(buffer_row.0, 0)
15210            ..Point::new(
15211                buffer_row.0,
15212                display_map.buffer_snapshot.line_len(buffer_row),
15213            );
15214
15215        let autoscroll = self
15216            .selections
15217            .all::<Point>(cx)
15218            .iter()
15219            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15220
15221        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15222    }
15223
15224    pub fn unfold_all(
15225        &mut self,
15226        _: &actions::UnfoldAll,
15227        _window: &mut Window,
15228        cx: &mut Context<Self>,
15229    ) {
15230        if self.buffer.read(cx).is_singleton() {
15231            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15232            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15233        } else {
15234            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15235                editor
15236                    .update(cx, |editor, cx| {
15237                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15238                            editor.unfold_buffer(buffer_id, cx);
15239                        }
15240                    })
15241                    .ok();
15242            });
15243        }
15244    }
15245
15246    pub fn fold_selected_ranges(
15247        &mut self,
15248        _: &FoldSelectedRanges,
15249        window: &mut Window,
15250        cx: &mut Context<Self>,
15251    ) {
15252        let selections = self.selections.all_adjusted(cx);
15253        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15254        let ranges = selections
15255            .into_iter()
15256            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15257            .collect::<Vec<_>>();
15258        self.fold_creases(ranges, true, window, cx);
15259    }
15260
15261    pub fn fold_ranges<T: ToOffset + Clone>(
15262        &mut self,
15263        ranges: Vec<Range<T>>,
15264        auto_scroll: bool,
15265        window: &mut Window,
15266        cx: &mut Context<Self>,
15267    ) {
15268        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15269        let ranges = ranges
15270            .into_iter()
15271            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15272            .collect::<Vec<_>>();
15273        self.fold_creases(ranges, auto_scroll, window, cx);
15274    }
15275
15276    pub fn fold_creases<T: ToOffset + Clone>(
15277        &mut self,
15278        creases: Vec<Crease<T>>,
15279        auto_scroll: bool,
15280        _window: &mut Window,
15281        cx: &mut Context<Self>,
15282    ) {
15283        if creases.is_empty() {
15284            return;
15285        }
15286
15287        let mut buffers_affected = HashSet::default();
15288        let multi_buffer = self.buffer().read(cx);
15289        for crease in &creases {
15290            if let Some((_, buffer, _)) =
15291                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15292            {
15293                buffers_affected.insert(buffer.read(cx).remote_id());
15294            };
15295        }
15296
15297        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15298
15299        if auto_scroll {
15300            self.request_autoscroll(Autoscroll::fit(), cx);
15301        }
15302
15303        cx.notify();
15304
15305        self.scrollbar_marker_state.dirty = true;
15306        self.folds_did_change(cx);
15307    }
15308
15309    /// Removes any folds whose ranges intersect any of the given ranges.
15310    pub fn unfold_ranges<T: ToOffset + Clone>(
15311        &mut self,
15312        ranges: &[Range<T>],
15313        inclusive: bool,
15314        auto_scroll: bool,
15315        cx: &mut Context<Self>,
15316    ) {
15317        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15318            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15319        });
15320        self.folds_did_change(cx);
15321    }
15322
15323    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15324        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15325            return;
15326        }
15327        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15328        self.display_map.update(cx, |display_map, cx| {
15329            display_map.fold_buffers([buffer_id], cx)
15330        });
15331        cx.emit(EditorEvent::BufferFoldToggled {
15332            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15333            folded: true,
15334        });
15335        cx.notify();
15336    }
15337
15338    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15339        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15340            return;
15341        }
15342        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15343        self.display_map.update(cx, |display_map, cx| {
15344            display_map.unfold_buffers([buffer_id], cx);
15345        });
15346        cx.emit(EditorEvent::BufferFoldToggled {
15347            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15348            folded: false,
15349        });
15350        cx.notify();
15351    }
15352
15353    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15354        self.display_map.read(cx).is_buffer_folded(buffer)
15355    }
15356
15357    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15358        self.display_map.read(cx).folded_buffers()
15359    }
15360
15361    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15362        self.display_map.update(cx, |display_map, cx| {
15363            display_map.disable_header_for_buffer(buffer_id, cx);
15364        });
15365        cx.notify();
15366    }
15367
15368    /// Removes any folds with the given ranges.
15369    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15370        &mut self,
15371        ranges: &[Range<T>],
15372        type_id: TypeId,
15373        auto_scroll: bool,
15374        cx: &mut Context<Self>,
15375    ) {
15376        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15377            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15378        });
15379        self.folds_did_change(cx);
15380    }
15381
15382    fn remove_folds_with<T: ToOffset + Clone>(
15383        &mut self,
15384        ranges: &[Range<T>],
15385        auto_scroll: bool,
15386        cx: &mut Context<Self>,
15387        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15388    ) {
15389        if ranges.is_empty() {
15390            return;
15391        }
15392
15393        let mut buffers_affected = HashSet::default();
15394        let multi_buffer = self.buffer().read(cx);
15395        for range in ranges {
15396            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15397                buffers_affected.insert(buffer.read(cx).remote_id());
15398            };
15399        }
15400
15401        self.display_map.update(cx, update);
15402
15403        if auto_scroll {
15404            self.request_autoscroll(Autoscroll::fit(), cx);
15405        }
15406
15407        cx.notify();
15408        self.scrollbar_marker_state.dirty = true;
15409        self.active_indent_guides_state.dirty = true;
15410    }
15411
15412    pub fn update_fold_widths(
15413        &mut self,
15414        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15415        cx: &mut Context<Self>,
15416    ) -> bool {
15417        self.display_map
15418            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15419    }
15420
15421    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15422        self.display_map.read(cx).fold_placeholder.clone()
15423    }
15424
15425    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15426        self.buffer.update(cx, |buffer, cx| {
15427            buffer.set_all_diff_hunks_expanded(cx);
15428        });
15429    }
15430
15431    pub fn expand_all_diff_hunks(
15432        &mut self,
15433        _: &ExpandAllDiffHunks,
15434        _window: &mut Window,
15435        cx: &mut Context<Self>,
15436    ) {
15437        self.buffer.update(cx, |buffer, cx| {
15438            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15439        });
15440    }
15441
15442    pub fn toggle_selected_diff_hunks(
15443        &mut self,
15444        _: &ToggleSelectedDiffHunks,
15445        _window: &mut Window,
15446        cx: &mut Context<Self>,
15447    ) {
15448        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15449        self.toggle_diff_hunks_in_ranges(ranges, cx);
15450    }
15451
15452    pub fn diff_hunks_in_ranges<'a>(
15453        &'a self,
15454        ranges: &'a [Range<Anchor>],
15455        buffer: &'a MultiBufferSnapshot,
15456    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15457        ranges.iter().flat_map(move |range| {
15458            let end_excerpt_id = range.end.excerpt_id;
15459            let range = range.to_point(buffer);
15460            let mut peek_end = range.end;
15461            if range.end.row < buffer.max_row().0 {
15462                peek_end = Point::new(range.end.row + 1, 0);
15463            }
15464            buffer
15465                .diff_hunks_in_range(range.start..peek_end)
15466                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15467        })
15468    }
15469
15470    pub fn has_stageable_diff_hunks_in_ranges(
15471        &self,
15472        ranges: &[Range<Anchor>],
15473        snapshot: &MultiBufferSnapshot,
15474    ) -> bool {
15475        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15476        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15477    }
15478
15479    pub fn toggle_staged_selected_diff_hunks(
15480        &mut self,
15481        _: &::git::ToggleStaged,
15482        _: &mut Window,
15483        cx: &mut Context<Self>,
15484    ) {
15485        let snapshot = self.buffer.read(cx).snapshot(cx);
15486        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15487        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15488        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15489    }
15490
15491    pub fn set_render_diff_hunk_controls(
15492        &mut self,
15493        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15494        cx: &mut Context<Self>,
15495    ) {
15496        self.render_diff_hunk_controls = render_diff_hunk_controls;
15497        cx.notify();
15498    }
15499
15500    pub fn stage_and_next(
15501        &mut self,
15502        _: &::git::StageAndNext,
15503        window: &mut Window,
15504        cx: &mut Context<Self>,
15505    ) {
15506        self.do_stage_or_unstage_and_next(true, window, cx);
15507    }
15508
15509    pub fn unstage_and_next(
15510        &mut self,
15511        _: &::git::UnstageAndNext,
15512        window: &mut Window,
15513        cx: &mut Context<Self>,
15514    ) {
15515        self.do_stage_or_unstage_and_next(false, window, cx);
15516    }
15517
15518    pub fn stage_or_unstage_diff_hunks(
15519        &mut self,
15520        stage: bool,
15521        ranges: Vec<Range<Anchor>>,
15522        cx: &mut Context<Self>,
15523    ) {
15524        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15525        cx.spawn(async move |this, cx| {
15526            task.await?;
15527            this.update(cx, |this, cx| {
15528                let snapshot = this.buffer.read(cx).snapshot(cx);
15529                let chunk_by = this
15530                    .diff_hunks_in_ranges(&ranges, &snapshot)
15531                    .chunk_by(|hunk| hunk.buffer_id);
15532                for (buffer_id, hunks) in &chunk_by {
15533                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15534                }
15535            })
15536        })
15537        .detach_and_log_err(cx);
15538    }
15539
15540    fn save_buffers_for_ranges_if_needed(
15541        &mut self,
15542        ranges: &[Range<Anchor>],
15543        cx: &mut Context<Editor>,
15544    ) -> Task<Result<()>> {
15545        let multibuffer = self.buffer.read(cx);
15546        let snapshot = multibuffer.read(cx);
15547        let buffer_ids: HashSet<_> = ranges
15548            .iter()
15549            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15550            .collect();
15551        drop(snapshot);
15552
15553        let mut buffers = HashSet::default();
15554        for buffer_id in buffer_ids {
15555            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15556                let buffer = buffer_entity.read(cx);
15557                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15558                {
15559                    buffers.insert(buffer_entity);
15560                }
15561            }
15562        }
15563
15564        if let Some(project) = &self.project {
15565            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15566        } else {
15567            Task::ready(Ok(()))
15568        }
15569    }
15570
15571    fn do_stage_or_unstage_and_next(
15572        &mut self,
15573        stage: bool,
15574        window: &mut Window,
15575        cx: &mut Context<Self>,
15576    ) {
15577        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15578
15579        if ranges.iter().any(|range| range.start != range.end) {
15580            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15581            return;
15582        }
15583
15584        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15585        let snapshot = self.snapshot(window, cx);
15586        let position = self.selections.newest::<Point>(cx).head();
15587        let mut row = snapshot
15588            .buffer_snapshot
15589            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15590            .find(|hunk| hunk.row_range.start.0 > position.row)
15591            .map(|hunk| hunk.row_range.start);
15592
15593        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15594        // Outside of the project diff editor, wrap around to the beginning.
15595        if !all_diff_hunks_expanded {
15596            row = row.or_else(|| {
15597                snapshot
15598                    .buffer_snapshot
15599                    .diff_hunks_in_range(Point::zero()..position)
15600                    .find(|hunk| hunk.row_range.end.0 < position.row)
15601                    .map(|hunk| hunk.row_range.start)
15602            });
15603        }
15604
15605        if let Some(row) = row {
15606            let destination = Point::new(row.0, 0);
15607            let autoscroll = Autoscroll::center();
15608
15609            self.unfold_ranges(&[destination..destination], false, false, cx);
15610            self.change_selections(Some(autoscroll), window, cx, |s| {
15611                s.select_ranges([destination..destination]);
15612            });
15613        }
15614    }
15615
15616    fn do_stage_or_unstage(
15617        &self,
15618        stage: bool,
15619        buffer_id: BufferId,
15620        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15621        cx: &mut App,
15622    ) -> Option<()> {
15623        let project = self.project.as_ref()?;
15624        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15625        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15626        let buffer_snapshot = buffer.read(cx).snapshot();
15627        let file_exists = buffer_snapshot
15628            .file()
15629            .is_some_and(|file| file.disk_state().exists());
15630        diff.update(cx, |diff, cx| {
15631            diff.stage_or_unstage_hunks(
15632                stage,
15633                &hunks
15634                    .map(|hunk| buffer_diff::DiffHunk {
15635                        buffer_range: hunk.buffer_range,
15636                        diff_base_byte_range: hunk.diff_base_byte_range,
15637                        secondary_status: hunk.secondary_status,
15638                        range: Point::zero()..Point::zero(), // unused
15639                    })
15640                    .collect::<Vec<_>>(),
15641                &buffer_snapshot,
15642                file_exists,
15643                cx,
15644            )
15645        });
15646        None
15647    }
15648
15649    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15650        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15651        self.buffer
15652            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15653    }
15654
15655    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15656        self.buffer.update(cx, |buffer, cx| {
15657            let ranges = vec![Anchor::min()..Anchor::max()];
15658            if !buffer.all_diff_hunks_expanded()
15659                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15660            {
15661                buffer.collapse_diff_hunks(ranges, cx);
15662                true
15663            } else {
15664                false
15665            }
15666        })
15667    }
15668
15669    fn toggle_diff_hunks_in_ranges(
15670        &mut self,
15671        ranges: Vec<Range<Anchor>>,
15672        cx: &mut Context<Editor>,
15673    ) {
15674        self.buffer.update(cx, |buffer, cx| {
15675            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15676            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15677        })
15678    }
15679
15680    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15681        self.buffer.update(cx, |buffer, cx| {
15682            let snapshot = buffer.snapshot(cx);
15683            let excerpt_id = range.end.excerpt_id;
15684            let point_range = range.to_point(&snapshot);
15685            let expand = !buffer.single_hunk_is_expanded(range, cx);
15686            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15687        })
15688    }
15689
15690    pub(crate) fn apply_all_diff_hunks(
15691        &mut self,
15692        _: &ApplyAllDiffHunks,
15693        window: &mut Window,
15694        cx: &mut Context<Self>,
15695    ) {
15696        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15697
15698        let buffers = self.buffer.read(cx).all_buffers();
15699        for branch_buffer in buffers {
15700            branch_buffer.update(cx, |branch_buffer, cx| {
15701                branch_buffer.merge_into_base(Vec::new(), cx);
15702            });
15703        }
15704
15705        if let Some(project) = self.project.clone() {
15706            self.save(true, project, window, cx).detach_and_log_err(cx);
15707        }
15708    }
15709
15710    pub(crate) fn apply_selected_diff_hunks(
15711        &mut self,
15712        _: &ApplyDiffHunk,
15713        window: &mut Window,
15714        cx: &mut Context<Self>,
15715    ) {
15716        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15717        let snapshot = self.snapshot(window, cx);
15718        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15719        let mut ranges_by_buffer = HashMap::default();
15720        self.transact(window, cx, |editor, _window, cx| {
15721            for hunk in hunks {
15722                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15723                    ranges_by_buffer
15724                        .entry(buffer.clone())
15725                        .or_insert_with(Vec::new)
15726                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15727                }
15728            }
15729
15730            for (buffer, ranges) in ranges_by_buffer {
15731                buffer.update(cx, |buffer, cx| {
15732                    buffer.merge_into_base(ranges, cx);
15733                });
15734            }
15735        });
15736
15737        if let Some(project) = self.project.clone() {
15738            self.save(true, project, window, cx).detach_and_log_err(cx);
15739        }
15740    }
15741
15742    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15743        if hovered != self.gutter_hovered {
15744            self.gutter_hovered = hovered;
15745            cx.notify();
15746        }
15747    }
15748
15749    pub fn insert_blocks(
15750        &mut self,
15751        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15752        autoscroll: Option<Autoscroll>,
15753        cx: &mut Context<Self>,
15754    ) -> Vec<CustomBlockId> {
15755        let blocks = self
15756            .display_map
15757            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15758        if let Some(autoscroll) = autoscroll {
15759            self.request_autoscroll(autoscroll, cx);
15760        }
15761        cx.notify();
15762        blocks
15763    }
15764
15765    pub fn resize_blocks(
15766        &mut self,
15767        heights: HashMap<CustomBlockId, u32>,
15768        autoscroll: Option<Autoscroll>,
15769        cx: &mut Context<Self>,
15770    ) {
15771        self.display_map
15772            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15773        if let Some(autoscroll) = autoscroll {
15774            self.request_autoscroll(autoscroll, cx);
15775        }
15776        cx.notify();
15777    }
15778
15779    pub fn replace_blocks(
15780        &mut self,
15781        renderers: HashMap<CustomBlockId, RenderBlock>,
15782        autoscroll: Option<Autoscroll>,
15783        cx: &mut Context<Self>,
15784    ) {
15785        self.display_map
15786            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15787        if let Some(autoscroll) = autoscroll {
15788            self.request_autoscroll(autoscroll, cx);
15789        }
15790        cx.notify();
15791    }
15792
15793    pub fn remove_blocks(
15794        &mut self,
15795        block_ids: HashSet<CustomBlockId>,
15796        autoscroll: Option<Autoscroll>,
15797        cx: &mut Context<Self>,
15798    ) {
15799        self.display_map.update(cx, |display_map, cx| {
15800            display_map.remove_blocks(block_ids, cx)
15801        });
15802        if let Some(autoscroll) = autoscroll {
15803            self.request_autoscroll(autoscroll, cx);
15804        }
15805        cx.notify();
15806    }
15807
15808    pub fn row_for_block(
15809        &self,
15810        block_id: CustomBlockId,
15811        cx: &mut Context<Self>,
15812    ) -> Option<DisplayRow> {
15813        self.display_map
15814            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15815    }
15816
15817    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15818        self.focused_block = Some(focused_block);
15819    }
15820
15821    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15822        self.focused_block.take()
15823    }
15824
15825    pub fn insert_creases(
15826        &mut self,
15827        creases: impl IntoIterator<Item = Crease<Anchor>>,
15828        cx: &mut Context<Self>,
15829    ) -> Vec<CreaseId> {
15830        self.display_map
15831            .update(cx, |map, cx| map.insert_creases(creases, cx))
15832    }
15833
15834    pub fn remove_creases(
15835        &mut self,
15836        ids: impl IntoIterator<Item = CreaseId>,
15837        cx: &mut Context<Self>,
15838    ) {
15839        self.display_map
15840            .update(cx, |map, cx| map.remove_creases(ids, cx));
15841    }
15842
15843    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15844        self.display_map
15845            .update(cx, |map, cx| map.snapshot(cx))
15846            .longest_row()
15847    }
15848
15849    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15850        self.display_map
15851            .update(cx, |map, cx| map.snapshot(cx))
15852            .max_point()
15853    }
15854
15855    pub fn text(&self, cx: &App) -> String {
15856        self.buffer.read(cx).read(cx).text()
15857    }
15858
15859    pub fn is_empty(&self, cx: &App) -> bool {
15860        self.buffer.read(cx).read(cx).is_empty()
15861    }
15862
15863    pub fn text_option(&self, cx: &App) -> Option<String> {
15864        let text = self.text(cx);
15865        let text = text.trim();
15866
15867        if text.is_empty() {
15868            return None;
15869        }
15870
15871        Some(text.to_string())
15872    }
15873
15874    pub fn set_text(
15875        &mut self,
15876        text: impl Into<Arc<str>>,
15877        window: &mut Window,
15878        cx: &mut Context<Self>,
15879    ) {
15880        self.transact(window, cx, |this, _, cx| {
15881            this.buffer
15882                .read(cx)
15883                .as_singleton()
15884                .expect("you can only call set_text on editors for singleton buffers")
15885                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15886        });
15887    }
15888
15889    pub fn display_text(&self, cx: &mut App) -> String {
15890        self.display_map
15891            .update(cx, |map, cx| map.snapshot(cx))
15892            .text()
15893    }
15894
15895    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15896        let mut wrap_guides = smallvec::smallvec![];
15897
15898        if self.show_wrap_guides == Some(false) {
15899            return wrap_guides;
15900        }
15901
15902        let settings = self.buffer.read(cx).language_settings(cx);
15903        if settings.show_wrap_guides {
15904            match self.soft_wrap_mode(cx) {
15905                SoftWrap::Column(soft_wrap) => {
15906                    wrap_guides.push((soft_wrap as usize, true));
15907                }
15908                SoftWrap::Bounded(soft_wrap) => {
15909                    wrap_guides.push((soft_wrap as usize, true));
15910                }
15911                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15912            }
15913            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15914        }
15915
15916        wrap_guides
15917    }
15918
15919    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15920        let settings = self.buffer.read(cx).language_settings(cx);
15921        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15922        match mode {
15923            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15924                SoftWrap::None
15925            }
15926            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15927            language_settings::SoftWrap::PreferredLineLength => {
15928                SoftWrap::Column(settings.preferred_line_length)
15929            }
15930            language_settings::SoftWrap::Bounded => {
15931                SoftWrap::Bounded(settings.preferred_line_length)
15932            }
15933        }
15934    }
15935
15936    pub fn set_soft_wrap_mode(
15937        &mut self,
15938        mode: language_settings::SoftWrap,
15939
15940        cx: &mut Context<Self>,
15941    ) {
15942        self.soft_wrap_mode_override = Some(mode);
15943        cx.notify();
15944    }
15945
15946    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15947        self.hard_wrap = hard_wrap;
15948        cx.notify();
15949    }
15950
15951    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15952        self.text_style_refinement = Some(style);
15953    }
15954
15955    /// called by the Element so we know what style we were most recently rendered with.
15956    pub(crate) fn set_style(
15957        &mut self,
15958        style: EditorStyle,
15959        window: &mut Window,
15960        cx: &mut Context<Self>,
15961    ) {
15962        let rem_size = window.rem_size();
15963        self.display_map.update(cx, |map, cx| {
15964            map.set_font(
15965                style.text.font(),
15966                style.text.font_size.to_pixels(rem_size),
15967                cx,
15968            )
15969        });
15970        self.style = Some(style);
15971    }
15972
15973    pub fn style(&self) -> Option<&EditorStyle> {
15974        self.style.as_ref()
15975    }
15976
15977    // Called by the element. This method is not designed to be called outside of the editor
15978    // element's layout code because it does not notify when rewrapping is computed synchronously.
15979    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15980        self.display_map
15981            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15982    }
15983
15984    pub fn set_soft_wrap(&mut self) {
15985        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15986    }
15987
15988    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15989        if self.soft_wrap_mode_override.is_some() {
15990            self.soft_wrap_mode_override.take();
15991        } else {
15992            let soft_wrap = match self.soft_wrap_mode(cx) {
15993                SoftWrap::GitDiff => return,
15994                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15995                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15996                    language_settings::SoftWrap::None
15997                }
15998            };
15999            self.soft_wrap_mode_override = Some(soft_wrap);
16000        }
16001        cx.notify();
16002    }
16003
16004    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16005        let Some(workspace) = self.workspace() else {
16006            return;
16007        };
16008        let fs = workspace.read(cx).app_state().fs.clone();
16009        let current_show = TabBarSettings::get_global(cx).show;
16010        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16011            setting.show = Some(!current_show);
16012        });
16013    }
16014
16015    pub fn toggle_indent_guides(
16016        &mut self,
16017        _: &ToggleIndentGuides,
16018        _: &mut Window,
16019        cx: &mut Context<Self>,
16020    ) {
16021        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16022            self.buffer
16023                .read(cx)
16024                .language_settings(cx)
16025                .indent_guides
16026                .enabled
16027        });
16028        self.show_indent_guides = Some(!currently_enabled);
16029        cx.notify();
16030    }
16031
16032    fn should_show_indent_guides(&self) -> Option<bool> {
16033        self.show_indent_guides
16034    }
16035
16036    pub fn toggle_line_numbers(
16037        &mut self,
16038        _: &ToggleLineNumbers,
16039        _: &mut Window,
16040        cx: &mut Context<Self>,
16041    ) {
16042        let mut editor_settings = EditorSettings::get_global(cx).clone();
16043        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16044        EditorSettings::override_global(editor_settings, cx);
16045    }
16046
16047    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16048        if let Some(show_line_numbers) = self.show_line_numbers {
16049            return show_line_numbers;
16050        }
16051        EditorSettings::get_global(cx).gutter.line_numbers
16052    }
16053
16054    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16055        self.use_relative_line_numbers
16056            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16057    }
16058
16059    pub fn toggle_relative_line_numbers(
16060        &mut self,
16061        _: &ToggleRelativeLineNumbers,
16062        _: &mut Window,
16063        cx: &mut Context<Self>,
16064    ) {
16065        let is_relative = self.should_use_relative_line_numbers(cx);
16066        self.set_relative_line_number(Some(!is_relative), cx)
16067    }
16068
16069    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16070        self.use_relative_line_numbers = is_relative;
16071        cx.notify();
16072    }
16073
16074    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16075        self.show_gutter = show_gutter;
16076        cx.notify();
16077    }
16078
16079    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16080        self.show_scrollbars = show_scrollbars;
16081        cx.notify();
16082    }
16083
16084    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16085        self.show_line_numbers = Some(show_line_numbers);
16086        cx.notify();
16087    }
16088
16089    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16090        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16091        cx.notify();
16092    }
16093
16094    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16095        self.show_code_actions = Some(show_code_actions);
16096        cx.notify();
16097    }
16098
16099    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16100        self.show_runnables = Some(show_runnables);
16101        cx.notify();
16102    }
16103
16104    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16105        self.show_breakpoints = Some(show_breakpoints);
16106        cx.notify();
16107    }
16108
16109    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16110        if self.display_map.read(cx).masked != masked {
16111            self.display_map.update(cx, |map, _| map.masked = masked);
16112        }
16113        cx.notify()
16114    }
16115
16116    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16117        self.show_wrap_guides = Some(show_wrap_guides);
16118        cx.notify();
16119    }
16120
16121    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16122        self.show_indent_guides = Some(show_indent_guides);
16123        cx.notify();
16124    }
16125
16126    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16127        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16128            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16129                if let Some(dir) = file.abs_path(cx).parent() {
16130                    return Some(dir.to_owned());
16131                }
16132            }
16133
16134            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16135                return Some(project_path.path.to_path_buf());
16136            }
16137        }
16138
16139        None
16140    }
16141
16142    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16143        self.active_excerpt(cx)?
16144            .1
16145            .read(cx)
16146            .file()
16147            .and_then(|f| f.as_local())
16148    }
16149
16150    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16151        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16152            let buffer = buffer.read(cx);
16153            if let Some(project_path) = buffer.project_path(cx) {
16154                let project = self.project.as_ref()?.read(cx);
16155                project.absolute_path(&project_path, cx)
16156            } else {
16157                buffer
16158                    .file()
16159                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16160            }
16161        })
16162    }
16163
16164    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16165        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16166            let project_path = buffer.read(cx).project_path(cx)?;
16167            let project = self.project.as_ref()?.read(cx);
16168            let entry = project.entry_for_path(&project_path, cx)?;
16169            let path = entry.path.to_path_buf();
16170            Some(path)
16171        })
16172    }
16173
16174    pub fn reveal_in_finder(
16175        &mut self,
16176        _: &RevealInFileManager,
16177        _window: &mut Window,
16178        cx: &mut Context<Self>,
16179    ) {
16180        if let Some(target) = self.target_file(cx) {
16181            cx.reveal_path(&target.abs_path(cx));
16182        }
16183    }
16184
16185    pub fn copy_path(
16186        &mut self,
16187        _: &zed_actions::workspace::CopyPath,
16188        _window: &mut Window,
16189        cx: &mut Context<Self>,
16190    ) {
16191        if let Some(path) = self.target_file_abs_path(cx) {
16192            if let Some(path) = path.to_str() {
16193                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16194            }
16195        }
16196    }
16197
16198    pub fn copy_relative_path(
16199        &mut self,
16200        _: &zed_actions::workspace::CopyRelativePath,
16201        _window: &mut Window,
16202        cx: &mut Context<Self>,
16203    ) {
16204        if let Some(path) = self.target_file_path(cx) {
16205            if let Some(path) = path.to_str() {
16206                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16207            }
16208        }
16209    }
16210
16211    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16212        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16213            buffer.read(cx).project_path(cx)
16214        } else {
16215            None
16216        }
16217    }
16218
16219    // Returns true if the editor handled a go-to-line request
16220    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16221        maybe!({
16222            let breakpoint_store = self.breakpoint_store.as_ref()?;
16223
16224            let Some((_, _, active_position)) =
16225                breakpoint_store.read(cx).active_position().cloned()
16226            else {
16227                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16228                return None;
16229            };
16230
16231            let snapshot = self
16232                .project
16233                .as_ref()?
16234                .read(cx)
16235                .buffer_for_id(active_position.buffer_id?, cx)?
16236                .read(cx)
16237                .snapshot();
16238
16239            let mut handled = false;
16240            for (id, ExcerptRange { context, .. }) in self
16241                .buffer
16242                .read(cx)
16243                .excerpts_for_buffer(active_position.buffer_id?, cx)
16244            {
16245                if context.start.cmp(&active_position, &snapshot).is_ge()
16246                    || context.end.cmp(&active_position, &snapshot).is_lt()
16247                {
16248                    continue;
16249                }
16250                let snapshot = self.buffer.read(cx).snapshot(cx);
16251                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16252
16253                handled = true;
16254                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16255                self.go_to_line::<DebugCurrentRowHighlight>(
16256                    multibuffer_anchor,
16257                    Some(cx.theme().colors().editor_debugger_active_line_background),
16258                    window,
16259                    cx,
16260                );
16261
16262                cx.notify();
16263            }
16264            handled.then_some(())
16265        })
16266        .is_some()
16267    }
16268
16269    pub fn copy_file_name_without_extension(
16270        &mut self,
16271        _: &CopyFileNameWithoutExtension,
16272        _: &mut Window,
16273        cx: &mut Context<Self>,
16274    ) {
16275        if let Some(file) = self.target_file(cx) {
16276            if let Some(file_stem) = file.path().file_stem() {
16277                if let Some(name) = file_stem.to_str() {
16278                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16279                }
16280            }
16281        }
16282    }
16283
16284    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16285        if let Some(file) = self.target_file(cx) {
16286            if let Some(file_name) = file.path().file_name() {
16287                if let Some(name) = file_name.to_str() {
16288                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16289                }
16290            }
16291        }
16292    }
16293
16294    pub fn toggle_git_blame(
16295        &mut self,
16296        _: &::git::Blame,
16297        window: &mut Window,
16298        cx: &mut Context<Self>,
16299    ) {
16300        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16301
16302        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16303            self.start_git_blame(true, window, cx);
16304        }
16305
16306        cx.notify();
16307    }
16308
16309    pub fn toggle_git_blame_inline(
16310        &mut self,
16311        _: &ToggleGitBlameInline,
16312        window: &mut Window,
16313        cx: &mut Context<Self>,
16314    ) {
16315        self.toggle_git_blame_inline_internal(true, window, cx);
16316        cx.notify();
16317    }
16318
16319    pub fn open_git_blame_commit(
16320        &mut self,
16321        _: &OpenGitBlameCommit,
16322        window: &mut Window,
16323        cx: &mut Context<Self>,
16324    ) {
16325        self.open_git_blame_commit_internal(window, cx);
16326    }
16327
16328    fn open_git_blame_commit_internal(
16329        &mut self,
16330        window: &mut Window,
16331        cx: &mut Context<Self>,
16332    ) -> Option<()> {
16333        let blame = self.blame.as_ref()?;
16334        let snapshot = self.snapshot(window, cx);
16335        let cursor = self.selections.newest::<Point>(cx).head();
16336        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16337        let blame_entry = blame
16338            .update(cx, |blame, cx| {
16339                blame
16340                    .blame_for_rows(
16341                        &[RowInfo {
16342                            buffer_id: Some(buffer.remote_id()),
16343                            buffer_row: Some(point.row),
16344                            ..Default::default()
16345                        }],
16346                        cx,
16347                    )
16348                    .next()
16349            })
16350            .flatten()?;
16351        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16352        let repo = blame.read(cx).repository(cx)?;
16353        let workspace = self.workspace()?.downgrade();
16354        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16355        None
16356    }
16357
16358    pub fn git_blame_inline_enabled(&self) -> bool {
16359        self.git_blame_inline_enabled
16360    }
16361
16362    pub fn toggle_selection_menu(
16363        &mut self,
16364        _: &ToggleSelectionMenu,
16365        _: &mut Window,
16366        cx: &mut Context<Self>,
16367    ) {
16368        self.show_selection_menu = self
16369            .show_selection_menu
16370            .map(|show_selections_menu| !show_selections_menu)
16371            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16372
16373        cx.notify();
16374    }
16375
16376    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16377        self.show_selection_menu
16378            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16379    }
16380
16381    fn start_git_blame(
16382        &mut self,
16383        user_triggered: bool,
16384        window: &mut Window,
16385        cx: &mut Context<Self>,
16386    ) {
16387        if let Some(project) = self.project.as_ref() {
16388            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16389                return;
16390            };
16391
16392            if buffer.read(cx).file().is_none() {
16393                return;
16394            }
16395
16396            let focused = self.focus_handle(cx).contains_focused(window, cx);
16397
16398            let project = project.clone();
16399            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16400            self.blame_subscription =
16401                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16402            self.blame = Some(blame);
16403        }
16404    }
16405
16406    fn toggle_git_blame_inline_internal(
16407        &mut self,
16408        user_triggered: bool,
16409        window: &mut Window,
16410        cx: &mut Context<Self>,
16411    ) {
16412        if self.git_blame_inline_enabled {
16413            self.git_blame_inline_enabled = false;
16414            self.show_git_blame_inline = false;
16415            self.show_git_blame_inline_delay_task.take();
16416        } else {
16417            self.git_blame_inline_enabled = true;
16418            self.start_git_blame_inline(user_triggered, window, cx);
16419        }
16420
16421        cx.notify();
16422    }
16423
16424    fn start_git_blame_inline(
16425        &mut self,
16426        user_triggered: bool,
16427        window: &mut Window,
16428        cx: &mut Context<Self>,
16429    ) {
16430        self.start_git_blame(user_triggered, window, cx);
16431
16432        if ProjectSettings::get_global(cx)
16433            .git
16434            .inline_blame_delay()
16435            .is_some()
16436        {
16437            self.start_inline_blame_timer(window, cx);
16438        } else {
16439            self.show_git_blame_inline = true
16440        }
16441    }
16442
16443    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16444        self.blame.as_ref()
16445    }
16446
16447    pub fn show_git_blame_gutter(&self) -> bool {
16448        self.show_git_blame_gutter
16449    }
16450
16451    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16452        self.show_git_blame_gutter && self.has_blame_entries(cx)
16453    }
16454
16455    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16456        self.show_git_blame_inline
16457            && (self.focus_handle.is_focused(window)
16458                || self
16459                    .git_blame_inline_tooltip
16460                    .as_ref()
16461                    .and_then(|t| t.upgrade())
16462                    .is_some())
16463            && !self.newest_selection_head_on_empty_line(cx)
16464            && self.has_blame_entries(cx)
16465    }
16466
16467    fn has_blame_entries(&self, cx: &App) -> bool {
16468        self.blame()
16469            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16470    }
16471
16472    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16473        let cursor_anchor = self.selections.newest_anchor().head();
16474
16475        let snapshot = self.buffer.read(cx).snapshot(cx);
16476        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16477
16478        snapshot.line_len(buffer_row) == 0
16479    }
16480
16481    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16482        let buffer_and_selection = maybe!({
16483            let selection = self.selections.newest::<Point>(cx);
16484            let selection_range = selection.range();
16485
16486            let multi_buffer = self.buffer().read(cx);
16487            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16488            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16489
16490            let (buffer, range, _) = if selection.reversed {
16491                buffer_ranges.first()
16492            } else {
16493                buffer_ranges.last()
16494            }?;
16495
16496            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16497                ..text::ToPoint::to_point(&range.end, &buffer).row;
16498            Some((
16499                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16500                selection,
16501            ))
16502        });
16503
16504        let Some((buffer, selection)) = buffer_and_selection else {
16505            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16506        };
16507
16508        let Some(project) = self.project.as_ref() else {
16509            return Task::ready(Err(anyhow!("editor does not have project")));
16510        };
16511
16512        project.update(cx, |project, cx| {
16513            project.get_permalink_to_line(&buffer, selection, cx)
16514        })
16515    }
16516
16517    pub fn copy_permalink_to_line(
16518        &mut self,
16519        _: &CopyPermalinkToLine,
16520        window: &mut Window,
16521        cx: &mut Context<Self>,
16522    ) {
16523        let permalink_task = self.get_permalink_to_line(cx);
16524        let workspace = self.workspace();
16525
16526        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16527            Ok(permalink) => {
16528                cx.update(|_, cx| {
16529                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16530                })
16531                .ok();
16532            }
16533            Err(err) => {
16534                let message = format!("Failed to copy permalink: {err}");
16535
16536                Err::<(), anyhow::Error>(err).log_err();
16537
16538                if let Some(workspace) = workspace {
16539                    workspace
16540                        .update_in(cx, |workspace, _, cx| {
16541                            struct CopyPermalinkToLine;
16542
16543                            workspace.show_toast(
16544                                Toast::new(
16545                                    NotificationId::unique::<CopyPermalinkToLine>(),
16546                                    message,
16547                                ),
16548                                cx,
16549                            )
16550                        })
16551                        .ok();
16552                }
16553            }
16554        })
16555        .detach();
16556    }
16557
16558    pub fn copy_file_location(
16559        &mut self,
16560        _: &CopyFileLocation,
16561        _: &mut Window,
16562        cx: &mut Context<Self>,
16563    ) {
16564        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16565        if let Some(file) = self.target_file(cx) {
16566            if let Some(path) = file.path().to_str() {
16567                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16568            }
16569        }
16570    }
16571
16572    pub fn open_permalink_to_line(
16573        &mut self,
16574        _: &OpenPermalinkToLine,
16575        window: &mut Window,
16576        cx: &mut Context<Self>,
16577    ) {
16578        let permalink_task = self.get_permalink_to_line(cx);
16579        let workspace = self.workspace();
16580
16581        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16582            Ok(permalink) => {
16583                cx.update(|_, cx| {
16584                    cx.open_url(permalink.as_ref());
16585                })
16586                .ok();
16587            }
16588            Err(err) => {
16589                let message = format!("Failed to open permalink: {err}");
16590
16591                Err::<(), anyhow::Error>(err).log_err();
16592
16593                if let Some(workspace) = workspace {
16594                    workspace
16595                        .update(cx, |workspace, cx| {
16596                            struct OpenPermalinkToLine;
16597
16598                            workspace.show_toast(
16599                                Toast::new(
16600                                    NotificationId::unique::<OpenPermalinkToLine>(),
16601                                    message,
16602                                ),
16603                                cx,
16604                            )
16605                        })
16606                        .ok();
16607                }
16608            }
16609        })
16610        .detach();
16611    }
16612
16613    pub fn insert_uuid_v4(
16614        &mut self,
16615        _: &InsertUuidV4,
16616        window: &mut Window,
16617        cx: &mut Context<Self>,
16618    ) {
16619        self.insert_uuid(UuidVersion::V4, window, cx);
16620    }
16621
16622    pub fn insert_uuid_v7(
16623        &mut self,
16624        _: &InsertUuidV7,
16625        window: &mut Window,
16626        cx: &mut Context<Self>,
16627    ) {
16628        self.insert_uuid(UuidVersion::V7, window, cx);
16629    }
16630
16631    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16632        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16633        self.transact(window, cx, |this, window, cx| {
16634            let edits = this
16635                .selections
16636                .all::<Point>(cx)
16637                .into_iter()
16638                .map(|selection| {
16639                    let uuid = match version {
16640                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16641                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16642                    };
16643
16644                    (selection.range(), uuid.to_string())
16645                });
16646            this.edit(edits, cx);
16647            this.refresh_inline_completion(true, false, window, cx);
16648        });
16649    }
16650
16651    pub fn open_selections_in_multibuffer(
16652        &mut self,
16653        _: &OpenSelectionsInMultibuffer,
16654        window: &mut Window,
16655        cx: &mut Context<Self>,
16656    ) {
16657        let multibuffer = self.buffer.read(cx);
16658
16659        let Some(buffer) = multibuffer.as_singleton() else {
16660            return;
16661        };
16662
16663        let Some(workspace) = self.workspace() else {
16664            return;
16665        };
16666
16667        let locations = self
16668            .selections
16669            .disjoint_anchors()
16670            .iter()
16671            .map(|range| Location {
16672                buffer: buffer.clone(),
16673                range: range.start.text_anchor..range.end.text_anchor,
16674            })
16675            .collect::<Vec<_>>();
16676
16677        let title = multibuffer.title(cx).to_string();
16678
16679        cx.spawn_in(window, async move |_, cx| {
16680            workspace.update_in(cx, |workspace, window, cx| {
16681                Self::open_locations_in_multibuffer(
16682                    workspace,
16683                    locations,
16684                    format!("Selections for '{title}'"),
16685                    false,
16686                    MultibufferSelectionMode::All,
16687                    window,
16688                    cx,
16689                );
16690            })
16691        })
16692        .detach();
16693    }
16694
16695    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16696    /// last highlight added will be used.
16697    ///
16698    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16699    pub fn highlight_rows<T: 'static>(
16700        &mut self,
16701        range: Range<Anchor>,
16702        color: Hsla,
16703        should_autoscroll: bool,
16704        cx: &mut Context<Self>,
16705    ) {
16706        let snapshot = self.buffer().read(cx).snapshot(cx);
16707        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16708        let ix = row_highlights.binary_search_by(|highlight| {
16709            Ordering::Equal
16710                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16711                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16712        });
16713
16714        if let Err(mut ix) = ix {
16715            let index = post_inc(&mut self.highlight_order);
16716
16717            // If this range intersects with the preceding highlight, then merge it with
16718            // the preceding highlight. Otherwise insert a new highlight.
16719            let mut merged = false;
16720            if ix > 0 {
16721                let prev_highlight = &mut row_highlights[ix - 1];
16722                if prev_highlight
16723                    .range
16724                    .end
16725                    .cmp(&range.start, &snapshot)
16726                    .is_ge()
16727                {
16728                    ix -= 1;
16729                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16730                        prev_highlight.range.end = range.end;
16731                    }
16732                    merged = true;
16733                    prev_highlight.index = index;
16734                    prev_highlight.color = color;
16735                    prev_highlight.should_autoscroll = should_autoscroll;
16736                }
16737            }
16738
16739            if !merged {
16740                row_highlights.insert(
16741                    ix,
16742                    RowHighlight {
16743                        range: range.clone(),
16744                        index,
16745                        color,
16746                        should_autoscroll,
16747                    },
16748                );
16749            }
16750
16751            // If any of the following highlights intersect with this one, merge them.
16752            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16753                let highlight = &row_highlights[ix];
16754                if next_highlight
16755                    .range
16756                    .start
16757                    .cmp(&highlight.range.end, &snapshot)
16758                    .is_le()
16759                {
16760                    if next_highlight
16761                        .range
16762                        .end
16763                        .cmp(&highlight.range.end, &snapshot)
16764                        .is_gt()
16765                    {
16766                        row_highlights[ix].range.end = next_highlight.range.end;
16767                    }
16768                    row_highlights.remove(ix + 1);
16769                } else {
16770                    break;
16771                }
16772            }
16773        }
16774    }
16775
16776    /// Remove any highlighted row ranges of the given type that intersect the
16777    /// given ranges.
16778    pub fn remove_highlighted_rows<T: 'static>(
16779        &mut self,
16780        ranges_to_remove: Vec<Range<Anchor>>,
16781        cx: &mut Context<Self>,
16782    ) {
16783        let snapshot = self.buffer().read(cx).snapshot(cx);
16784        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16785        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16786        row_highlights.retain(|highlight| {
16787            while let Some(range_to_remove) = ranges_to_remove.peek() {
16788                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16789                    Ordering::Less | Ordering::Equal => {
16790                        ranges_to_remove.next();
16791                    }
16792                    Ordering::Greater => {
16793                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16794                            Ordering::Less | Ordering::Equal => {
16795                                return false;
16796                            }
16797                            Ordering::Greater => break,
16798                        }
16799                    }
16800                }
16801            }
16802
16803            true
16804        })
16805    }
16806
16807    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16808    pub fn clear_row_highlights<T: 'static>(&mut self) {
16809        self.highlighted_rows.remove(&TypeId::of::<T>());
16810    }
16811
16812    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16813    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16814        self.highlighted_rows
16815            .get(&TypeId::of::<T>())
16816            .map_or(&[] as &[_], |vec| vec.as_slice())
16817            .iter()
16818            .map(|highlight| (highlight.range.clone(), highlight.color))
16819    }
16820
16821    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16822    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16823    /// Allows to ignore certain kinds of highlights.
16824    pub fn highlighted_display_rows(
16825        &self,
16826        window: &mut Window,
16827        cx: &mut App,
16828    ) -> BTreeMap<DisplayRow, LineHighlight> {
16829        let snapshot = self.snapshot(window, cx);
16830        let mut used_highlight_orders = HashMap::default();
16831        self.highlighted_rows
16832            .iter()
16833            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16834            .fold(
16835                BTreeMap::<DisplayRow, LineHighlight>::new(),
16836                |mut unique_rows, highlight| {
16837                    let start = highlight.range.start.to_display_point(&snapshot);
16838                    let end = highlight.range.end.to_display_point(&snapshot);
16839                    let start_row = start.row().0;
16840                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16841                        && end.column() == 0
16842                    {
16843                        end.row().0.saturating_sub(1)
16844                    } else {
16845                        end.row().0
16846                    };
16847                    for row in start_row..=end_row {
16848                        let used_index =
16849                            used_highlight_orders.entry(row).or_insert(highlight.index);
16850                        if highlight.index >= *used_index {
16851                            *used_index = highlight.index;
16852                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16853                        }
16854                    }
16855                    unique_rows
16856                },
16857            )
16858    }
16859
16860    pub fn highlighted_display_row_for_autoscroll(
16861        &self,
16862        snapshot: &DisplaySnapshot,
16863    ) -> Option<DisplayRow> {
16864        self.highlighted_rows
16865            .values()
16866            .flat_map(|highlighted_rows| highlighted_rows.iter())
16867            .filter_map(|highlight| {
16868                if highlight.should_autoscroll {
16869                    Some(highlight.range.start.to_display_point(snapshot).row())
16870                } else {
16871                    None
16872                }
16873            })
16874            .min()
16875    }
16876
16877    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16878        self.highlight_background::<SearchWithinRange>(
16879            ranges,
16880            |colors| colors.editor_document_highlight_read_background,
16881            cx,
16882        )
16883    }
16884
16885    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16886        self.breadcrumb_header = Some(new_header);
16887    }
16888
16889    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16890        self.clear_background_highlights::<SearchWithinRange>(cx);
16891    }
16892
16893    pub fn highlight_background<T: 'static>(
16894        &mut self,
16895        ranges: &[Range<Anchor>],
16896        color_fetcher: fn(&ThemeColors) -> Hsla,
16897        cx: &mut Context<Self>,
16898    ) {
16899        self.background_highlights
16900            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16901        self.scrollbar_marker_state.dirty = true;
16902        cx.notify();
16903    }
16904
16905    pub fn clear_background_highlights<T: 'static>(
16906        &mut self,
16907        cx: &mut Context<Self>,
16908    ) -> Option<BackgroundHighlight> {
16909        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16910        if !text_highlights.1.is_empty() {
16911            self.scrollbar_marker_state.dirty = true;
16912            cx.notify();
16913        }
16914        Some(text_highlights)
16915    }
16916
16917    pub fn highlight_gutter<T: 'static>(
16918        &mut self,
16919        ranges: &[Range<Anchor>],
16920        color_fetcher: fn(&App) -> Hsla,
16921        cx: &mut Context<Self>,
16922    ) {
16923        self.gutter_highlights
16924            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16925        cx.notify();
16926    }
16927
16928    pub fn clear_gutter_highlights<T: 'static>(
16929        &mut self,
16930        cx: &mut Context<Self>,
16931    ) -> Option<GutterHighlight> {
16932        cx.notify();
16933        self.gutter_highlights.remove(&TypeId::of::<T>())
16934    }
16935
16936    #[cfg(feature = "test-support")]
16937    pub fn all_text_background_highlights(
16938        &self,
16939        window: &mut Window,
16940        cx: &mut Context<Self>,
16941    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16942        let snapshot = self.snapshot(window, cx);
16943        let buffer = &snapshot.buffer_snapshot;
16944        let start = buffer.anchor_before(0);
16945        let end = buffer.anchor_after(buffer.len());
16946        let theme = cx.theme().colors();
16947        self.background_highlights_in_range(start..end, &snapshot, theme)
16948    }
16949
16950    #[cfg(feature = "test-support")]
16951    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16952        let snapshot = self.buffer().read(cx).snapshot(cx);
16953
16954        let highlights = self
16955            .background_highlights
16956            .get(&TypeId::of::<items::BufferSearchHighlights>());
16957
16958        if let Some((_color, ranges)) = highlights {
16959            ranges
16960                .iter()
16961                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16962                .collect_vec()
16963        } else {
16964            vec![]
16965        }
16966    }
16967
16968    fn document_highlights_for_position<'a>(
16969        &'a self,
16970        position: Anchor,
16971        buffer: &'a MultiBufferSnapshot,
16972    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16973        let read_highlights = self
16974            .background_highlights
16975            .get(&TypeId::of::<DocumentHighlightRead>())
16976            .map(|h| &h.1);
16977        let write_highlights = self
16978            .background_highlights
16979            .get(&TypeId::of::<DocumentHighlightWrite>())
16980            .map(|h| &h.1);
16981        let left_position = position.bias_left(buffer);
16982        let right_position = position.bias_right(buffer);
16983        read_highlights
16984            .into_iter()
16985            .chain(write_highlights)
16986            .flat_map(move |ranges| {
16987                let start_ix = match ranges.binary_search_by(|probe| {
16988                    let cmp = probe.end.cmp(&left_position, buffer);
16989                    if cmp.is_ge() {
16990                        Ordering::Greater
16991                    } else {
16992                        Ordering::Less
16993                    }
16994                }) {
16995                    Ok(i) | Err(i) => i,
16996                };
16997
16998                ranges[start_ix..]
16999                    .iter()
17000                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17001            })
17002    }
17003
17004    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17005        self.background_highlights
17006            .get(&TypeId::of::<T>())
17007            .map_or(false, |(_, highlights)| !highlights.is_empty())
17008    }
17009
17010    pub fn background_highlights_in_range(
17011        &self,
17012        search_range: Range<Anchor>,
17013        display_snapshot: &DisplaySnapshot,
17014        theme: &ThemeColors,
17015    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17016        let mut results = Vec::new();
17017        for (color_fetcher, ranges) in self.background_highlights.values() {
17018            let color = color_fetcher(theme);
17019            let start_ix = match ranges.binary_search_by(|probe| {
17020                let cmp = probe
17021                    .end
17022                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17023                if cmp.is_gt() {
17024                    Ordering::Greater
17025                } else {
17026                    Ordering::Less
17027                }
17028            }) {
17029                Ok(i) | Err(i) => i,
17030            };
17031            for range in &ranges[start_ix..] {
17032                if range
17033                    .start
17034                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17035                    .is_ge()
17036                {
17037                    break;
17038                }
17039
17040                let start = range.start.to_display_point(display_snapshot);
17041                let end = range.end.to_display_point(display_snapshot);
17042                results.push((start..end, color))
17043            }
17044        }
17045        results
17046    }
17047
17048    pub fn background_highlight_row_ranges<T: 'static>(
17049        &self,
17050        search_range: Range<Anchor>,
17051        display_snapshot: &DisplaySnapshot,
17052        count: usize,
17053    ) -> Vec<RangeInclusive<DisplayPoint>> {
17054        let mut results = Vec::new();
17055        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17056            return vec![];
17057        };
17058
17059        let start_ix = match ranges.binary_search_by(|probe| {
17060            let cmp = probe
17061                .end
17062                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17063            if cmp.is_gt() {
17064                Ordering::Greater
17065            } else {
17066                Ordering::Less
17067            }
17068        }) {
17069            Ok(i) | Err(i) => i,
17070        };
17071        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17072            if let (Some(start_display), Some(end_display)) = (start, end) {
17073                results.push(
17074                    start_display.to_display_point(display_snapshot)
17075                        ..=end_display.to_display_point(display_snapshot),
17076                );
17077            }
17078        };
17079        let mut start_row: Option<Point> = None;
17080        let mut end_row: Option<Point> = None;
17081        if ranges.len() > count {
17082            return Vec::new();
17083        }
17084        for range in &ranges[start_ix..] {
17085            if range
17086                .start
17087                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17088                .is_ge()
17089            {
17090                break;
17091            }
17092            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17093            if let Some(current_row) = &end_row {
17094                if end.row == current_row.row {
17095                    continue;
17096                }
17097            }
17098            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17099            if start_row.is_none() {
17100                assert_eq!(end_row, None);
17101                start_row = Some(start);
17102                end_row = Some(end);
17103                continue;
17104            }
17105            if let Some(current_end) = end_row.as_mut() {
17106                if start.row > current_end.row + 1 {
17107                    push_region(start_row, end_row);
17108                    start_row = Some(start);
17109                    end_row = Some(end);
17110                } else {
17111                    // Merge two hunks.
17112                    *current_end = end;
17113                }
17114            } else {
17115                unreachable!();
17116            }
17117        }
17118        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17119        push_region(start_row, end_row);
17120        results
17121    }
17122
17123    pub fn gutter_highlights_in_range(
17124        &self,
17125        search_range: Range<Anchor>,
17126        display_snapshot: &DisplaySnapshot,
17127        cx: &App,
17128    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17129        let mut results = Vec::new();
17130        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17131            let color = color_fetcher(cx);
17132            let start_ix = match ranges.binary_search_by(|probe| {
17133                let cmp = probe
17134                    .end
17135                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17136                if cmp.is_gt() {
17137                    Ordering::Greater
17138                } else {
17139                    Ordering::Less
17140                }
17141            }) {
17142                Ok(i) | Err(i) => i,
17143            };
17144            for range in &ranges[start_ix..] {
17145                if range
17146                    .start
17147                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17148                    .is_ge()
17149                {
17150                    break;
17151                }
17152
17153                let start = range.start.to_display_point(display_snapshot);
17154                let end = range.end.to_display_point(display_snapshot);
17155                results.push((start..end, color))
17156            }
17157        }
17158        results
17159    }
17160
17161    /// Get the text ranges corresponding to the redaction query
17162    pub fn redacted_ranges(
17163        &self,
17164        search_range: Range<Anchor>,
17165        display_snapshot: &DisplaySnapshot,
17166        cx: &App,
17167    ) -> Vec<Range<DisplayPoint>> {
17168        display_snapshot
17169            .buffer_snapshot
17170            .redacted_ranges(search_range, |file| {
17171                if let Some(file) = file {
17172                    file.is_private()
17173                        && EditorSettings::get(
17174                            Some(SettingsLocation {
17175                                worktree_id: file.worktree_id(cx),
17176                                path: file.path().as_ref(),
17177                            }),
17178                            cx,
17179                        )
17180                        .redact_private_values
17181                } else {
17182                    false
17183                }
17184            })
17185            .map(|range| {
17186                range.start.to_display_point(display_snapshot)
17187                    ..range.end.to_display_point(display_snapshot)
17188            })
17189            .collect()
17190    }
17191
17192    pub fn highlight_text<T: 'static>(
17193        &mut self,
17194        ranges: Vec<Range<Anchor>>,
17195        style: HighlightStyle,
17196        cx: &mut Context<Self>,
17197    ) {
17198        self.display_map.update(cx, |map, _| {
17199            map.highlight_text(TypeId::of::<T>(), ranges, style)
17200        });
17201        cx.notify();
17202    }
17203
17204    pub(crate) fn highlight_inlays<T: 'static>(
17205        &mut self,
17206        highlights: Vec<InlayHighlight>,
17207        style: HighlightStyle,
17208        cx: &mut Context<Self>,
17209    ) {
17210        self.display_map.update(cx, |map, _| {
17211            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17212        });
17213        cx.notify();
17214    }
17215
17216    pub fn text_highlights<'a, T: 'static>(
17217        &'a self,
17218        cx: &'a App,
17219    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17220        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17221    }
17222
17223    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17224        let cleared = self
17225            .display_map
17226            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17227        if cleared {
17228            cx.notify();
17229        }
17230    }
17231
17232    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17233        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17234            && self.focus_handle.is_focused(window)
17235    }
17236
17237    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17238        self.show_cursor_when_unfocused = is_enabled;
17239        cx.notify();
17240    }
17241
17242    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17243        cx.notify();
17244    }
17245
17246    fn on_buffer_event(
17247        &mut self,
17248        multibuffer: &Entity<MultiBuffer>,
17249        event: &multi_buffer::Event,
17250        window: &mut Window,
17251        cx: &mut Context<Self>,
17252    ) {
17253        match event {
17254            multi_buffer::Event::Edited {
17255                singleton_buffer_edited,
17256                edited_buffer: buffer_edited,
17257            } => {
17258                self.scrollbar_marker_state.dirty = true;
17259                self.active_indent_guides_state.dirty = true;
17260                self.refresh_active_diagnostics(cx);
17261                self.refresh_code_actions(window, cx);
17262                if self.has_active_inline_completion() {
17263                    self.update_visible_inline_completion(window, cx);
17264                }
17265                if let Some(buffer) = buffer_edited {
17266                    let buffer_id = buffer.read(cx).remote_id();
17267                    if !self.registered_buffers.contains_key(&buffer_id) {
17268                        if let Some(project) = self.project.as_ref() {
17269                            project.update(cx, |project, cx| {
17270                                self.registered_buffers.insert(
17271                                    buffer_id,
17272                                    project.register_buffer_with_language_servers(&buffer, cx),
17273                                );
17274                            })
17275                        }
17276                    }
17277                }
17278                cx.emit(EditorEvent::BufferEdited);
17279                cx.emit(SearchEvent::MatchesInvalidated);
17280                if *singleton_buffer_edited {
17281                    if let Some(project) = &self.project {
17282                        #[allow(clippy::mutable_key_type)]
17283                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17284                            multibuffer
17285                                .all_buffers()
17286                                .into_iter()
17287                                .filter_map(|buffer| {
17288                                    buffer.update(cx, |buffer, cx| {
17289                                        let language = buffer.language()?;
17290                                        let should_discard = project.update(cx, |project, cx| {
17291                                            project.is_local()
17292                                                && !project.has_language_servers_for(buffer, cx)
17293                                        });
17294                                        should_discard.not().then_some(language.clone())
17295                                    })
17296                                })
17297                                .collect::<HashSet<_>>()
17298                        });
17299                        if !languages_affected.is_empty() {
17300                            self.refresh_inlay_hints(
17301                                InlayHintRefreshReason::BufferEdited(languages_affected),
17302                                cx,
17303                            );
17304                        }
17305                    }
17306                }
17307
17308                let Some(project) = &self.project else { return };
17309                let (telemetry, is_via_ssh) = {
17310                    let project = project.read(cx);
17311                    let telemetry = project.client().telemetry().clone();
17312                    let is_via_ssh = project.is_via_ssh();
17313                    (telemetry, is_via_ssh)
17314                };
17315                refresh_linked_ranges(self, window, cx);
17316                telemetry.log_edit_event("editor", is_via_ssh);
17317            }
17318            multi_buffer::Event::ExcerptsAdded {
17319                buffer,
17320                predecessor,
17321                excerpts,
17322            } => {
17323                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17324                let buffer_id = buffer.read(cx).remote_id();
17325                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17326                    if let Some(project) = &self.project {
17327                        get_uncommitted_diff_for_buffer(
17328                            project,
17329                            [buffer.clone()],
17330                            self.buffer.clone(),
17331                            cx,
17332                        )
17333                        .detach();
17334                    }
17335                }
17336                cx.emit(EditorEvent::ExcerptsAdded {
17337                    buffer: buffer.clone(),
17338                    predecessor: *predecessor,
17339                    excerpts: excerpts.clone(),
17340                });
17341                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17342            }
17343            multi_buffer::Event::ExcerptsRemoved { ids } => {
17344                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17345                let buffer = self.buffer.read(cx);
17346                self.registered_buffers
17347                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17348                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17349                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17350            }
17351            multi_buffer::Event::ExcerptsEdited {
17352                excerpt_ids,
17353                buffer_ids,
17354            } => {
17355                self.display_map.update(cx, |map, cx| {
17356                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17357                });
17358                cx.emit(EditorEvent::ExcerptsEdited {
17359                    ids: excerpt_ids.clone(),
17360                })
17361            }
17362            multi_buffer::Event::ExcerptsExpanded { ids } => {
17363                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17364                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17365            }
17366            multi_buffer::Event::Reparsed(buffer_id) => {
17367                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17368                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17369
17370                cx.emit(EditorEvent::Reparsed(*buffer_id));
17371            }
17372            multi_buffer::Event::DiffHunksToggled => {
17373                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17374            }
17375            multi_buffer::Event::LanguageChanged(buffer_id) => {
17376                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17377                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17378                cx.emit(EditorEvent::Reparsed(*buffer_id));
17379                cx.notify();
17380            }
17381            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17382            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17383            multi_buffer::Event::FileHandleChanged
17384            | multi_buffer::Event::Reloaded
17385            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17386            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17387            multi_buffer::Event::DiagnosticsUpdated => {
17388                self.refresh_active_diagnostics(cx);
17389                self.refresh_inline_diagnostics(true, window, cx);
17390                self.scrollbar_marker_state.dirty = true;
17391                cx.notify();
17392            }
17393            _ => {}
17394        };
17395    }
17396
17397    fn on_display_map_changed(
17398        &mut self,
17399        _: Entity<DisplayMap>,
17400        _: &mut Window,
17401        cx: &mut Context<Self>,
17402    ) {
17403        cx.notify();
17404    }
17405
17406    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17407        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17408        self.update_edit_prediction_settings(cx);
17409        self.refresh_inline_completion(true, false, window, cx);
17410        self.refresh_inlay_hints(
17411            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17412                self.selections.newest_anchor().head(),
17413                &self.buffer.read(cx).snapshot(cx),
17414                cx,
17415            )),
17416            cx,
17417        );
17418
17419        let old_cursor_shape = self.cursor_shape;
17420
17421        {
17422            let editor_settings = EditorSettings::get_global(cx);
17423            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17424            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17425            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17426            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17427        }
17428
17429        if old_cursor_shape != self.cursor_shape {
17430            cx.emit(EditorEvent::CursorShapeChanged);
17431        }
17432
17433        let project_settings = ProjectSettings::get_global(cx);
17434        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17435
17436        if self.mode.is_full() {
17437            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17438            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17439            if self.show_inline_diagnostics != show_inline_diagnostics {
17440                self.show_inline_diagnostics = show_inline_diagnostics;
17441                self.refresh_inline_diagnostics(false, window, cx);
17442            }
17443
17444            if self.git_blame_inline_enabled != inline_blame_enabled {
17445                self.toggle_git_blame_inline_internal(false, window, cx);
17446            }
17447        }
17448
17449        cx.notify();
17450    }
17451
17452    pub fn set_searchable(&mut self, searchable: bool) {
17453        self.searchable = searchable;
17454    }
17455
17456    pub fn searchable(&self) -> bool {
17457        self.searchable
17458    }
17459
17460    fn open_proposed_changes_editor(
17461        &mut self,
17462        _: &OpenProposedChangesEditor,
17463        window: &mut Window,
17464        cx: &mut Context<Self>,
17465    ) {
17466        let Some(workspace) = self.workspace() else {
17467            cx.propagate();
17468            return;
17469        };
17470
17471        let selections = self.selections.all::<usize>(cx);
17472        let multi_buffer = self.buffer.read(cx);
17473        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17474        let mut new_selections_by_buffer = HashMap::default();
17475        for selection in selections {
17476            for (buffer, range, _) in
17477                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17478            {
17479                let mut range = range.to_point(buffer);
17480                range.start.column = 0;
17481                range.end.column = buffer.line_len(range.end.row);
17482                new_selections_by_buffer
17483                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17484                    .or_insert(Vec::new())
17485                    .push(range)
17486            }
17487        }
17488
17489        let proposed_changes_buffers = new_selections_by_buffer
17490            .into_iter()
17491            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17492            .collect::<Vec<_>>();
17493        let proposed_changes_editor = cx.new(|cx| {
17494            ProposedChangesEditor::new(
17495                "Proposed changes",
17496                proposed_changes_buffers,
17497                self.project.clone(),
17498                window,
17499                cx,
17500            )
17501        });
17502
17503        window.defer(cx, move |window, cx| {
17504            workspace.update(cx, |workspace, cx| {
17505                workspace.active_pane().update(cx, |pane, cx| {
17506                    pane.add_item(
17507                        Box::new(proposed_changes_editor),
17508                        true,
17509                        true,
17510                        None,
17511                        window,
17512                        cx,
17513                    );
17514                });
17515            });
17516        });
17517    }
17518
17519    pub fn open_excerpts_in_split(
17520        &mut self,
17521        _: &OpenExcerptsSplit,
17522        window: &mut Window,
17523        cx: &mut Context<Self>,
17524    ) {
17525        self.open_excerpts_common(None, true, window, cx)
17526    }
17527
17528    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17529        self.open_excerpts_common(None, false, window, cx)
17530    }
17531
17532    fn open_excerpts_common(
17533        &mut self,
17534        jump_data: Option<JumpData>,
17535        split: bool,
17536        window: &mut Window,
17537        cx: &mut Context<Self>,
17538    ) {
17539        let Some(workspace) = self.workspace() else {
17540            cx.propagate();
17541            return;
17542        };
17543
17544        if self.buffer.read(cx).is_singleton() {
17545            cx.propagate();
17546            return;
17547        }
17548
17549        let mut new_selections_by_buffer = HashMap::default();
17550        match &jump_data {
17551            Some(JumpData::MultiBufferPoint {
17552                excerpt_id,
17553                position,
17554                anchor,
17555                line_offset_from_top,
17556            }) => {
17557                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17558                if let Some(buffer) = multi_buffer_snapshot
17559                    .buffer_id_for_excerpt(*excerpt_id)
17560                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17561                {
17562                    let buffer_snapshot = buffer.read(cx).snapshot();
17563                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17564                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17565                    } else {
17566                        buffer_snapshot.clip_point(*position, Bias::Left)
17567                    };
17568                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17569                    new_selections_by_buffer.insert(
17570                        buffer,
17571                        (
17572                            vec![jump_to_offset..jump_to_offset],
17573                            Some(*line_offset_from_top),
17574                        ),
17575                    );
17576                }
17577            }
17578            Some(JumpData::MultiBufferRow {
17579                row,
17580                line_offset_from_top,
17581            }) => {
17582                let point = MultiBufferPoint::new(row.0, 0);
17583                if let Some((buffer, buffer_point, _)) =
17584                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17585                {
17586                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17587                    new_selections_by_buffer
17588                        .entry(buffer)
17589                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17590                        .0
17591                        .push(buffer_offset..buffer_offset)
17592                }
17593            }
17594            None => {
17595                let selections = self.selections.all::<usize>(cx);
17596                let multi_buffer = self.buffer.read(cx);
17597                for selection in selections {
17598                    for (snapshot, range, _, anchor) in multi_buffer
17599                        .snapshot(cx)
17600                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17601                    {
17602                        if let Some(anchor) = anchor {
17603                            // selection is in a deleted hunk
17604                            let Some(buffer_id) = anchor.buffer_id else {
17605                                continue;
17606                            };
17607                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17608                                continue;
17609                            };
17610                            let offset = text::ToOffset::to_offset(
17611                                &anchor.text_anchor,
17612                                &buffer_handle.read(cx).snapshot(),
17613                            );
17614                            let range = offset..offset;
17615                            new_selections_by_buffer
17616                                .entry(buffer_handle)
17617                                .or_insert((Vec::new(), None))
17618                                .0
17619                                .push(range)
17620                        } else {
17621                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17622                            else {
17623                                continue;
17624                            };
17625                            new_selections_by_buffer
17626                                .entry(buffer_handle)
17627                                .or_insert((Vec::new(), None))
17628                                .0
17629                                .push(range)
17630                        }
17631                    }
17632                }
17633            }
17634        }
17635
17636        new_selections_by_buffer
17637            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17638
17639        if new_selections_by_buffer.is_empty() {
17640            return;
17641        }
17642
17643        // We defer the pane interaction because we ourselves are a workspace item
17644        // and activating a new item causes the pane to call a method on us reentrantly,
17645        // which panics if we're on the stack.
17646        window.defer(cx, move |window, cx| {
17647            workspace.update(cx, |workspace, cx| {
17648                let pane = if split {
17649                    workspace.adjacent_pane(window, cx)
17650                } else {
17651                    workspace.active_pane().clone()
17652                };
17653
17654                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17655                    let editor = buffer
17656                        .read(cx)
17657                        .file()
17658                        .is_none()
17659                        .then(|| {
17660                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17661                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17662                            // Instead, we try to activate the existing editor in the pane first.
17663                            let (editor, pane_item_index) =
17664                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17665                                    let editor = item.downcast::<Editor>()?;
17666                                    let singleton_buffer =
17667                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17668                                    if singleton_buffer == buffer {
17669                                        Some((editor, i))
17670                                    } else {
17671                                        None
17672                                    }
17673                                })?;
17674                            pane.update(cx, |pane, cx| {
17675                                pane.activate_item(pane_item_index, true, true, window, cx)
17676                            });
17677                            Some(editor)
17678                        })
17679                        .flatten()
17680                        .unwrap_or_else(|| {
17681                            workspace.open_project_item::<Self>(
17682                                pane.clone(),
17683                                buffer,
17684                                true,
17685                                true,
17686                                window,
17687                                cx,
17688                            )
17689                        });
17690
17691                    editor.update(cx, |editor, cx| {
17692                        let autoscroll = match scroll_offset {
17693                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17694                            None => Autoscroll::newest(),
17695                        };
17696                        let nav_history = editor.nav_history.take();
17697                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17698                            s.select_ranges(ranges);
17699                        });
17700                        editor.nav_history = nav_history;
17701                    });
17702                }
17703            })
17704        });
17705    }
17706
17707    // For now, don't allow opening excerpts in buffers that aren't backed by
17708    // regular project files.
17709    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17710        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17711    }
17712
17713    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17714        let snapshot = self.buffer.read(cx).read(cx);
17715        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17716        Some(
17717            ranges
17718                .iter()
17719                .map(move |range| {
17720                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17721                })
17722                .collect(),
17723        )
17724    }
17725
17726    fn selection_replacement_ranges(
17727        &self,
17728        range: Range<OffsetUtf16>,
17729        cx: &mut App,
17730    ) -> Vec<Range<OffsetUtf16>> {
17731        let selections = self.selections.all::<OffsetUtf16>(cx);
17732        let newest_selection = selections
17733            .iter()
17734            .max_by_key(|selection| selection.id)
17735            .unwrap();
17736        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17737        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17738        let snapshot = self.buffer.read(cx).read(cx);
17739        selections
17740            .into_iter()
17741            .map(|mut selection| {
17742                selection.start.0 =
17743                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17744                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17745                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17746                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17747            })
17748            .collect()
17749    }
17750
17751    fn report_editor_event(
17752        &self,
17753        event_type: &'static str,
17754        file_extension: Option<String>,
17755        cx: &App,
17756    ) {
17757        if cfg!(any(test, feature = "test-support")) {
17758            return;
17759        }
17760
17761        let Some(project) = &self.project else { return };
17762
17763        // If None, we are in a file without an extension
17764        let file = self
17765            .buffer
17766            .read(cx)
17767            .as_singleton()
17768            .and_then(|b| b.read(cx).file());
17769        let file_extension = file_extension.or(file
17770            .as_ref()
17771            .and_then(|file| Path::new(file.file_name(cx)).extension())
17772            .and_then(|e| e.to_str())
17773            .map(|a| a.to_string()));
17774
17775        let vim_mode = cx
17776            .global::<SettingsStore>()
17777            .raw_user_settings()
17778            .get("vim_mode")
17779            == Some(&serde_json::Value::Bool(true));
17780
17781        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17782        let copilot_enabled = edit_predictions_provider
17783            == language::language_settings::EditPredictionProvider::Copilot;
17784        let copilot_enabled_for_language = self
17785            .buffer
17786            .read(cx)
17787            .language_settings(cx)
17788            .show_edit_predictions;
17789
17790        let project = project.read(cx);
17791        telemetry::event!(
17792            event_type,
17793            file_extension,
17794            vim_mode,
17795            copilot_enabled,
17796            copilot_enabled_for_language,
17797            edit_predictions_provider,
17798            is_via_ssh = project.is_via_ssh(),
17799        );
17800    }
17801
17802    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17803    /// with each line being an array of {text, highlight} objects.
17804    fn copy_highlight_json(
17805        &mut self,
17806        _: &CopyHighlightJson,
17807        window: &mut Window,
17808        cx: &mut Context<Self>,
17809    ) {
17810        #[derive(Serialize)]
17811        struct Chunk<'a> {
17812            text: String,
17813            highlight: Option<&'a str>,
17814        }
17815
17816        let snapshot = self.buffer.read(cx).snapshot(cx);
17817        let range = self
17818            .selected_text_range(false, window, cx)
17819            .and_then(|selection| {
17820                if selection.range.is_empty() {
17821                    None
17822                } else {
17823                    Some(selection.range)
17824                }
17825            })
17826            .unwrap_or_else(|| 0..snapshot.len());
17827
17828        let chunks = snapshot.chunks(range, true);
17829        let mut lines = Vec::new();
17830        let mut line: VecDeque<Chunk> = VecDeque::new();
17831
17832        let Some(style) = self.style.as_ref() else {
17833            return;
17834        };
17835
17836        for chunk in chunks {
17837            let highlight = chunk
17838                .syntax_highlight_id
17839                .and_then(|id| id.name(&style.syntax));
17840            let mut chunk_lines = chunk.text.split('\n').peekable();
17841            while let Some(text) = chunk_lines.next() {
17842                let mut merged_with_last_token = false;
17843                if let Some(last_token) = line.back_mut() {
17844                    if last_token.highlight == highlight {
17845                        last_token.text.push_str(text);
17846                        merged_with_last_token = true;
17847                    }
17848                }
17849
17850                if !merged_with_last_token {
17851                    line.push_back(Chunk {
17852                        text: text.into(),
17853                        highlight,
17854                    });
17855                }
17856
17857                if chunk_lines.peek().is_some() {
17858                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17859                        line.pop_front();
17860                    }
17861                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17862                        line.pop_back();
17863                    }
17864
17865                    lines.push(mem::take(&mut line));
17866                }
17867            }
17868        }
17869
17870        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17871            return;
17872        };
17873        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17874    }
17875
17876    pub fn open_context_menu(
17877        &mut self,
17878        _: &OpenContextMenu,
17879        window: &mut Window,
17880        cx: &mut Context<Self>,
17881    ) {
17882        self.request_autoscroll(Autoscroll::newest(), cx);
17883        let position = self.selections.newest_display(cx).start;
17884        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17885    }
17886
17887    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17888        &self.inlay_hint_cache
17889    }
17890
17891    pub fn replay_insert_event(
17892        &mut self,
17893        text: &str,
17894        relative_utf16_range: Option<Range<isize>>,
17895        window: &mut Window,
17896        cx: &mut Context<Self>,
17897    ) {
17898        if !self.input_enabled {
17899            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17900            return;
17901        }
17902        if let Some(relative_utf16_range) = relative_utf16_range {
17903            let selections = self.selections.all::<OffsetUtf16>(cx);
17904            self.change_selections(None, window, cx, |s| {
17905                let new_ranges = selections.into_iter().map(|range| {
17906                    let start = OffsetUtf16(
17907                        range
17908                            .head()
17909                            .0
17910                            .saturating_add_signed(relative_utf16_range.start),
17911                    );
17912                    let end = OffsetUtf16(
17913                        range
17914                            .head()
17915                            .0
17916                            .saturating_add_signed(relative_utf16_range.end),
17917                    );
17918                    start..end
17919                });
17920                s.select_ranges(new_ranges);
17921            });
17922        }
17923
17924        self.handle_input(text, window, cx);
17925    }
17926
17927    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17928        let Some(provider) = self.semantics_provider.as_ref() else {
17929            return false;
17930        };
17931
17932        let mut supports = false;
17933        self.buffer().update(cx, |this, cx| {
17934            this.for_each_buffer(|buffer| {
17935                supports |= provider.supports_inlay_hints(buffer, cx);
17936            });
17937        });
17938
17939        supports
17940    }
17941
17942    pub fn is_focused(&self, window: &Window) -> bool {
17943        self.focus_handle.is_focused(window)
17944    }
17945
17946    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17947        cx.emit(EditorEvent::Focused);
17948
17949        if let Some(descendant) = self
17950            .last_focused_descendant
17951            .take()
17952            .and_then(|descendant| descendant.upgrade())
17953        {
17954            window.focus(&descendant);
17955        } else {
17956            if let Some(blame) = self.blame.as_ref() {
17957                blame.update(cx, GitBlame::focus)
17958            }
17959
17960            self.blink_manager.update(cx, BlinkManager::enable);
17961            self.show_cursor_names(window, cx);
17962            self.buffer.update(cx, |buffer, cx| {
17963                buffer.finalize_last_transaction(cx);
17964                if self.leader_peer_id.is_none() {
17965                    buffer.set_active_selections(
17966                        &self.selections.disjoint_anchors(),
17967                        self.selections.line_mode,
17968                        self.cursor_shape,
17969                        cx,
17970                    );
17971                }
17972            });
17973        }
17974    }
17975
17976    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17977        cx.emit(EditorEvent::FocusedIn)
17978    }
17979
17980    fn handle_focus_out(
17981        &mut self,
17982        event: FocusOutEvent,
17983        _window: &mut Window,
17984        cx: &mut Context<Self>,
17985    ) {
17986        if event.blurred != self.focus_handle {
17987            self.last_focused_descendant = Some(event.blurred);
17988        }
17989        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17990    }
17991
17992    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17993        self.blink_manager.update(cx, BlinkManager::disable);
17994        self.buffer
17995            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17996
17997        if let Some(blame) = self.blame.as_ref() {
17998            blame.update(cx, GitBlame::blur)
17999        }
18000        if !self.hover_state.focused(window, cx) {
18001            hide_hover(self, cx);
18002        }
18003        if !self
18004            .context_menu
18005            .borrow()
18006            .as_ref()
18007            .is_some_and(|context_menu| context_menu.focused(window, cx))
18008        {
18009            self.hide_context_menu(window, cx);
18010        }
18011        self.discard_inline_completion(false, cx);
18012        cx.emit(EditorEvent::Blurred);
18013        cx.notify();
18014    }
18015
18016    pub fn register_action<A: Action>(
18017        &mut self,
18018        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18019    ) -> Subscription {
18020        let id = self.next_editor_action_id.post_inc();
18021        let listener = Arc::new(listener);
18022        self.editor_actions.borrow_mut().insert(
18023            id,
18024            Box::new(move |window, _| {
18025                let listener = listener.clone();
18026                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18027                    let action = action.downcast_ref().unwrap();
18028                    if phase == DispatchPhase::Bubble {
18029                        listener(action, window, cx)
18030                    }
18031                })
18032            }),
18033        );
18034
18035        let editor_actions = self.editor_actions.clone();
18036        Subscription::new(move || {
18037            editor_actions.borrow_mut().remove(&id);
18038        })
18039    }
18040
18041    pub fn file_header_size(&self) -> u32 {
18042        FILE_HEADER_HEIGHT
18043    }
18044
18045    pub fn restore(
18046        &mut self,
18047        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18048        window: &mut Window,
18049        cx: &mut Context<Self>,
18050    ) {
18051        let workspace = self.workspace();
18052        let project = self.project.as_ref();
18053        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18054            let mut tasks = Vec::new();
18055            for (buffer_id, changes) in revert_changes {
18056                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18057                    buffer.update(cx, |buffer, cx| {
18058                        buffer.edit(
18059                            changes
18060                                .into_iter()
18061                                .map(|(range, text)| (range, text.to_string())),
18062                            None,
18063                            cx,
18064                        );
18065                    });
18066
18067                    if let Some(project) =
18068                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18069                    {
18070                        project.update(cx, |project, cx| {
18071                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18072                        })
18073                    }
18074                }
18075            }
18076            tasks
18077        });
18078        cx.spawn_in(window, async move |_, cx| {
18079            for (buffer, task) in save_tasks {
18080                let result = task.await;
18081                if result.is_err() {
18082                    let Some(path) = buffer
18083                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18084                        .ok()
18085                    else {
18086                        continue;
18087                    };
18088                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18089                        let Some(task) = cx
18090                            .update_window_entity(&workspace, |workspace, window, cx| {
18091                                workspace
18092                                    .open_path_preview(path, None, false, false, false, window, cx)
18093                            })
18094                            .ok()
18095                        else {
18096                            continue;
18097                        };
18098                        task.await.log_err();
18099                    }
18100                }
18101            }
18102        })
18103        .detach();
18104        self.change_selections(None, window, cx, |selections| selections.refresh());
18105    }
18106
18107    pub fn to_pixel_point(
18108        &self,
18109        source: multi_buffer::Anchor,
18110        editor_snapshot: &EditorSnapshot,
18111        window: &mut Window,
18112    ) -> Option<gpui::Point<Pixels>> {
18113        let source_point = source.to_display_point(editor_snapshot);
18114        self.display_to_pixel_point(source_point, editor_snapshot, window)
18115    }
18116
18117    pub fn display_to_pixel_point(
18118        &self,
18119        source: DisplayPoint,
18120        editor_snapshot: &EditorSnapshot,
18121        window: &mut Window,
18122    ) -> Option<gpui::Point<Pixels>> {
18123        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18124        let text_layout_details = self.text_layout_details(window);
18125        let scroll_top = text_layout_details
18126            .scroll_anchor
18127            .scroll_position(editor_snapshot)
18128            .y;
18129
18130        if source.row().as_f32() < scroll_top.floor() {
18131            return None;
18132        }
18133        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18134        let source_y = line_height * (source.row().as_f32() - scroll_top);
18135        Some(gpui::Point::new(source_x, source_y))
18136    }
18137
18138    pub fn has_visible_completions_menu(&self) -> bool {
18139        !self.edit_prediction_preview_is_active()
18140            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18141                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18142            })
18143    }
18144
18145    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18146        self.addons
18147            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18148    }
18149
18150    pub fn unregister_addon<T: Addon>(&mut self) {
18151        self.addons.remove(&std::any::TypeId::of::<T>());
18152    }
18153
18154    pub fn addon<T: Addon>(&self) -> Option<&T> {
18155        let type_id = std::any::TypeId::of::<T>();
18156        self.addons
18157            .get(&type_id)
18158            .and_then(|item| item.to_any().downcast_ref::<T>())
18159    }
18160
18161    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18162        let text_layout_details = self.text_layout_details(window);
18163        let style = &text_layout_details.editor_style;
18164        let font_id = window.text_system().resolve_font(&style.text.font());
18165        let font_size = style.text.font_size.to_pixels(window.rem_size());
18166        let line_height = style.text.line_height_in_pixels(window.rem_size());
18167        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18168
18169        gpui::Size::new(em_width, line_height)
18170    }
18171
18172    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18173        self.load_diff_task.clone()
18174    }
18175
18176    fn read_metadata_from_db(
18177        &mut self,
18178        item_id: u64,
18179        workspace_id: WorkspaceId,
18180        window: &mut Window,
18181        cx: &mut Context<Editor>,
18182    ) {
18183        if self.is_singleton(cx)
18184            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18185        {
18186            let buffer_snapshot = OnceCell::new();
18187
18188            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18189                if !folds.is_empty() {
18190                    let snapshot =
18191                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18192                    self.fold_ranges(
18193                        folds
18194                            .into_iter()
18195                            .map(|(start, end)| {
18196                                snapshot.clip_offset(start, Bias::Left)
18197                                    ..snapshot.clip_offset(end, Bias::Right)
18198                            })
18199                            .collect(),
18200                        false,
18201                        window,
18202                        cx,
18203                    );
18204                }
18205            }
18206
18207            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18208                if !selections.is_empty() {
18209                    let snapshot =
18210                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18211                    self.change_selections(None, window, cx, |s| {
18212                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18213                            snapshot.clip_offset(start, Bias::Left)
18214                                ..snapshot.clip_offset(end, Bias::Right)
18215                        }));
18216                    });
18217                }
18218            };
18219        }
18220
18221        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18222    }
18223}
18224
18225// Consider user intent and default settings
18226fn choose_completion_range(
18227    completion: &Completion,
18228    intent: CompletionIntent,
18229    buffer: &Entity<Buffer>,
18230    cx: &mut Context<Editor>,
18231) -> Range<usize> {
18232    fn should_replace(
18233        completion: &Completion,
18234        insert_range: &Range<text::Anchor>,
18235        intent: CompletionIntent,
18236        completion_mode_setting: LspInsertMode,
18237        buffer: &Buffer,
18238    ) -> bool {
18239        // specific actions take precedence over settings
18240        match intent {
18241            CompletionIntent::CompleteWithInsert => return false,
18242            CompletionIntent::CompleteWithReplace => return true,
18243            CompletionIntent::Complete | CompletionIntent::Compose => {}
18244        }
18245
18246        match completion_mode_setting {
18247            LspInsertMode::Insert => false,
18248            LspInsertMode::Replace => true,
18249            LspInsertMode::ReplaceSubsequence => {
18250                let mut text_to_replace = buffer.chars_for_range(
18251                    buffer.anchor_before(completion.replace_range.start)
18252                        ..buffer.anchor_after(completion.replace_range.end),
18253                );
18254                let mut completion_text = completion.new_text.chars();
18255
18256                // is `text_to_replace` a subsequence of `completion_text`
18257                text_to_replace
18258                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18259            }
18260            LspInsertMode::ReplaceSuffix => {
18261                let range_after_cursor = insert_range.end..completion.replace_range.end;
18262
18263                let text_after_cursor = buffer
18264                    .text_for_range(
18265                        buffer.anchor_before(range_after_cursor.start)
18266                            ..buffer.anchor_after(range_after_cursor.end),
18267                    )
18268                    .collect::<String>();
18269                completion.new_text.ends_with(&text_after_cursor)
18270            }
18271        }
18272    }
18273
18274    let buffer = buffer.read(cx);
18275
18276    if let CompletionSource::Lsp {
18277        insert_range: Some(insert_range),
18278        ..
18279    } = &completion.source
18280    {
18281        let completion_mode_setting =
18282            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18283                .completions
18284                .lsp_insert_mode;
18285
18286        if !should_replace(
18287            completion,
18288            &insert_range,
18289            intent,
18290            completion_mode_setting,
18291            buffer,
18292        ) {
18293            return insert_range.to_offset(buffer);
18294        }
18295    }
18296
18297    completion.replace_range.to_offset(buffer)
18298}
18299
18300fn insert_extra_newline_brackets(
18301    buffer: &MultiBufferSnapshot,
18302    range: Range<usize>,
18303    language: &language::LanguageScope,
18304) -> bool {
18305    let leading_whitespace_len = buffer
18306        .reversed_chars_at(range.start)
18307        .take_while(|c| c.is_whitespace() && *c != '\n')
18308        .map(|c| c.len_utf8())
18309        .sum::<usize>();
18310    let trailing_whitespace_len = buffer
18311        .chars_at(range.end)
18312        .take_while(|c| c.is_whitespace() && *c != '\n')
18313        .map(|c| c.len_utf8())
18314        .sum::<usize>();
18315    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18316
18317    language.brackets().any(|(pair, enabled)| {
18318        let pair_start = pair.start.trim_end();
18319        let pair_end = pair.end.trim_start();
18320
18321        enabled
18322            && pair.newline
18323            && buffer.contains_str_at(range.end, pair_end)
18324            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18325    })
18326}
18327
18328fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18329    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18330        [(buffer, range, _)] => (*buffer, range.clone()),
18331        _ => return false,
18332    };
18333    let pair = {
18334        let mut result: Option<BracketMatch> = None;
18335
18336        for pair in buffer
18337            .all_bracket_ranges(range.clone())
18338            .filter(move |pair| {
18339                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18340            })
18341        {
18342            let len = pair.close_range.end - pair.open_range.start;
18343
18344            if let Some(existing) = &result {
18345                let existing_len = existing.close_range.end - existing.open_range.start;
18346                if len > existing_len {
18347                    continue;
18348                }
18349            }
18350
18351            result = Some(pair);
18352        }
18353
18354        result
18355    };
18356    let Some(pair) = pair else {
18357        return false;
18358    };
18359    pair.newline_only
18360        && buffer
18361            .chars_for_range(pair.open_range.end..range.start)
18362            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18363            .all(|c| c.is_whitespace() && c != '\n')
18364}
18365
18366fn get_uncommitted_diff_for_buffer(
18367    project: &Entity<Project>,
18368    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18369    buffer: Entity<MultiBuffer>,
18370    cx: &mut App,
18371) -> Task<()> {
18372    let mut tasks = Vec::new();
18373    project.update(cx, |project, cx| {
18374        for buffer in buffers {
18375            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18376                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18377            }
18378        }
18379    });
18380    cx.spawn(async move |cx| {
18381        let diffs = future::join_all(tasks).await;
18382        buffer
18383            .update(cx, |buffer, cx| {
18384                for diff in diffs.into_iter().flatten() {
18385                    buffer.add_diff(diff, cx);
18386                }
18387            })
18388            .ok();
18389    })
18390}
18391
18392fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18393    let tab_size = tab_size.get() as usize;
18394    let mut width = offset;
18395
18396    for ch in text.chars() {
18397        width += if ch == '\t' {
18398            tab_size - (width % tab_size)
18399        } else {
18400            1
18401        };
18402    }
18403
18404    width - offset
18405}
18406
18407#[cfg(test)]
18408mod tests {
18409    use super::*;
18410
18411    #[test]
18412    fn test_string_size_with_expanded_tabs() {
18413        let nz = |val| NonZeroU32::new(val).unwrap();
18414        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18415        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18416        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18417        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18418        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18419        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18420        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18421        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18422    }
18423}
18424
18425/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18426struct WordBreakingTokenizer<'a> {
18427    input: &'a str,
18428}
18429
18430impl<'a> WordBreakingTokenizer<'a> {
18431    fn new(input: &'a str) -> Self {
18432        Self { input }
18433    }
18434}
18435
18436fn is_char_ideographic(ch: char) -> bool {
18437    use unicode_script::Script::*;
18438    use unicode_script::UnicodeScript;
18439    matches!(ch.script(), Han | Tangut | Yi)
18440}
18441
18442fn is_grapheme_ideographic(text: &str) -> bool {
18443    text.chars().any(is_char_ideographic)
18444}
18445
18446fn is_grapheme_whitespace(text: &str) -> bool {
18447    text.chars().any(|x| x.is_whitespace())
18448}
18449
18450fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18451    text.chars().next().map_or(false, |ch| {
18452        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18453    })
18454}
18455
18456#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18457enum WordBreakToken<'a> {
18458    Word { token: &'a str, grapheme_len: usize },
18459    InlineWhitespace { token: &'a str, grapheme_len: usize },
18460    Newline,
18461}
18462
18463impl<'a> Iterator for WordBreakingTokenizer<'a> {
18464    /// Yields a span, the count of graphemes in the token, and whether it was
18465    /// whitespace. Note that it also breaks at word boundaries.
18466    type Item = WordBreakToken<'a>;
18467
18468    fn next(&mut self) -> Option<Self::Item> {
18469        use unicode_segmentation::UnicodeSegmentation;
18470        if self.input.is_empty() {
18471            return None;
18472        }
18473
18474        let mut iter = self.input.graphemes(true).peekable();
18475        let mut offset = 0;
18476        let mut grapheme_len = 0;
18477        if let Some(first_grapheme) = iter.next() {
18478            let is_newline = first_grapheme == "\n";
18479            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18480            offset += first_grapheme.len();
18481            grapheme_len += 1;
18482            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18483                if let Some(grapheme) = iter.peek().copied() {
18484                    if should_stay_with_preceding_ideograph(grapheme) {
18485                        offset += grapheme.len();
18486                        grapheme_len += 1;
18487                    }
18488                }
18489            } else {
18490                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18491                let mut next_word_bound = words.peek().copied();
18492                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18493                    next_word_bound = words.next();
18494                }
18495                while let Some(grapheme) = iter.peek().copied() {
18496                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18497                        break;
18498                    };
18499                    if is_grapheme_whitespace(grapheme) != is_whitespace
18500                        || (grapheme == "\n") != is_newline
18501                    {
18502                        break;
18503                    };
18504                    offset += grapheme.len();
18505                    grapheme_len += 1;
18506                    iter.next();
18507                }
18508            }
18509            let token = &self.input[..offset];
18510            self.input = &self.input[offset..];
18511            if token == "\n" {
18512                Some(WordBreakToken::Newline)
18513            } else if is_whitespace {
18514                Some(WordBreakToken::InlineWhitespace {
18515                    token,
18516                    grapheme_len,
18517                })
18518            } else {
18519                Some(WordBreakToken::Word {
18520                    token,
18521                    grapheme_len,
18522                })
18523            }
18524        } else {
18525            None
18526        }
18527    }
18528}
18529
18530#[test]
18531fn test_word_breaking_tokenizer() {
18532    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18533        ("", &[]),
18534        ("  ", &[whitespace("  ", 2)]),
18535        ("Ʒ", &[word("Ʒ", 1)]),
18536        ("Ǽ", &[word("Ǽ", 1)]),
18537        ("", &[word("", 1)]),
18538        ("⋑⋑", &[word("⋑⋑", 2)]),
18539        (
18540            "原理,进而",
18541            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18542        ),
18543        (
18544            "hello world",
18545            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18546        ),
18547        (
18548            "hello, world",
18549            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18550        ),
18551        (
18552            "  hello world",
18553            &[
18554                whitespace("  ", 2),
18555                word("hello", 5),
18556                whitespace(" ", 1),
18557                word("world", 5),
18558            ],
18559        ),
18560        (
18561            "这是什么 \n 钢笔",
18562            &[
18563                word("", 1),
18564                word("", 1),
18565                word("", 1),
18566                word("", 1),
18567                whitespace(" ", 1),
18568                newline(),
18569                whitespace(" ", 1),
18570                word("", 1),
18571                word("", 1),
18572            ],
18573        ),
18574        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18575    ];
18576
18577    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18578        WordBreakToken::Word {
18579            token,
18580            grapheme_len,
18581        }
18582    }
18583
18584    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18585        WordBreakToken::InlineWhitespace {
18586            token,
18587            grapheme_len,
18588        }
18589    }
18590
18591    fn newline() -> WordBreakToken<'static> {
18592        WordBreakToken::Newline
18593    }
18594
18595    for (input, result) in tests {
18596        assert_eq!(
18597            WordBreakingTokenizer::new(input)
18598                .collect::<Vec<_>>()
18599                .as_slice(),
18600            *result,
18601        );
18602    }
18603}
18604
18605fn wrap_with_prefix(
18606    line_prefix: String,
18607    unwrapped_text: String,
18608    wrap_column: usize,
18609    tab_size: NonZeroU32,
18610    preserve_existing_whitespace: bool,
18611) -> String {
18612    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18613    let mut wrapped_text = String::new();
18614    let mut current_line = line_prefix.clone();
18615
18616    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18617    let mut current_line_len = line_prefix_len;
18618    let mut in_whitespace = false;
18619    for token in tokenizer {
18620        let have_preceding_whitespace = in_whitespace;
18621        match token {
18622            WordBreakToken::Word {
18623                token,
18624                grapheme_len,
18625            } => {
18626                in_whitespace = false;
18627                if current_line_len + grapheme_len > wrap_column
18628                    && current_line_len != line_prefix_len
18629                {
18630                    wrapped_text.push_str(current_line.trim_end());
18631                    wrapped_text.push('\n');
18632                    current_line.truncate(line_prefix.len());
18633                    current_line_len = line_prefix_len;
18634                }
18635                current_line.push_str(token);
18636                current_line_len += grapheme_len;
18637            }
18638            WordBreakToken::InlineWhitespace {
18639                mut token,
18640                mut grapheme_len,
18641            } => {
18642                in_whitespace = true;
18643                if have_preceding_whitespace && !preserve_existing_whitespace {
18644                    continue;
18645                }
18646                if !preserve_existing_whitespace {
18647                    token = " ";
18648                    grapheme_len = 1;
18649                }
18650                if current_line_len + grapheme_len > wrap_column {
18651                    wrapped_text.push_str(current_line.trim_end());
18652                    wrapped_text.push('\n');
18653                    current_line.truncate(line_prefix.len());
18654                    current_line_len = line_prefix_len;
18655                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18656                    current_line.push_str(token);
18657                    current_line_len += grapheme_len;
18658                }
18659            }
18660            WordBreakToken::Newline => {
18661                in_whitespace = true;
18662                if preserve_existing_whitespace {
18663                    wrapped_text.push_str(current_line.trim_end());
18664                    wrapped_text.push('\n');
18665                    current_line.truncate(line_prefix.len());
18666                    current_line_len = line_prefix_len;
18667                } else if have_preceding_whitespace {
18668                    continue;
18669                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18670                {
18671                    wrapped_text.push_str(current_line.trim_end());
18672                    wrapped_text.push('\n');
18673                    current_line.truncate(line_prefix.len());
18674                    current_line_len = line_prefix_len;
18675                } else if current_line_len != line_prefix_len {
18676                    current_line.push(' ');
18677                    current_line_len += 1;
18678                }
18679            }
18680        }
18681    }
18682
18683    if !current_line.is_empty() {
18684        wrapped_text.push_str(&current_line);
18685    }
18686    wrapped_text
18687}
18688
18689#[test]
18690fn test_wrap_with_prefix() {
18691    assert_eq!(
18692        wrap_with_prefix(
18693            "# ".to_string(),
18694            "abcdefg".to_string(),
18695            4,
18696            NonZeroU32::new(4).unwrap(),
18697            false,
18698        ),
18699        "# abcdefg"
18700    );
18701    assert_eq!(
18702        wrap_with_prefix(
18703            "".to_string(),
18704            "\thello world".to_string(),
18705            8,
18706            NonZeroU32::new(4).unwrap(),
18707            false,
18708        ),
18709        "hello\nworld"
18710    );
18711    assert_eq!(
18712        wrap_with_prefix(
18713            "// ".to_string(),
18714            "xx \nyy zz aa bb cc".to_string(),
18715            12,
18716            NonZeroU32::new(4).unwrap(),
18717            false,
18718        ),
18719        "// xx yy zz\n// aa bb cc"
18720    );
18721    assert_eq!(
18722        wrap_with_prefix(
18723            String::new(),
18724            "这是什么 \n 钢笔".to_string(),
18725            3,
18726            NonZeroU32::new(4).unwrap(),
18727            false,
18728        ),
18729        "这是什\n么 钢\n"
18730    );
18731}
18732
18733pub trait CollaborationHub {
18734    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18735    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18736    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18737}
18738
18739impl CollaborationHub for Entity<Project> {
18740    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18741        self.read(cx).collaborators()
18742    }
18743
18744    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18745        self.read(cx).user_store().read(cx).participant_indices()
18746    }
18747
18748    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18749        let this = self.read(cx);
18750        let user_ids = this.collaborators().values().map(|c| c.user_id);
18751        this.user_store().read_with(cx, |user_store, cx| {
18752            user_store.participant_names(user_ids, cx)
18753        })
18754    }
18755}
18756
18757pub trait SemanticsProvider {
18758    fn hover(
18759        &self,
18760        buffer: &Entity<Buffer>,
18761        position: text::Anchor,
18762        cx: &mut App,
18763    ) -> Option<Task<Vec<project::Hover>>>;
18764
18765    fn inlay_hints(
18766        &self,
18767        buffer_handle: Entity<Buffer>,
18768        range: Range<text::Anchor>,
18769        cx: &mut App,
18770    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18771
18772    fn resolve_inlay_hint(
18773        &self,
18774        hint: InlayHint,
18775        buffer_handle: Entity<Buffer>,
18776        server_id: LanguageServerId,
18777        cx: &mut App,
18778    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18779
18780    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18781
18782    fn document_highlights(
18783        &self,
18784        buffer: &Entity<Buffer>,
18785        position: text::Anchor,
18786        cx: &mut App,
18787    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18788
18789    fn definitions(
18790        &self,
18791        buffer: &Entity<Buffer>,
18792        position: text::Anchor,
18793        kind: GotoDefinitionKind,
18794        cx: &mut App,
18795    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18796
18797    fn range_for_rename(
18798        &self,
18799        buffer: &Entity<Buffer>,
18800        position: text::Anchor,
18801        cx: &mut App,
18802    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18803
18804    fn perform_rename(
18805        &self,
18806        buffer: &Entity<Buffer>,
18807        position: text::Anchor,
18808        new_name: String,
18809        cx: &mut App,
18810    ) -> Option<Task<Result<ProjectTransaction>>>;
18811}
18812
18813pub trait CompletionProvider {
18814    fn completions(
18815        &self,
18816        excerpt_id: ExcerptId,
18817        buffer: &Entity<Buffer>,
18818        buffer_position: text::Anchor,
18819        trigger: CompletionContext,
18820        window: &mut Window,
18821        cx: &mut Context<Editor>,
18822    ) -> Task<Result<Option<Vec<Completion>>>>;
18823
18824    fn resolve_completions(
18825        &self,
18826        buffer: Entity<Buffer>,
18827        completion_indices: Vec<usize>,
18828        completions: Rc<RefCell<Box<[Completion]>>>,
18829        cx: &mut Context<Editor>,
18830    ) -> Task<Result<bool>>;
18831
18832    fn apply_additional_edits_for_completion(
18833        &self,
18834        _buffer: Entity<Buffer>,
18835        _completions: Rc<RefCell<Box<[Completion]>>>,
18836        _completion_index: usize,
18837        _push_to_history: bool,
18838        _cx: &mut Context<Editor>,
18839    ) -> Task<Result<Option<language::Transaction>>> {
18840        Task::ready(Ok(None))
18841    }
18842
18843    fn is_completion_trigger(
18844        &self,
18845        buffer: &Entity<Buffer>,
18846        position: language::Anchor,
18847        text: &str,
18848        trigger_in_words: bool,
18849        cx: &mut Context<Editor>,
18850    ) -> bool;
18851
18852    fn sort_completions(&self) -> bool {
18853        true
18854    }
18855
18856    fn filter_completions(&self) -> bool {
18857        true
18858    }
18859}
18860
18861pub trait CodeActionProvider {
18862    fn id(&self) -> Arc<str>;
18863
18864    fn code_actions(
18865        &self,
18866        buffer: &Entity<Buffer>,
18867        range: Range<text::Anchor>,
18868        window: &mut Window,
18869        cx: &mut App,
18870    ) -> Task<Result<Vec<CodeAction>>>;
18871
18872    fn apply_code_action(
18873        &self,
18874        buffer_handle: Entity<Buffer>,
18875        action: CodeAction,
18876        excerpt_id: ExcerptId,
18877        push_to_history: bool,
18878        window: &mut Window,
18879        cx: &mut App,
18880    ) -> Task<Result<ProjectTransaction>>;
18881}
18882
18883impl CodeActionProvider for Entity<Project> {
18884    fn id(&self) -> Arc<str> {
18885        "project".into()
18886    }
18887
18888    fn code_actions(
18889        &self,
18890        buffer: &Entity<Buffer>,
18891        range: Range<text::Anchor>,
18892        _window: &mut Window,
18893        cx: &mut App,
18894    ) -> Task<Result<Vec<CodeAction>>> {
18895        self.update(cx, |project, cx| {
18896            let code_lens = project.code_lens(buffer, range.clone(), cx);
18897            let code_actions = project.code_actions(buffer, range, None, cx);
18898            cx.background_spawn(async move {
18899                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18900                Ok(code_lens
18901                    .context("code lens fetch")?
18902                    .into_iter()
18903                    .chain(code_actions.context("code action fetch")?)
18904                    .collect())
18905            })
18906        })
18907    }
18908
18909    fn apply_code_action(
18910        &self,
18911        buffer_handle: Entity<Buffer>,
18912        action: CodeAction,
18913        _excerpt_id: ExcerptId,
18914        push_to_history: bool,
18915        _window: &mut Window,
18916        cx: &mut App,
18917    ) -> Task<Result<ProjectTransaction>> {
18918        self.update(cx, |project, cx| {
18919            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18920        })
18921    }
18922}
18923
18924fn snippet_completions(
18925    project: &Project,
18926    buffer: &Entity<Buffer>,
18927    buffer_position: text::Anchor,
18928    cx: &mut App,
18929) -> Task<Result<Vec<Completion>>> {
18930    let languages = buffer.read(cx).languages_at(buffer_position);
18931    let snippet_store = project.snippets().read(cx);
18932
18933    let scopes: Vec<_> = languages
18934        .iter()
18935        .filter_map(|language| {
18936            let language_name = language.lsp_id();
18937            let snippets = snippet_store.snippets_for(Some(language_name), cx);
18938
18939            if snippets.is_empty() {
18940                None
18941            } else {
18942                Some((language.default_scope(), snippets))
18943            }
18944        })
18945        .collect();
18946
18947    if scopes.is_empty() {
18948        return Task::ready(Ok(vec![]));
18949    }
18950
18951    let snapshot = buffer.read(cx).text_snapshot();
18952    let chars: String = snapshot
18953        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18954        .collect();
18955    let executor = cx.background_executor().clone();
18956
18957    cx.background_spawn(async move {
18958        let mut all_results: Vec<Completion> = Vec::new();
18959        for (scope, snippets) in scopes.into_iter() {
18960            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
18961            let mut last_word = chars
18962                .chars()
18963                .take_while(|c| classifier.is_word(*c))
18964                .collect::<String>();
18965            last_word = last_word.chars().rev().collect();
18966
18967            if last_word.is_empty() {
18968                return Ok(vec![]);
18969            }
18970
18971            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18972            let to_lsp = |point: &text::Anchor| {
18973                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18974                point_to_lsp(end)
18975            };
18976            let lsp_end = to_lsp(&buffer_position);
18977
18978            let candidates = snippets
18979                .iter()
18980                .enumerate()
18981                .flat_map(|(ix, snippet)| {
18982                    snippet
18983                        .prefix
18984                        .iter()
18985                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18986                })
18987                .collect::<Vec<StringMatchCandidate>>();
18988
18989            let mut matches = fuzzy::match_strings(
18990                &candidates,
18991                &last_word,
18992                last_word.chars().any(|c| c.is_uppercase()),
18993                100,
18994                &Default::default(),
18995                executor.clone(),
18996            )
18997            .await;
18998
18999            // Remove all candidates where the query's start does not match the start of any word in the candidate
19000            if let Some(query_start) = last_word.chars().next() {
19001                matches.retain(|string_match| {
19002                    split_words(&string_match.string).any(|word| {
19003                        // Check that the first codepoint of the word as lowercase matches the first
19004                        // codepoint of the query as lowercase
19005                        word.chars()
19006                            .flat_map(|codepoint| codepoint.to_lowercase())
19007                            .zip(query_start.to_lowercase())
19008                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19009                    })
19010                });
19011            }
19012
19013            let matched_strings = matches
19014                .into_iter()
19015                .map(|m| m.string)
19016                .collect::<HashSet<_>>();
19017
19018            let mut result: Vec<Completion> = snippets
19019                .iter()
19020                .filter_map(|snippet| {
19021                    let matching_prefix = snippet
19022                        .prefix
19023                        .iter()
19024                        .find(|prefix| matched_strings.contains(*prefix))?;
19025                    let start = as_offset - last_word.len();
19026                    let start = snapshot.anchor_before(start);
19027                    let range = start..buffer_position;
19028                    let lsp_start = to_lsp(&start);
19029                    let lsp_range = lsp::Range {
19030                        start: lsp_start,
19031                        end: lsp_end,
19032                    };
19033                    Some(Completion {
19034                        replace_range: range,
19035                        new_text: snippet.body.clone(),
19036                        source: CompletionSource::Lsp {
19037                            insert_range: None,
19038                            server_id: LanguageServerId(usize::MAX),
19039                            resolved: true,
19040                            lsp_completion: Box::new(lsp::CompletionItem {
19041                                label: snippet.prefix.first().unwrap().clone(),
19042                                kind: Some(CompletionItemKind::SNIPPET),
19043                                label_details: snippet.description.as_ref().map(|description| {
19044                                    lsp::CompletionItemLabelDetails {
19045                                        detail: Some(description.clone()),
19046                                        description: None,
19047                                    }
19048                                }),
19049                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19050                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19051                                    lsp::InsertReplaceEdit {
19052                                        new_text: snippet.body.clone(),
19053                                        insert: lsp_range,
19054                                        replace: lsp_range,
19055                                    },
19056                                )),
19057                                filter_text: Some(snippet.body.clone()),
19058                                sort_text: Some(char::MAX.to_string()),
19059                                ..lsp::CompletionItem::default()
19060                            }),
19061                            lsp_defaults: None,
19062                        },
19063                        label: CodeLabel {
19064                            text: matching_prefix.clone(),
19065                            runs: Vec::new(),
19066                            filter_range: 0..matching_prefix.len(),
19067                        },
19068                        icon_path: None,
19069                        documentation: snippet.description.clone().map(|description| {
19070                            CompletionDocumentation::SingleLine(description.into())
19071                        }),
19072                        insert_text_mode: None,
19073                        confirm: None,
19074                    })
19075                })
19076                .collect();
19077
19078            all_results.append(&mut result);
19079        }
19080
19081        Ok(all_results)
19082    })
19083}
19084
19085impl CompletionProvider for Entity<Project> {
19086    fn completions(
19087        &self,
19088        _excerpt_id: ExcerptId,
19089        buffer: &Entity<Buffer>,
19090        buffer_position: text::Anchor,
19091        options: CompletionContext,
19092        _window: &mut Window,
19093        cx: &mut Context<Editor>,
19094    ) -> Task<Result<Option<Vec<Completion>>>> {
19095        self.update(cx, |project, cx| {
19096            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19097            let project_completions = project.completions(buffer, buffer_position, options, cx);
19098            cx.background_spawn(async move {
19099                let snippets_completions = snippets.await?;
19100                match project_completions.await? {
19101                    Some(mut completions) => {
19102                        completions.extend(snippets_completions);
19103                        Ok(Some(completions))
19104                    }
19105                    None => {
19106                        if snippets_completions.is_empty() {
19107                            Ok(None)
19108                        } else {
19109                            Ok(Some(snippets_completions))
19110                        }
19111                    }
19112                }
19113            })
19114        })
19115    }
19116
19117    fn resolve_completions(
19118        &self,
19119        buffer: Entity<Buffer>,
19120        completion_indices: Vec<usize>,
19121        completions: Rc<RefCell<Box<[Completion]>>>,
19122        cx: &mut Context<Editor>,
19123    ) -> Task<Result<bool>> {
19124        self.update(cx, |project, cx| {
19125            project.lsp_store().update(cx, |lsp_store, cx| {
19126                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19127            })
19128        })
19129    }
19130
19131    fn apply_additional_edits_for_completion(
19132        &self,
19133        buffer: Entity<Buffer>,
19134        completions: Rc<RefCell<Box<[Completion]>>>,
19135        completion_index: usize,
19136        push_to_history: bool,
19137        cx: &mut Context<Editor>,
19138    ) -> Task<Result<Option<language::Transaction>>> {
19139        self.update(cx, |project, cx| {
19140            project.lsp_store().update(cx, |lsp_store, cx| {
19141                lsp_store.apply_additional_edits_for_completion(
19142                    buffer,
19143                    completions,
19144                    completion_index,
19145                    push_to_history,
19146                    cx,
19147                )
19148            })
19149        })
19150    }
19151
19152    fn is_completion_trigger(
19153        &self,
19154        buffer: &Entity<Buffer>,
19155        position: language::Anchor,
19156        text: &str,
19157        trigger_in_words: bool,
19158        cx: &mut Context<Editor>,
19159    ) -> bool {
19160        let mut chars = text.chars();
19161        let char = if let Some(char) = chars.next() {
19162            char
19163        } else {
19164            return false;
19165        };
19166        if chars.next().is_some() {
19167            return false;
19168        }
19169
19170        let buffer = buffer.read(cx);
19171        let snapshot = buffer.snapshot();
19172        if !snapshot.settings_at(position, cx).show_completions_on_input {
19173            return false;
19174        }
19175        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19176        if trigger_in_words && classifier.is_word(char) {
19177            return true;
19178        }
19179
19180        buffer.completion_triggers().contains(text)
19181    }
19182}
19183
19184impl SemanticsProvider for Entity<Project> {
19185    fn hover(
19186        &self,
19187        buffer: &Entity<Buffer>,
19188        position: text::Anchor,
19189        cx: &mut App,
19190    ) -> Option<Task<Vec<project::Hover>>> {
19191        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19192    }
19193
19194    fn document_highlights(
19195        &self,
19196        buffer: &Entity<Buffer>,
19197        position: text::Anchor,
19198        cx: &mut App,
19199    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19200        Some(self.update(cx, |project, cx| {
19201            project.document_highlights(buffer, position, cx)
19202        }))
19203    }
19204
19205    fn definitions(
19206        &self,
19207        buffer: &Entity<Buffer>,
19208        position: text::Anchor,
19209        kind: GotoDefinitionKind,
19210        cx: &mut App,
19211    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19212        Some(self.update(cx, |project, cx| match kind {
19213            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19214            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19215            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19216            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19217        }))
19218    }
19219
19220    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19221        // TODO: make this work for remote projects
19222        self.update(cx, |this, cx| {
19223            buffer.update(cx, |buffer, cx| {
19224                this.any_language_server_supports_inlay_hints(buffer, cx)
19225            })
19226        })
19227    }
19228
19229    fn inlay_hints(
19230        &self,
19231        buffer_handle: Entity<Buffer>,
19232        range: Range<text::Anchor>,
19233        cx: &mut App,
19234    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19235        Some(self.update(cx, |project, cx| {
19236            project.inlay_hints(buffer_handle, range, cx)
19237        }))
19238    }
19239
19240    fn resolve_inlay_hint(
19241        &self,
19242        hint: InlayHint,
19243        buffer_handle: Entity<Buffer>,
19244        server_id: LanguageServerId,
19245        cx: &mut App,
19246    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19247        Some(self.update(cx, |project, cx| {
19248            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19249        }))
19250    }
19251
19252    fn range_for_rename(
19253        &self,
19254        buffer: &Entity<Buffer>,
19255        position: text::Anchor,
19256        cx: &mut App,
19257    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19258        Some(self.update(cx, |project, cx| {
19259            let buffer = buffer.clone();
19260            let task = project.prepare_rename(buffer.clone(), position, cx);
19261            cx.spawn(async move |_, cx| {
19262                Ok(match task.await? {
19263                    PrepareRenameResponse::Success(range) => Some(range),
19264                    PrepareRenameResponse::InvalidPosition => None,
19265                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19266                        // Fallback on using TreeSitter info to determine identifier range
19267                        buffer.update(cx, |buffer, _| {
19268                            let snapshot = buffer.snapshot();
19269                            let (range, kind) = snapshot.surrounding_word(position);
19270                            if kind != Some(CharKind::Word) {
19271                                return None;
19272                            }
19273                            Some(
19274                                snapshot.anchor_before(range.start)
19275                                    ..snapshot.anchor_after(range.end),
19276                            )
19277                        })?
19278                    }
19279                })
19280            })
19281        }))
19282    }
19283
19284    fn perform_rename(
19285        &self,
19286        buffer: &Entity<Buffer>,
19287        position: text::Anchor,
19288        new_name: String,
19289        cx: &mut App,
19290    ) -> Option<Task<Result<ProjectTransaction>>> {
19291        Some(self.update(cx, |project, cx| {
19292            project.perform_rename(buffer.clone(), position, new_name, cx)
19293        }))
19294    }
19295}
19296
19297fn inlay_hint_settings(
19298    location: Anchor,
19299    snapshot: &MultiBufferSnapshot,
19300    cx: &mut Context<Editor>,
19301) -> InlayHintSettings {
19302    let file = snapshot.file_at(location);
19303    let language = snapshot.language_at(location).map(|l| l.name());
19304    language_settings(language, file, cx).inlay_hints
19305}
19306
19307fn consume_contiguous_rows(
19308    contiguous_row_selections: &mut Vec<Selection<Point>>,
19309    selection: &Selection<Point>,
19310    display_map: &DisplaySnapshot,
19311    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19312) -> (MultiBufferRow, MultiBufferRow) {
19313    contiguous_row_selections.push(selection.clone());
19314    let start_row = MultiBufferRow(selection.start.row);
19315    let mut end_row = ending_row(selection, display_map);
19316
19317    while let Some(next_selection) = selections.peek() {
19318        if next_selection.start.row <= end_row.0 {
19319            end_row = ending_row(next_selection, display_map);
19320            contiguous_row_selections.push(selections.next().unwrap().clone());
19321        } else {
19322            break;
19323        }
19324    }
19325    (start_row, end_row)
19326}
19327
19328fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19329    if next_selection.end.column > 0 || next_selection.is_empty() {
19330        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19331    } else {
19332        MultiBufferRow(next_selection.end.row)
19333    }
19334}
19335
19336impl EditorSnapshot {
19337    pub fn remote_selections_in_range<'a>(
19338        &'a self,
19339        range: &'a Range<Anchor>,
19340        collaboration_hub: &dyn CollaborationHub,
19341        cx: &'a App,
19342    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19343        let participant_names = collaboration_hub.user_names(cx);
19344        let participant_indices = collaboration_hub.user_participant_indices(cx);
19345        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19346        let collaborators_by_replica_id = collaborators_by_peer_id
19347            .iter()
19348            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19349            .collect::<HashMap<_, _>>();
19350        self.buffer_snapshot
19351            .selections_in_range(range, false)
19352            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19353                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19354                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19355                let user_name = participant_names.get(&collaborator.user_id).cloned();
19356                Some(RemoteSelection {
19357                    replica_id,
19358                    selection,
19359                    cursor_shape,
19360                    line_mode,
19361                    participant_index,
19362                    peer_id: collaborator.peer_id,
19363                    user_name,
19364                })
19365            })
19366    }
19367
19368    pub fn hunks_for_ranges(
19369        &self,
19370        ranges: impl IntoIterator<Item = Range<Point>>,
19371    ) -> Vec<MultiBufferDiffHunk> {
19372        let mut hunks = Vec::new();
19373        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19374            HashMap::default();
19375        for query_range in ranges {
19376            let query_rows =
19377                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19378            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19379                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19380            ) {
19381                // Include deleted hunks that are adjacent to the query range, because
19382                // otherwise they would be missed.
19383                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19384                if hunk.status().is_deleted() {
19385                    intersects_range |= hunk.row_range.start == query_rows.end;
19386                    intersects_range |= hunk.row_range.end == query_rows.start;
19387                }
19388                if intersects_range {
19389                    if !processed_buffer_rows
19390                        .entry(hunk.buffer_id)
19391                        .or_default()
19392                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19393                    {
19394                        continue;
19395                    }
19396                    hunks.push(hunk);
19397                }
19398            }
19399        }
19400
19401        hunks
19402    }
19403
19404    fn display_diff_hunks_for_rows<'a>(
19405        &'a self,
19406        display_rows: Range<DisplayRow>,
19407        folded_buffers: &'a HashSet<BufferId>,
19408    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19409        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19410        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19411
19412        self.buffer_snapshot
19413            .diff_hunks_in_range(buffer_start..buffer_end)
19414            .filter_map(|hunk| {
19415                if folded_buffers.contains(&hunk.buffer_id) {
19416                    return None;
19417                }
19418
19419                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19420                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19421
19422                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19423                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19424
19425                let display_hunk = if hunk_display_start.column() != 0 {
19426                    DisplayDiffHunk::Folded {
19427                        display_row: hunk_display_start.row(),
19428                    }
19429                } else {
19430                    let mut end_row = hunk_display_end.row();
19431                    if hunk_display_end.column() > 0 {
19432                        end_row.0 += 1;
19433                    }
19434                    let is_created_file = hunk.is_created_file();
19435                    DisplayDiffHunk::Unfolded {
19436                        status: hunk.status(),
19437                        diff_base_byte_range: hunk.diff_base_byte_range,
19438                        display_row_range: hunk_display_start.row()..end_row,
19439                        multi_buffer_range: Anchor::range_in_buffer(
19440                            hunk.excerpt_id,
19441                            hunk.buffer_id,
19442                            hunk.buffer_range,
19443                        ),
19444                        is_created_file,
19445                    }
19446                };
19447
19448                Some(display_hunk)
19449            })
19450    }
19451
19452    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19453        self.display_snapshot.buffer_snapshot.language_at(position)
19454    }
19455
19456    pub fn is_focused(&self) -> bool {
19457        self.is_focused
19458    }
19459
19460    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19461        self.placeholder_text.as_ref()
19462    }
19463
19464    pub fn scroll_position(&self) -> gpui::Point<f32> {
19465        self.scroll_anchor.scroll_position(&self.display_snapshot)
19466    }
19467
19468    fn gutter_dimensions(
19469        &self,
19470        font_id: FontId,
19471        font_size: Pixels,
19472        max_line_number_width: Pixels,
19473        cx: &App,
19474    ) -> Option<GutterDimensions> {
19475        if !self.show_gutter {
19476            return None;
19477        }
19478
19479        let descent = cx.text_system().descent(font_id, font_size);
19480        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19481        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19482
19483        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19484            matches!(
19485                ProjectSettings::get_global(cx).git.git_gutter,
19486                Some(GitGutterSetting::TrackedFiles)
19487            )
19488        });
19489        let gutter_settings = EditorSettings::get_global(cx).gutter;
19490        let show_line_numbers = self
19491            .show_line_numbers
19492            .unwrap_or(gutter_settings.line_numbers);
19493        let line_gutter_width = if show_line_numbers {
19494            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19495            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19496            max_line_number_width.max(min_width_for_number_on_gutter)
19497        } else {
19498            0.0.into()
19499        };
19500
19501        let show_code_actions = self
19502            .show_code_actions
19503            .unwrap_or(gutter_settings.code_actions);
19504
19505        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19506        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19507
19508        let git_blame_entries_width =
19509            self.git_blame_gutter_max_author_length
19510                .map(|max_author_length| {
19511                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19512                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19513
19514                    /// The number of characters to dedicate to gaps and margins.
19515                    const SPACING_WIDTH: usize = 4;
19516
19517                    let max_char_count = max_author_length.min(renderer.max_author_length())
19518                        + ::git::SHORT_SHA_LENGTH
19519                        + MAX_RELATIVE_TIMESTAMP.len()
19520                        + SPACING_WIDTH;
19521
19522                    em_advance * max_char_count
19523                });
19524
19525        let is_singleton = self.buffer_snapshot.is_singleton();
19526
19527        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19528        left_padding += if !is_singleton {
19529            em_width * 4.0
19530        } else if show_code_actions || show_runnables || show_breakpoints {
19531            em_width * 3.0
19532        } else if show_git_gutter && show_line_numbers {
19533            em_width * 2.0
19534        } else if show_git_gutter || show_line_numbers {
19535            em_width
19536        } else {
19537            px(0.)
19538        };
19539
19540        let shows_folds = is_singleton && gutter_settings.folds;
19541
19542        let right_padding = if shows_folds && show_line_numbers {
19543            em_width * 4.0
19544        } else if shows_folds || (!is_singleton && show_line_numbers) {
19545            em_width * 3.0
19546        } else if show_line_numbers {
19547            em_width
19548        } else {
19549            px(0.)
19550        };
19551
19552        Some(GutterDimensions {
19553            left_padding,
19554            right_padding,
19555            width: line_gutter_width + left_padding + right_padding,
19556            margin: -descent,
19557            git_blame_entries_width,
19558        })
19559    }
19560
19561    pub fn render_crease_toggle(
19562        &self,
19563        buffer_row: MultiBufferRow,
19564        row_contains_cursor: bool,
19565        editor: Entity<Editor>,
19566        window: &mut Window,
19567        cx: &mut App,
19568    ) -> Option<AnyElement> {
19569        let folded = self.is_line_folded(buffer_row);
19570        let mut is_foldable = false;
19571
19572        if let Some(crease) = self
19573            .crease_snapshot
19574            .query_row(buffer_row, &self.buffer_snapshot)
19575        {
19576            is_foldable = true;
19577            match crease {
19578                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19579                    if let Some(render_toggle) = render_toggle {
19580                        let toggle_callback =
19581                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19582                                if folded {
19583                                    editor.update(cx, |editor, cx| {
19584                                        editor.fold_at(buffer_row, window, cx)
19585                                    });
19586                                } else {
19587                                    editor.update(cx, |editor, cx| {
19588                                        editor.unfold_at(buffer_row, window, cx)
19589                                    });
19590                                }
19591                            });
19592                        return Some((render_toggle)(
19593                            buffer_row,
19594                            folded,
19595                            toggle_callback,
19596                            window,
19597                            cx,
19598                        ));
19599                    }
19600                }
19601            }
19602        }
19603
19604        is_foldable |= self.starts_indent(buffer_row);
19605
19606        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19607            Some(
19608                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19609                    .toggle_state(folded)
19610                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19611                        if folded {
19612                            this.unfold_at(buffer_row, window, cx);
19613                        } else {
19614                            this.fold_at(buffer_row, window, cx);
19615                        }
19616                    }))
19617                    .into_any_element(),
19618            )
19619        } else {
19620            None
19621        }
19622    }
19623
19624    pub fn render_crease_trailer(
19625        &self,
19626        buffer_row: MultiBufferRow,
19627        window: &mut Window,
19628        cx: &mut App,
19629    ) -> Option<AnyElement> {
19630        let folded = self.is_line_folded(buffer_row);
19631        if let Crease::Inline { render_trailer, .. } = self
19632            .crease_snapshot
19633            .query_row(buffer_row, &self.buffer_snapshot)?
19634        {
19635            let render_trailer = render_trailer.as_ref()?;
19636            Some(render_trailer(buffer_row, folded, window, cx))
19637        } else {
19638            None
19639        }
19640    }
19641}
19642
19643impl Deref for EditorSnapshot {
19644    type Target = DisplaySnapshot;
19645
19646    fn deref(&self) -> &Self::Target {
19647        &self.display_snapshot
19648    }
19649}
19650
19651#[derive(Clone, Debug, PartialEq, Eq)]
19652pub enum EditorEvent {
19653    InputIgnored {
19654        text: Arc<str>,
19655    },
19656    InputHandled {
19657        utf16_range_to_replace: Option<Range<isize>>,
19658        text: Arc<str>,
19659    },
19660    ExcerptsAdded {
19661        buffer: Entity<Buffer>,
19662        predecessor: ExcerptId,
19663        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19664    },
19665    ExcerptsRemoved {
19666        ids: Vec<ExcerptId>,
19667    },
19668    BufferFoldToggled {
19669        ids: Vec<ExcerptId>,
19670        folded: bool,
19671    },
19672    ExcerptsEdited {
19673        ids: Vec<ExcerptId>,
19674    },
19675    ExcerptsExpanded {
19676        ids: Vec<ExcerptId>,
19677    },
19678    BufferEdited,
19679    Edited {
19680        transaction_id: clock::Lamport,
19681    },
19682    Reparsed(BufferId),
19683    Focused,
19684    FocusedIn,
19685    Blurred,
19686    DirtyChanged,
19687    Saved,
19688    TitleChanged,
19689    DiffBaseChanged,
19690    SelectionsChanged {
19691        local: bool,
19692    },
19693    ScrollPositionChanged {
19694        local: bool,
19695        autoscroll: bool,
19696    },
19697    Closed,
19698    TransactionUndone {
19699        transaction_id: clock::Lamport,
19700    },
19701    TransactionBegun {
19702        transaction_id: clock::Lamport,
19703    },
19704    Reloaded,
19705    CursorShapeChanged,
19706    PushedToNavHistory {
19707        anchor: Anchor,
19708        is_deactivate: bool,
19709    },
19710}
19711
19712impl EventEmitter<EditorEvent> for Editor {}
19713
19714impl Focusable for Editor {
19715    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19716        self.focus_handle.clone()
19717    }
19718}
19719
19720impl Render for Editor {
19721    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19722        let settings = ThemeSettings::get_global(cx);
19723
19724        let mut text_style = match self.mode {
19725            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19726                color: cx.theme().colors().editor_foreground,
19727                font_family: settings.ui_font.family.clone(),
19728                font_features: settings.ui_font.features.clone(),
19729                font_fallbacks: settings.ui_font.fallbacks.clone(),
19730                font_size: rems(0.875).into(),
19731                font_weight: settings.ui_font.weight,
19732                line_height: relative(settings.buffer_line_height.value()),
19733                ..Default::default()
19734            },
19735            EditorMode::Full { .. } => TextStyle {
19736                color: cx.theme().colors().editor_foreground,
19737                font_family: settings.buffer_font.family.clone(),
19738                font_features: settings.buffer_font.features.clone(),
19739                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19740                font_size: settings.buffer_font_size(cx).into(),
19741                font_weight: settings.buffer_font.weight,
19742                line_height: relative(settings.buffer_line_height.value()),
19743                ..Default::default()
19744            },
19745        };
19746        if let Some(text_style_refinement) = &self.text_style_refinement {
19747            text_style.refine(text_style_refinement)
19748        }
19749
19750        let background = match self.mode {
19751            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19752            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19753            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19754        };
19755
19756        EditorElement::new(
19757            &cx.entity(),
19758            EditorStyle {
19759                background,
19760                local_player: cx.theme().players().local(),
19761                text: text_style,
19762                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19763                syntax: cx.theme().syntax().clone(),
19764                status: cx.theme().status().clone(),
19765                inlay_hints_style: make_inlay_hints_style(cx),
19766                inline_completion_styles: make_suggestion_styles(cx),
19767                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19768            },
19769        )
19770    }
19771}
19772
19773impl EntityInputHandler for Editor {
19774    fn text_for_range(
19775        &mut self,
19776        range_utf16: Range<usize>,
19777        adjusted_range: &mut Option<Range<usize>>,
19778        _: &mut Window,
19779        cx: &mut Context<Self>,
19780    ) -> Option<String> {
19781        let snapshot = self.buffer.read(cx).read(cx);
19782        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19783        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19784        if (start.0..end.0) != range_utf16 {
19785            adjusted_range.replace(start.0..end.0);
19786        }
19787        Some(snapshot.text_for_range(start..end).collect())
19788    }
19789
19790    fn selected_text_range(
19791        &mut self,
19792        ignore_disabled_input: bool,
19793        _: &mut Window,
19794        cx: &mut Context<Self>,
19795    ) -> Option<UTF16Selection> {
19796        // Prevent the IME menu from appearing when holding down an alphabetic key
19797        // while input is disabled.
19798        if !ignore_disabled_input && !self.input_enabled {
19799            return None;
19800        }
19801
19802        let selection = self.selections.newest::<OffsetUtf16>(cx);
19803        let range = selection.range();
19804
19805        Some(UTF16Selection {
19806            range: range.start.0..range.end.0,
19807            reversed: selection.reversed,
19808        })
19809    }
19810
19811    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19812        let snapshot = self.buffer.read(cx).read(cx);
19813        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19814        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19815    }
19816
19817    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19818        self.clear_highlights::<InputComposition>(cx);
19819        self.ime_transaction.take();
19820    }
19821
19822    fn replace_text_in_range(
19823        &mut self,
19824        range_utf16: Option<Range<usize>>,
19825        text: &str,
19826        window: &mut Window,
19827        cx: &mut Context<Self>,
19828    ) {
19829        if !self.input_enabled {
19830            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19831            return;
19832        }
19833
19834        self.transact(window, cx, |this, window, cx| {
19835            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19836                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19837                Some(this.selection_replacement_ranges(range_utf16, cx))
19838            } else {
19839                this.marked_text_ranges(cx)
19840            };
19841
19842            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19843                let newest_selection_id = this.selections.newest_anchor().id;
19844                this.selections
19845                    .all::<OffsetUtf16>(cx)
19846                    .iter()
19847                    .zip(ranges_to_replace.iter())
19848                    .find_map(|(selection, range)| {
19849                        if selection.id == newest_selection_id {
19850                            Some(
19851                                (range.start.0 as isize - selection.head().0 as isize)
19852                                    ..(range.end.0 as isize - selection.head().0 as isize),
19853                            )
19854                        } else {
19855                            None
19856                        }
19857                    })
19858            });
19859
19860            cx.emit(EditorEvent::InputHandled {
19861                utf16_range_to_replace: range_to_replace,
19862                text: text.into(),
19863            });
19864
19865            if let Some(new_selected_ranges) = new_selected_ranges {
19866                this.change_selections(None, window, cx, |selections| {
19867                    selections.select_ranges(new_selected_ranges)
19868                });
19869                this.backspace(&Default::default(), window, cx);
19870            }
19871
19872            this.handle_input(text, window, cx);
19873        });
19874
19875        if let Some(transaction) = self.ime_transaction {
19876            self.buffer.update(cx, |buffer, cx| {
19877                buffer.group_until_transaction(transaction, cx);
19878            });
19879        }
19880
19881        self.unmark_text(window, cx);
19882    }
19883
19884    fn replace_and_mark_text_in_range(
19885        &mut self,
19886        range_utf16: Option<Range<usize>>,
19887        text: &str,
19888        new_selected_range_utf16: Option<Range<usize>>,
19889        window: &mut Window,
19890        cx: &mut Context<Self>,
19891    ) {
19892        if !self.input_enabled {
19893            return;
19894        }
19895
19896        let transaction = self.transact(window, cx, |this, window, cx| {
19897            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19898                let snapshot = this.buffer.read(cx).read(cx);
19899                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19900                    for marked_range in &mut marked_ranges {
19901                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19902                        marked_range.start.0 += relative_range_utf16.start;
19903                        marked_range.start =
19904                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19905                        marked_range.end =
19906                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19907                    }
19908                }
19909                Some(marked_ranges)
19910            } else if let Some(range_utf16) = range_utf16 {
19911                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19912                Some(this.selection_replacement_ranges(range_utf16, cx))
19913            } else {
19914                None
19915            };
19916
19917            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19918                let newest_selection_id = this.selections.newest_anchor().id;
19919                this.selections
19920                    .all::<OffsetUtf16>(cx)
19921                    .iter()
19922                    .zip(ranges_to_replace.iter())
19923                    .find_map(|(selection, range)| {
19924                        if selection.id == newest_selection_id {
19925                            Some(
19926                                (range.start.0 as isize - selection.head().0 as isize)
19927                                    ..(range.end.0 as isize - selection.head().0 as isize),
19928                            )
19929                        } else {
19930                            None
19931                        }
19932                    })
19933            });
19934
19935            cx.emit(EditorEvent::InputHandled {
19936                utf16_range_to_replace: range_to_replace,
19937                text: text.into(),
19938            });
19939
19940            if let Some(ranges) = ranges_to_replace {
19941                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19942            }
19943
19944            let marked_ranges = {
19945                let snapshot = this.buffer.read(cx).read(cx);
19946                this.selections
19947                    .disjoint_anchors()
19948                    .iter()
19949                    .map(|selection| {
19950                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19951                    })
19952                    .collect::<Vec<_>>()
19953            };
19954
19955            if text.is_empty() {
19956                this.unmark_text(window, cx);
19957            } else {
19958                this.highlight_text::<InputComposition>(
19959                    marked_ranges.clone(),
19960                    HighlightStyle {
19961                        underline: Some(UnderlineStyle {
19962                            thickness: px(1.),
19963                            color: None,
19964                            wavy: false,
19965                        }),
19966                        ..Default::default()
19967                    },
19968                    cx,
19969                );
19970            }
19971
19972            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19973            let use_autoclose = this.use_autoclose;
19974            let use_auto_surround = this.use_auto_surround;
19975            this.set_use_autoclose(false);
19976            this.set_use_auto_surround(false);
19977            this.handle_input(text, window, cx);
19978            this.set_use_autoclose(use_autoclose);
19979            this.set_use_auto_surround(use_auto_surround);
19980
19981            if let Some(new_selected_range) = new_selected_range_utf16 {
19982                let snapshot = this.buffer.read(cx).read(cx);
19983                let new_selected_ranges = marked_ranges
19984                    .into_iter()
19985                    .map(|marked_range| {
19986                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19987                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19988                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19989                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19990                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19991                    })
19992                    .collect::<Vec<_>>();
19993
19994                drop(snapshot);
19995                this.change_selections(None, window, cx, |selections| {
19996                    selections.select_ranges(new_selected_ranges)
19997                });
19998            }
19999        });
20000
20001        self.ime_transaction = self.ime_transaction.or(transaction);
20002        if let Some(transaction) = self.ime_transaction {
20003            self.buffer.update(cx, |buffer, cx| {
20004                buffer.group_until_transaction(transaction, cx);
20005            });
20006        }
20007
20008        if self.text_highlights::<InputComposition>(cx).is_none() {
20009            self.ime_transaction.take();
20010        }
20011    }
20012
20013    fn bounds_for_range(
20014        &mut self,
20015        range_utf16: Range<usize>,
20016        element_bounds: gpui::Bounds<Pixels>,
20017        window: &mut Window,
20018        cx: &mut Context<Self>,
20019    ) -> Option<gpui::Bounds<Pixels>> {
20020        let text_layout_details = self.text_layout_details(window);
20021        let gpui::Size {
20022            width: em_width,
20023            height: line_height,
20024        } = self.character_size(window);
20025
20026        let snapshot = self.snapshot(window, cx);
20027        let scroll_position = snapshot.scroll_position();
20028        let scroll_left = scroll_position.x * em_width;
20029
20030        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20031        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20032            + self.gutter_dimensions.width
20033            + self.gutter_dimensions.margin;
20034        let y = line_height * (start.row().as_f32() - scroll_position.y);
20035
20036        Some(Bounds {
20037            origin: element_bounds.origin + point(x, y),
20038            size: size(em_width, line_height),
20039        })
20040    }
20041
20042    fn character_index_for_point(
20043        &mut self,
20044        point: gpui::Point<Pixels>,
20045        _window: &mut Window,
20046        _cx: &mut Context<Self>,
20047    ) -> Option<usize> {
20048        let position_map = self.last_position_map.as_ref()?;
20049        if !position_map.text_hitbox.contains(&point) {
20050            return None;
20051        }
20052        let display_point = position_map.point_for_position(point).previous_valid;
20053        let anchor = position_map
20054            .snapshot
20055            .display_point_to_anchor(display_point, Bias::Left);
20056        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20057        Some(utf16_offset.0)
20058    }
20059}
20060
20061trait SelectionExt {
20062    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20063    fn spanned_rows(
20064        &self,
20065        include_end_if_at_line_start: bool,
20066        map: &DisplaySnapshot,
20067    ) -> Range<MultiBufferRow>;
20068}
20069
20070impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20071    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20072        let start = self
20073            .start
20074            .to_point(&map.buffer_snapshot)
20075            .to_display_point(map);
20076        let end = self
20077            .end
20078            .to_point(&map.buffer_snapshot)
20079            .to_display_point(map);
20080        if self.reversed {
20081            end..start
20082        } else {
20083            start..end
20084        }
20085    }
20086
20087    fn spanned_rows(
20088        &self,
20089        include_end_if_at_line_start: bool,
20090        map: &DisplaySnapshot,
20091    ) -> Range<MultiBufferRow> {
20092        let start = self.start.to_point(&map.buffer_snapshot);
20093        let mut end = self.end.to_point(&map.buffer_snapshot);
20094        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20095            end.row -= 1;
20096        }
20097
20098        let buffer_start = map.prev_line_boundary(start).0;
20099        let buffer_end = map.next_line_boundary(end).0;
20100        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20101    }
20102}
20103
20104impl<T: InvalidationRegion> InvalidationStack<T> {
20105    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20106    where
20107        S: Clone + ToOffset,
20108    {
20109        while let Some(region) = self.last() {
20110            let all_selections_inside_invalidation_ranges =
20111                if selections.len() == region.ranges().len() {
20112                    selections
20113                        .iter()
20114                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20115                        .all(|(selection, invalidation_range)| {
20116                            let head = selection.head().to_offset(buffer);
20117                            invalidation_range.start <= head && invalidation_range.end >= head
20118                        })
20119                } else {
20120                    false
20121                };
20122
20123            if all_selections_inside_invalidation_ranges {
20124                break;
20125            } else {
20126                self.pop();
20127            }
20128        }
20129    }
20130}
20131
20132impl<T> Default for InvalidationStack<T> {
20133    fn default() -> Self {
20134        Self(Default::default())
20135    }
20136}
20137
20138impl<T> Deref for InvalidationStack<T> {
20139    type Target = Vec<T>;
20140
20141    fn deref(&self) -> &Self::Target {
20142        &self.0
20143    }
20144}
20145
20146impl<T> DerefMut for InvalidationStack<T> {
20147    fn deref_mut(&mut self) -> &mut Self::Target {
20148        &mut self.0
20149    }
20150}
20151
20152impl InvalidationRegion for SnippetState {
20153    fn ranges(&self) -> &[Range<Anchor>] {
20154        &self.ranges[self.active_index]
20155    }
20156}
20157
20158fn inline_completion_edit_text(
20159    current_snapshot: &BufferSnapshot,
20160    edits: &[(Range<Anchor>, String)],
20161    edit_preview: &EditPreview,
20162    include_deletions: bool,
20163    cx: &App,
20164) -> HighlightedText {
20165    let edits = edits
20166        .iter()
20167        .map(|(anchor, text)| {
20168            (
20169                anchor.start.text_anchor..anchor.end.text_anchor,
20170                text.clone(),
20171            )
20172        })
20173        .collect::<Vec<_>>();
20174
20175    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20176}
20177
20178pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20179    match severity {
20180        DiagnosticSeverity::ERROR => colors.error,
20181        DiagnosticSeverity::WARNING => colors.warning,
20182        DiagnosticSeverity::INFORMATION => colors.info,
20183        DiagnosticSeverity::HINT => colors.info,
20184        _ => colors.ignored,
20185    }
20186}
20187
20188pub fn styled_runs_for_code_label<'a>(
20189    label: &'a CodeLabel,
20190    syntax_theme: &'a theme::SyntaxTheme,
20191) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20192    let fade_out = HighlightStyle {
20193        fade_out: Some(0.35),
20194        ..Default::default()
20195    };
20196
20197    let mut prev_end = label.filter_range.end;
20198    label
20199        .runs
20200        .iter()
20201        .enumerate()
20202        .flat_map(move |(ix, (range, highlight_id))| {
20203            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20204                style
20205            } else {
20206                return Default::default();
20207            };
20208            let mut muted_style = style;
20209            muted_style.highlight(fade_out);
20210
20211            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20212            if range.start >= label.filter_range.end {
20213                if range.start > prev_end {
20214                    runs.push((prev_end..range.start, fade_out));
20215                }
20216                runs.push((range.clone(), muted_style));
20217            } else if range.end <= label.filter_range.end {
20218                runs.push((range.clone(), style));
20219            } else {
20220                runs.push((range.start..label.filter_range.end, style));
20221                runs.push((label.filter_range.end..range.end, muted_style));
20222            }
20223            prev_end = cmp::max(prev_end, range.end);
20224
20225            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20226                runs.push((prev_end..label.text.len(), fade_out));
20227            }
20228
20229            runs
20230        })
20231}
20232
20233pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20234    let mut prev_index = 0;
20235    let mut prev_codepoint: Option<char> = None;
20236    text.char_indices()
20237        .chain([(text.len(), '\0')])
20238        .filter_map(move |(index, codepoint)| {
20239            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20240            let is_boundary = index == text.len()
20241                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20242                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20243            if is_boundary {
20244                let chunk = &text[prev_index..index];
20245                prev_index = index;
20246                Some(chunk)
20247            } else {
20248                None
20249            }
20250        })
20251}
20252
20253pub trait RangeToAnchorExt: Sized {
20254    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20255
20256    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20257        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20258        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20259    }
20260}
20261
20262impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20263    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20264        let start_offset = self.start.to_offset(snapshot);
20265        let end_offset = self.end.to_offset(snapshot);
20266        if start_offset == end_offset {
20267            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20268        } else {
20269            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20270        }
20271    }
20272}
20273
20274pub trait RowExt {
20275    fn as_f32(&self) -> f32;
20276
20277    fn next_row(&self) -> Self;
20278
20279    fn previous_row(&self) -> Self;
20280
20281    fn minus(&self, other: Self) -> u32;
20282}
20283
20284impl RowExt for DisplayRow {
20285    fn as_f32(&self) -> f32 {
20286        self.0 as f32
20287    }
20288
20289    fn next_row(&self) -> Self {
20290        Self(self.0 + 1)
20291    }
20292
20293    fn previous_row(&self) -> Self {
20294        Self(self.0.saturating_sub(1))
20295    }
20296
20297    fn minus(&self, other: Self) -> u32 {
20298        self.0 - other.0
20299    }
20300}
20301
20302impl RowExt for MultiBufferRow {
20303    fn as_f32(&self) -> f32 {
20304        self.0 as f32
20305    }
20306
20307    fn next_row(&self) -> Self {
20308        Self(self.0 + 1)
20309    }
20310
20311    fn previous_row(&self) -> Self {
20312        Self(self.0.saturating_sub(1))
20313    }
20314
20315    fn minus(&self, other: Self) -> u32 {
20316        self.0 - other.0
20317    }
20318}
20319
20320trait RowRangeExt {
20321    type Row;
20322
20323    fn len(&self) -> usize;
20324
20325    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20326}
20327
20328impl RowRangeExt for Range<MultiBufferRow> {
20329    type Row = MultiBufferRow;
20330
20331    fn len(&self) -> usize {
20332        (self.end.0 - self.start.0) as usize
20333    }
20334
20335    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20336        (self.start.0..self.end.0).map(MultiBufferRow)
20337    }
20338}
20339
20340impl RowRangeExt for Range<DisplayRow> {
20341    type Row = DisplayRow;
20342
20343    fn len(&self) -> usize {
20344        (self.end.0 - self.start.0) as usize
20345    }
20346
20347    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20348        (self.start.0..self.end.0).map(DisplayRow)
20349    }
20350}
20351
20352/// If select range has more than one line, we
20353/// just point the cursor to range.start.
20354fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20355    if range.start.row == range.end.row {
20356        range
20357    } else {
20358        range.start..range.start
20359    }
20360}
20361pub struct KillRing(ClipboardItem);
20362impl Global for KillRing {}
20363
20364const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20365
20366enum BreakpointPromptEditAction {
20367    Log,
20368    Condition,
20369    HitCondition,
20370}
20371
20372struct BreakpointPromptEditor {
20373    pub(crate) prompt: Entity<Editor>,
20374    editor: WeakEntity<Editor>,
20375    breakpoint_anchor: Anchor,
20376    breakpoint: Breakpoint,
20377    edit_action: BreakpointPromptEditAction,
20378    block_ids: HashSet<CustomBlockId>,
20379    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20380    _subscriptions: Vec<Subscription>,
20381}
20382
20383impl BreakpointPromptEditor {
20384    const MAX_LINES: u8 = 4;
20385
20386    fn new(
20387        editor: WeakEntity<Editor>,
20388        breakpoint_anchor: Anchor,
20389        breakpoint: Breakpoint,
20390        edit_action: BreakpointPromptEditAction,
20391        window: &mut Window,
20392        cx: &mut Context<Self>,
20393    ) -> Self {
20394        let base_text = match edit_action {
20395            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20396            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20397            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20398        }
20399        .map(|msg| msg.to_string())
20400        .unwrap_or_default();
20401
20402        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20403        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20404
20405        let prompt = cx.new(|cx| {
20406            let mut prompt = Editor::new(
20407                EditorMode::AutoHeight {
20408                    max_lines: Self::MAX_LINES as usize,
20409                },
20410                buffer,
20411                None,
20412                window,
20413                cx,
20414            );
20415            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20416            prompt.set_show_cursor_when_unfocused(false, cx);
20417            prompt.set_placeholder_text(
20418                match edit_action {
20419                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20420                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20421                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20422                },
20423                cx,
20424            );
20425
20426            prompt
20427        });
20428
20429        Self {
20430            prompt,
20431            editor,
20432            breakpoint_anchor,
20433            breakpoint,
20434            edit_action,
20435            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20436            block_ids: Default::default(),
20437            _subscriptions: vec![],
20438        }
20439    }
20440
20441    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20442        self.block_ids.extend(block_ids)
20443    }
20444
20445    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20446        if let Some(editor) = self.editor.upgrade() {
20447            let message = self
20448                .prompt
20449                .read(cx)
20450                .buffer
20451                .read(cx)
20452                .as_singleton()
20453                .expect("A multi buffer in breakpoint prompt isn't possible")
20454                .read(cx)
20455                .as_rope()
20456                .to_string();
20457
20458            editor.update(cx, |editor, cx| {
20459                editor.edit_breakpoint_at_anchor(
20460                    self.breakpoint_anchor,
20461                    self.breakpoint.clone(),
20462                    match self.edit_action {
20463                        BreakpointPromptEditAction::Log => {
20464                            BreakpointEditAction::EditLogMessage(message.into())
20465                        }
20466                        BreakpointPromptEditAction::Condition => {
20467                            BreakpointEditAction::EditCondition(message.into())
20468                        }
20469                        BreakpointPromptEditAction::HitCondition => {
20470                            BreakpointEditAction::EditHitCondition(message.into())
20471                        }
20472                    },
20473                    cx,
20474                );
20475
20476                editor.remove_blocks(self.block_ids.clone(), None, cx);
20477                cx.focus_self(window);
20478            });
20479        }
20480    }
20481
20482    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20483        self.editor
20484            .update(cx, |editor, cx| {
20485                editor.remove_blocks(self.block_ids.clone(), None, cx);
20486                window.focus(&editor.focus_handle);
20487            })
20488            .log_err();
20489    }
20490
20491    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20492        let settings = ThemeSettings::get_global(cx);
20493        let text_style = TextStyle {
20494            color: if self.prompt.read(cx).read_only(cx) {
20495                cx.theme().colors().text_disabled
20496            } else {
20497                cx.theme().colors().text
20498            },
20499            font_family: settings.buffer_font.family.clone(),
20500            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20501            font_size: settings.buffer_font_size(cx).into(),
20502            font_weight: settings.buffer_font.weight,
20503            line_height: relative(settings.buffer_line_height.value()),
20504            ..Default::default()
20505        };
20506        EditorElement::new(
20507            &self.prompt,
20508            EditorStyle {
20509                background: cx.theme().colors().editor_background,
20510                local_player: cx.theme().players().local(),
20511                text: text_style,
20512                ..Default::default()
20513            },
20514        )
20515    }
20516}
20517
20518impl Render for BreakpointPromptEditor {
20519    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20520        let gutter_dimensions = *self.gutter_dimensions.lock();
20521        h_flex()
20522            .key_context("Editor")
20523            .bg(cx.theme().colors().editor_background)
20524            .border_y_1()
20525            .border_color(cx.theme().status().info_border)
20526            .size_full()
20527            .py(window.line_height() / 2.5)
20528            .on_action(cx.listener(Self::confirm))
20529            .on_action(cx.listener(Self::cancel))
20530            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20531            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20532    }
20533}
20534
20535impl Focusable for BreakpointPromptEditor {
20536    fn focus_handle(&self, cx: &App) -> FocusHandle {
20537        self.prompt.focus_handle(cx)
20538    }
20539}
20540
20541fn all_edits_insertions_or_deletions(
20542    edits: &Vec<(Range<Anchor>, String)>,
20543    snapshot: &MultiBufferSnapshot,
20544) -> bool {
20545    let mut all_insertions = true;
20546    let mut all_deletions = true;
20547
20548    for (range, new_text) in edits.iter() {
20549        let range_is_empty = range.to_offset(&snapshot).is_empty();
20550        let text_is_empty = new_text.is_empty();
20551
20552        if range_is_empty != text_is_empty {
20553            if range_is_empty {
20554                all_deletions = false;
20555            } else {
20556                all_insertions = false;
20557            }
20558        } else {
20559            return false;
20560        }
20561
20562        if !all_insertions && !all_deletions {
20563            return false;
20564        }
20565    }
20566    all_insertions || all_deletions
20567}
20568
20569struct MissingEditPredictionKeybindingTooltip;
20570
20571impl Render for MissingEditPredictionKeybindingTooltip {
20572    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20573        ui::tooltip_container(window, cx, |container, _, cx| {
20574            container
20575                .flex_shrink_0()
20576                .max_w_80()
20577                .min_h(rems_from_px(124.))
20578                .justify_between()
20579                .child(
20580                    v_flex()
20581                        .flex_1()
20582                        .text_ui_sm(cx)
20583                        .child(Label::new("Conflict with Accept Keybinding"))
20584                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20585                )
20586                .child(
20587                    h_flex()
20588                        .pb_1()
20589                        .gap_1()
20590                        .items_end()
20591                        .w_full()
20592                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20593                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20594                        }))
20595                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20596                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20597                        })),
20598                )
20599        })
20600    }
20601}
20602
20603#[derive(Debug, Clone, Copy, PartialEq)]
20604pub struct LineHighlight {
20605    pub background: Background,
20606    pub border: Option<gpui::Hsla>,
20607}
20608
20609impl From<Hsla> for LineHighlight {
20610    fn from(hsla: Hsla) -> Self {
20611        Self {
20612            background: hsla.into(),
20613            border: None,
20614        }
20615    }
20616}
20617
20618impl From<Background> for LineHighlight {
20619    fn from(background: Background) -> Self {
20620        Self {
20621            background,
20622            border: None,
20623        }
20624    }
20625}
20626
20627fn render_diff_hunk_controls(
20628    row: u32,
20629    status: &DiffHunkStatus,
20630    hunk_range: Range<Anchor>,
20631    is_created_file: bool,
20632    line_height: Pixels,
20633    editor: &Entity<Editor>,
20634    _window: &mut Window,
20635    cx: &mut App,
20636) -> AnyElement {
20637    h_flex()
20638        .h(line_height)
20639        .mr_1()
20640        .gap_1()
20641        .px_0p5()
20642        .pb_1()
20643        .border_x_1()
20644        .border_b_1()
20645        .border_color(cx.theme().colors().border_variant)
20646        .rounded_b_lg()
20647        .bg(cx.theme().colors().editor_background)
20648        .gap_1()
20649        .occlude()
20650        .shadow_md()
20651        .child(if status.has_secondary_hunk() {
20652            Button::new(("stage", row as u64), "Stage")
20653                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20654                .tooltip({
20655                    let focus_handle = editor.focus_handle(cx);
20656                    move |window, cx| {
20657                        Tooltip::for_action_in(
20658                            "Stage Hunk",
20659                            &::git::ToggleStaged,
20660                            &focus_handle,
20661                            window,
20662                            cx,
20663                        )
20664                    }
20665                })
20666                .on_click({
20667                    let editor = editor.clone();
20668                    move |_event, _window, cx| {
20669                        editor.update(cx, |editor, cx| {
20670                            editor.stage_or_unstage_diff_hunks(
20671                                true,
20672                                vec![hunk_range.start..hunk_range.start],
20673                                cx,
20674                            );
20675                        });
20676                    }
20677                })
20678        } else {
20679            Button::new(("unstage", row as u64), "Unstage")
20680                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20681                .tooltip({
20682                    let focus_handle = editor.focus_handle(cx);
20683                    move |window, cx| {
20684                        Tooltip::for_action_in(
20685                            "Unstage Hunk",
20686                            &::git::ToggleStaged,
20687                            &focus_handle,
20688                            window,
20689                            cx,
20690                        )
20691                    }
20692                })
20693                .on_click({
20694                    let editor = editor.clone();
20695                    move |_event, _window, cx| {
20696                        editor.update(cx, |editor, cx| {
20697                            editor.stage_or_unstage_diff_hunks(
20698                                false,
20699                                vec![hunk_range.start..hunk_range.start],
20700                                cx,
20701                            );
20702                        });
20703                    }
20704                })
20705        })
20706        .child(
20707            Button::new(("restore", row as u64), "Restore")
20708                .tooltip({
20709                    let focus_handle = editor.focus_handle(cx);
20710                    move |window, cx| {
20711                        Tooltip::for_action_in(
20712                            "Restore Hunk",
20713                            &::git::Restore,
20714                            &focus_handle,
20715                            window,
20716                            cx,
20717                        )
20718                    }
20719                })
20720                .on_click({
20721                    let editor = editor.clone();
20722                    move |_event, window, cx| {
20723                        editor.update(cx, |editor, cx| {
20724                            let snapshot = editor.snapshot(window, cx);
20725                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20726                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20727                        });
20728                    }
20729                })
20730                .disabled(is_created_file),
20731        )
20732        .when(
20733            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20734            |el| {
20735                el.child(
20736                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20737                        .shape(IconButtonShape::Square)
20738                        .icon_size(IconSize::Small)
20739                        // .disabled(!has_multiple_hunks)
20740                        .tooltip({
20741                            let focus_handle = editor.focus_handle(cx);
20742                            move |window, cx| {
20743                                Tooltip::for_action_in(
20744                                    "Next Hunk",
20745                                    &GoToHunk,
20746                                    &focus_handle,
20747                                    window,
20748                                    cx,
20749                                )
20750                            }
20751                        })
20752                        .on_click({
20753                            let editor = editor.clone();
20754                            move |_event, window, cx| {
20755                                editor.update(cx, |editor, cx| {
20756                                    let snapshot = editor.snapshot(window, cx);
20757                                    let position =
20758                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20759                                    editor.go_to_hunk_before_or_after_position(
20760                                        &snapshot,
20761                                        position,
20762                                        Direction::Next,
20763                                        window,
20764                                        cx,
20765                                    );
20766                                    editor.expand_selected_diff_hunks(cx);
20767                                });
20768                            }
20769                        }),
20770                )
20771                .child(
20772                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20773                        .shape(IconButtonShape::Square)
20774                        .icon_size(IconSize::Small)
20775                        // .disabled(!has_multiple_hunks)
20776                        .tooltip({
20777                            let focus_handle = editor.focus_handle(cx);
20778                            move |window, cx| {
20779                                Tooltip::for_action_in(
20780                                    "Previous Hunk",
20781                                    &GoToPreviousHunk,
20782                                    &focus_handle,
20783                                    window,
20784                                    cx,
20785                                )
20786                            }
20787                        })
20788                        .on_click({
20789                            let editor = editor.clone();
20790                            move |_event, window, cx| {
20791                                editor.update(cx, |editor, cx| {
20792                                    let snapshot = editor.snapshot(window, cx);
20793                                    let point =
20794                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20795                                    editor.go_to_hunk_before_or_after_position(
20796                                        &snapshot,
20797                                        point,
20798                                        Direction::Prev,
20799                                        window,
20800                                        cx,
20801                                    );
20802                                    editor.expand_selected_diff_hunks(cx);
20803                                });
20804                            }
20805                        }),
20806                )
20807            },
20808        )
20809        .into_any_element()
20810}