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_non_empty_selection(&self, cx: &mut App) -> bool {
 3039        self.selections
 3040            .all_adjusted(cx)
 3041            .iter()
 3042            .any(|selection| !selection.is_empty())
 3043    }
 3044
 3045    pub fn has_pending_nonempty_selection(&self) -> bool {
 3046        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3047            Some(Selection { start, end, .. }) => start != end,
 3048            None => false,
 3049        };
 3050
 3051        pending_nonempty_selection
 3052            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3053    }
 3054
 3055    pub fn has_pending_selection(&self) -> bool {
 3056        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3057    }
 3058
 3059    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3060        self.selection_mark_mode = false;
 3061
 3062        if self.clear_expanded_diff_hunks(cx) {
 3063            cx.notify();
 3064            return;
 3065        }
 3066        if self.dismiss_menus_and_popups(true, window, cx) {
 3067            return;
 3068        }
 3069
 3070        if self.mode.is_full()
 3071            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3072        {
 3073            return;
 3074        }
 3075
 3076        cx.propagate();
 3077    }
 3078
 3079    pub fn dismiss_menus_and_popups(
 3080        &mut self,
 3081        is_user_requested: bool,
 3082        window: &mut Window,
 3083        cx: &mut Context<Self>,
 3084    ) -> bool {
 3085        if self.take_rename(false, window, cx).is_some() {
 3086            return true;
 3087        }
 3088
 3089        if hide_hover(self, cx) {
 3090            return true;
 3091        }
 3092
 3093        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3094            return true;
 3095        }
 3096
 3097        if self.hide_context_menu(window, cx).is_some() {
 3098            return true;
 3099        }
 3100
 3101        if self.mouse_context_menu.take().is_some() {
 3102            return true;
 3103        }
 3104
 3105        if is_user_requested && self.discard_inline_completion(true, cx) {
 3106            return true;
 3107        }
 3108
 3109        if self.snippet_stack.pop().is_some() {
 3110            return true;
 3111        }
 3112
 3113        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3114            self.dismiss_diagnostics(cx);
 3115            return true;
 3116        }
 3117
 3118        false
 3119    }
 3120
 3121    fn linked_editing_ranges_for(
 3122        &self,
 3123        selection: Range<text::Anchor>,
 3124        cx: &App,
 3125    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3126        if self.linked_edit_ranges.is_empty() {
 3127            return None;
 3128        }
 3129        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3130            selection.end.buffer_id.and_then(|end_buffer_id| {
 3131                if selection.start.buffer_id != Some(end_buffer_id) {
 3132                    return None;
 3133                }
 3134                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3135                let snapshot = buffer.read(cx).snapshot();
 3136                self.linked_edit_ranges
 3137                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3138                    .map(|ranges| (ranges, snapshot, buffer))
 3139            })?;
 3140        use text::ToOffset as TO;
 3141        // find offset from the start of current range to current cursor position
 3142        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3143
 3144        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3145        let start_difference = start_offset - start_byte_offset;
 3146        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3147        let end_difference = end_offset - start_byte_offset;
 3148        // Current range has associated linked ranges.
 3149        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3150        for range in linked_ranges.iter() {
 3151            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3152            let end_offset = start_offset + end_difference;
 3153            let start_offset = start_offset + start_difference;
 3154            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3155                continue;
 3156            }
 3157            if self.selections.disjoint_anchor_ranges().any(|s| {
 3158                if s.start.buffer_id != selection.start.buffer_id
 3159                    || s.end.buffer_id != selection.end.buffer_id
 3160                {
 3161                    return false;
 3162                }
 3163                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3164                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3165            }) {
 3166                continue;
 3167            }
 3168            let start = buffer_snapshot.anchor_after(start_offset);
 3169            let end = buffer_snapshot.anchor_after(end_offset);
 3170            linked_edits
 3171                .entry(buffer.clone())
 3172                .or_default()
 3173                .push(start..end);
 3174        }
 3175        Some(linked_edits)
 3176    }
 3177
 3178    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3179        let text: Arc<str> = text.into();
 3180
 3181        if self.read_only(cx) {
 3182            return;
 3183        }
 3184
 3185        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3186
 3187        let selections = self.selections.all_adjusted(cx);
 3188        let mut bracket_inserted = false;
 3189        let mut edits = Vec::new();
 3190        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3191        let mut new_selections = Vec::with_capacity(selections.len());
 3192        let mut new_autoclose_regions = Vec::new();
 3193        let snapshot = self.buffer.read(cx).read(cx);
 3194        let mut clear_linked_edit_ranges = false;
 3195
 3196        for (selection, autoclose_region) in
 3197            self.selections_with_autoclose_regions(selections, &snapshot)
 3198        {
 3199            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3200                // Determine if the inserted text matches the opening or closing
 3201                // bracket of any of this language's bracket pairs.
 3202                let mut bracket_pair = None;
 3203                let mut is_bracket_pair_start = false;
 3204                let mut is_bracket_pair_end = false;
 3205                if !text.is_empty() {
 3206                    let mut bracket_pair_matching_end = None;
 3207                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3208                    //  and they are removing the character that triggered IME popup.
 3209                    for (pair, enabled) in scope.brackets() {
 3210                        if !pair.close && !pair.surround {
 3211                            continue;
 3212                        }
 3213
 3214                        if enabled && pair.start.ends_with(text.as_ref()) {
 3215                            let prefix_len = pair.start.len() - text.len();
 3216                            let preceding_text_matches_prefix = prefix_len == 0
 3217                                || (selection.start.column >= (prefix_len as u32)
 3218                                    && snapshot.contains_str_at(
 3219                                        Point::new(
 3220                                            selection.start.row,
 3221                                            selection.start.column - (prefix_len as u32),
 3222                                        ),
 3223                                        &pair.start[..prefix_len],
 3224                                    ));
 3225                            if preceding_text_matches_prefix {
 3226                                bracket_pair = Some(pair.clone());
 3227                                is_bracket_pair_start = true;
 3228                                break;
 3229                            }
 3230                        }
 3231                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3232                        {
 3233                            // take first bracket pair matching end, but don't break in case a later bracket
 3234                            // pair matches start
 3235                            bracket_pair_matching_end = Some(pair.clone());
 3236                        }
 3237                    }
 3238                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3239                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3240                        is_bracket_pair_end = true;
 3241                    }
 3242                }
 3243
 3244                if let Some(bracket_pair) = bracket_pair {
 3245                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3246                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3247                    let auto_surround =
 3248                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3249                    if selection.is_empty() {
 3250                        if is_bracket_pair_start {
 3251                            // If the inserted text is a suffix of an opening bracket and the
 3252                            // selection is preceded by the rest of the opening bracket, then
 3253                            // insert the closing bracket.
 3254                            let following_text_allows_autoclose = snapshot
 3255                                .chars_at(selection.start)
 3256                                .next()
 3257                                .map_or(true, |c| scope.should_autoclose_before(c));
 3258
 3259                            let preceding_text_allows_autoclose = selection.start.column == 0
 3260                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3261                                    true,
 3262                                    |c| {
 3263                                        bracket_pair.start != bracket_pair.end
 3264                                            || !snapshot
 3265                                                .char_classifier_at(selection.start)
 3266                                                .is_word(c)
 3267                                    },
 3268                                );
 3269
 3270                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3271                                && bracket_pair.start.len() == 1
 3272                            {
 3273                                let target = bracket_pair.start.chars().next().unwrap();
 3274                                let current_line_count = snapshot
 3275                                    .reversed_chars_at(selection.start)
 3276                                    .take_while(|&c| c != '\n')
 3277                                    .filter(|&c| c == target)
 3278                                    .count();
 3279                                current_line_count % 2 == 1
 3280                            } else {
 3281                                false
 3282                            };
 3283
 3284                            if autoclose
 3285                                && bracket_pair.close
 3286                                && following_text_allows_autoclose
 3287                                && preceding_text_allows_autoclose
 3288                                && !is_closing_quote
 3289                            {
 3290                                let anchor = snapshot.anchor_before(selection.end);
 3291                                new_selections.push((selection.map(|_| anchor), text.len()));
 3292                                new_autoclose_regions.push((
 3293                                    anchor,
 3294                                    text.len(),
 3295                                    selection.id,
 3296                                    bracket_pair.clone(),
 3297                                ));
 3298                                edits.push((
 3299                                    selection.range(),
 3300                                    format!("{}{}", text, bracket_pair.end).into(),
 3301                                ));
 3302                                bracket_inserted = true;
 3303                                continue;
 3304                            }
 3305                        }
 3306
 3307                        if let Some(region) = autoclose_region {
 3308                            // If the selection is followed by an auto-inserted closing bracket,
 3309                            // then don't insert that closing bracket again; just move the selection
 3310                            // past the closing bracket.
 3311                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3312                                && text.as_ref() == region.pair.end.as_str();
 3313                            if should_skip {
 3314                                let anchor = snapshot.anchor_after(selection.end);
 3315                                new_selections
 3316                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3317                                continue;
 3318                            }
 3319                        }
 3320
 3321                        let always_treat_brackets_as_autoclosed = snapshot
 3322                            .language_settings_at(selection.start, cx)
 3323                            .always_treat_brackets_as_autoclosed;
 3324                        if always_treat_brackets_as_autoclosed
 3325                            && is_bracket_pair_end
 3326                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3327                        {
 3328                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3329                            // and the inserted text is a closing bracket and the selection is followed
 3330                            // by the closing bracket then move the selection past the closing bracket.
 3331                            let anchor = snapshot.anchor_after(selection.end);
 3332                            new_selections.push((selection.map(|_| anchor), text.len()));
 3333                            continue;
 3334                        }
 3335                    }
 3336                    // If an opening bracket is 1 character long and is typed while
 3337                    // text is selected, then surround that text with the bracket pair.
 3338                    else if auto_surround
 3339                        && bracket_pair.surround
 3340                        && is_bracket_pair_start
 3341                        && bracket_pair.start.chars().count() == 1
 3342                    {
 3343                        edits.push((selection.start..selection.start, text.clone()));
 3344                        edits.push((
 3345                            selection.end..selection.end,
 3346                            bracket_pair.end.as_str().into(),
 3347                        ));
 3348                        bracket_inserted = true;
 3349                        new_selections.push((
 3350                            Selection {
 3351                                id: selection.id,
 3352                                start: snapshot.anchor_after(selection.start),
 3353                                end: snapshot.anchor_before(selection.end),
 3354                                reversed: selection.reversed,
 3355                                goal: selection.goal,
 3356                            },
 3357                            0,
 3358                        ));
 3359                        continue;
 3360                    }
 3361                }
 3362            }
 3363
 3364            if self.auto_replace_emoji_shortcode
 3365                && selection.is_empty()
 3366                && text.as_ref().ends_with(':')
 3367            {
 3368                if let Some(possible_emoji_short_code) =
 3369                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3370                {
 3371                    if !possible_emoji_short_code.is_empty() {
 3372                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3373                            let emoji_shortcode_start = Point::new(
 3374                                selection.start.row,
 3375                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3376                            );
 3377
 3378                            // Remove shortcode from buffer
 3379                            edits.push((
 3380                                emoji_shortcode_start..selection.start,
 3381                                "".to_string().into(),
 3382                            ));
 3383                            new_selections.push((
 3384                                Selection {
 3385                                    id: selection.id,
 3386                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3387                                    end: snapshot.anchor_before(selection.start),
 3388                                    reversed: selection.reversed,
 3389                                    goal: selection.goal,
 3390                                },
 3391                                0,
 3392                            ));
 3393
 3394                            // Insert emoji
 3395                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3396                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3397                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3398
 3399                            continue;
 3400                        }
 3401                    }
 3402                }
 3403            }
 3404
 3405            // If not handling any auto-close operation, then just replace the selected
 3406            // text with the given input and move the selection to the end of the
 3407            // newly inserted text.
 3408            let anchor = snapshot.anchor_after(selection.end);
 3409            if !self.linked_edit_ranges.is_empty() {
 3410                let start_anchor = snapshot.anchor_before(selection.start);
 3411
 3412                let is_word_char = text.chars().next().map_or(true, |char| {
 3413                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3414                    classifier.is_word(char)
 3415                });
 3416
 3417                if is_word_char {
 3418                    if let Some(ranges) = self
 3419                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3420                    {
 3421                        for (buffer, edits) in ranges {
 3422                            linked_edits
 3423                                .entry(buffer.clone())
 3424                                .or_default()
 3425                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3426                        }
 3427                    }
 3428                } else {
 3429                    clear_linked_edit_ranges = true;
 3430                }
 3431            }
 3432
 3433            new_selections.push((selection.map(|_| anchor), 0));
 3434            edits.push((selection.start..selection.end, text.clone()));
 3435        }
 3436
 3437        drop(snapshot);
 3438
 3439        self.transact(window, cx, |this, window, cx| {
 3440            if clear_linked_edit_ranges {
 3441                this.linked_edit_ranges.clear();
 3442            }
 3443            let initial_buffer_versions =
 3444                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3445
 3446            this.buffer.update(cx, |buffer, cx| {
 3447                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3448            });
 3449            for (buffer, edits) in linked_edits {
 3450                buffer.update(cx, |buffer, cx| {
 3451                    let snapshot = buffer.snapshot();
 3452                    let edits = edits
 3453                        .into_iter()
 3454                        .map(|(range, text)| {
 3455                            use text::ToPoint as TP;
 3456                            let end_point = TP::to_point(&range.end, &snapshot);
 3457                            let start_point = TP::to_point(&range.start, &snapshot);
 3458                            (start_point..end_point, text)
 3459                        })
 3460                        .sorted_by_key(|(range, _)| range.start);
 3461                    buffer.edit(edits, None, cx);
 3462                })
 3463            }
 3464            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3465            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3466            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3467            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3468                .zip(new_selection_deltas)
 3469                .map(|(selection, delta)| Selection {
 3470                    id: selection.id,
 3471                    start: selection.start + delta,
 3472                    end: selection.end + delta,
 3473                    reversed: selection.reversed,
 3474                    goal: SelectionGoal::None,
 3475                })
 3476                .collect::<Vec<_>>();
 3477
 3478            let mut i = 0;
 3479            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3480                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3481                let start = map.buffer_snapshot.anchor_before(position);
 3482                let end = map.buffer_snapshot.anchor_after(position);
 3483                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3484                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3485                        Ordering::Less => i += 1,
 3486                        Ordering::Greater => break,
 3487                        Ordering::Equal => {
 3488                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3489                                Ordering::Less => i += 1,
 3490                                Ordering::Equal => break,
 3491                                Ordering::Greater => break,
 3492                            }
 3493                        }
 3494                    }
 3495                }
 3496                this.autoclose_regions.insert(
 3497                    i,
 3498                    AutocloseRegion {
 3499                        selection_id,
 3500                        range: start..end,
 3501                        pair,
 3502                    },
 3503                );
 3504            }
 3505
 3506            let had_active_inline_completion = this.has_active_inline_completion();
 3507            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3508                s.select(new_selections)
 3509            });
 3510
 3511            if !bracket_inserted {
 3512                if let Some(on_type_format_task) =
 3513                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3514                {
 3515                    on_type_format_task.detach_and_log_err(cx);
 3516                }
 3517            }
 3518
 3519            let editor_settings = EditorSettings::get_global(cx);
 3520            if bracket_inserted
 3521                && (editor_settings.auto_signature_help
 3522                    || editor_settings.show_signature_help_after_edits)
 3523            {
 3524                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3525            }
 3526
 3527            let trigger_in_words =
 3528                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3529            if this.hard_wrap.is_some() {
 3530                let latest: Range<Point> = this.selections.newest(cx).range();
 3531                if latest.is_empty()
 3532                    && this
 3533                        .buffer()
 3534                        .read(cx)
 3535                        .snapshot(cx)
 3536                        .line_len(MultiBufferRow(latest.start.row))
 3537                        == latest.start.column
 3538                {
 3539                    this.rewrap_impl(
 3540                        RewrapOptions {
 3541                            override_language_settings: true,
 3542                            preserve_existing_whitespace: true,
 3543                        },
 3544                        cx,
 3545                    )
 3546                }
 3547            }
 3548            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3549            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3550            this.refresh_inline_completion(true, false, window, cx);
 3551            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3552        });
 3553    }
 3554
 3555    fn find_possible_emoji_shortcode_at_position(
 3556        snapshot: &MultiBufferSnapshot,
 3557        position: Point,
 3558    ) -> Option<String> {
 3559        let mut chars = Vec::new();
 3560        let mut found_colon = false;
 3561        for char in snapshot.reversed_chars_at(position).take(100) {
 3562            // Found a possible emoji shortcode in the middle of the buffer
 3563            if found_colon {
 3564                if char.is_whitespace() {
 3565                    chars.reverse();
 3566                    return Some(chars.iter().collect());
 3567                }
 3568                // If the previous character is not a whitespace, we are in the middle of a word
 3569                // and we only want to complete the shortcode if the word is made up of other emojis
 3570                let mut containing_word = String::new();
 3571                for ch in snapshot
 3572                    .reversed_chars_at(position)
 3573                    .skip(chars.len() + 1)
 3574                    .take(100)
 3575                {
 3576                    if ch.is_whitespace() {
 3577                        break;
 3578                    }
 3579                    containing_word.push(ch);
 3580                }
 3581                let containing_word = containing_word.chars().rev().collect::<String>();
 3582                if util::word_consists_of_emojis(containing_word.as_str()) {
 3583                    chars.reverse();
 3584                    return Some(chars.iter().collect());
 3585                }
 3586            }
 3587
 3588            if char.is_whitespace() || !char.is_ascii() {
 3589                return None;
 3590            }
 3591            if char == ':' {
 3592                found_colon = true;
 3593            } else {
 3594                chars.push(char);
 3595            }
 3596        }
 3597        // Found a possible emoji shortcode at the beginning of the buffer
 3598        chars.reverse();
 3599        Some(chars.iter().collect())
 3600    }
 3601
 3602    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3603        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3604        self.transact(window, cx, |this, window, cx| {
 3605            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3606                let selections = this.selections.all::<usize>(cx);
 3607                let multi_buffer = this.buffer.read(cx);
 3608                let buffer = multi_buffer.snapshot(cx);
 3609                selections
 3610                    .iter()
 3611                    .map(|selection| {
 3612                        let start_point = selection.start.to_point(&buffer);
 3613                        let mut indent =
 3614                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3615                        indent.len = cmp::min(indent.len, start_point.column);
 3616                        let start = selection.start;
 3617                        let end = selection.end;
 3618                        let selection_is_empty = start == end;
 3619                        let language_scope = buffer.language_scope_at(start);
 3620                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3621                            &language_scope
 3622                        {
 3623                            let insert_extra_newline =
 3624                                insert_extra_newline_brackets(&buffer, start..end, language)
 3625                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3626
 3627                            // Comment extension on newline is allowed only for cursor selections
 3628                            let comment_delimiter = maybe!({
 3629                                if !selection_is_empty {
 3630                                    return None;
 3631                                }
 3632
 3633                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3634                                    return None;
 3635                                }
 3636
 3637                                let delimiters = language.line_comment_prefixes();
 3638                                let max_len_of_delimiter =
 3639                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3640                                let (snapshot, range) =
 3641                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3642
 3643                                let mut index_of_first_non_whitespace = 0;
 3644                                let comment_candidate = snapshot
 3645                                    .chars_for_range(range)
 3646                                    .skip_while(|c| {
 3647                                        let should_skip = c.is_whitespace();
 3648                                        if should_skip {
 3649                                            index_of_first_non_whitespace += 1;
 3650                                        }
 3651                                        should_skip
 3652                                    })
 3653                                    .take(max_len_of_delimiter)
 3654                                    .collect::<String>();
 3655                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3656                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3657                                })?;
 3658                                let cursor_is_placed_after_comment_marker =
 3659                                    index_of_first_non_whitespace + comment_prefix.len()
 3660                                        <= start_point.column as usize;
 3661                                if cursor_is_placed_after_comment_marker {
 3662                                    Some(comment_prefix.clone())
 3663                                } else {
 3664                                    None
 3665                                }
 3666                            });
 3667                            (comment_delimiter, insert_extra_newline)
 3668                        } else {
 3669                            (None, false)
 3670                        };
 3671
 3672                        let capacity_for_delimiter = comment_delimiter
 3673                            .as_deref()
 3674                            .map(str::len)
 3675                            .unwrap_or_default();
 3676                        let mut new_text =
 3677                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3678                        new_text.push('\n');
 3679                        new_text.extend(indent.chars());
 3680                        if let Some(delimiter) = &comment_delimiter {
 3681                            new_text.push_str(delimiter);
 3682                        }
 3683                        if insert_extra_newline {
 3684                            new_text = new_text.repeat(2);
 3685                        }
 3686
 3687                        let anchor = buffer.anchor_after(end);
 3688                        let new_selection = selection.map(|_| anchor);
 3689                        (
 3690                            (start..end, new_text),
 3691                            (insert_extra_newline, new_selection),
 3692                        )
 3693                    })
 3694                    .unzip()
 3695            };
 3696
 3697            this.edit_with_autoindent(edits, cx);
 3698            let buffer = this.buffer.read(cx).snapshot(cx);
 3699            let new_selections = selection_fixup_info
 3700                .into_iter()
 3701                .map(|(extra_newline_inserted, new_selection)| {
 3702                    let mut cursor = new_selection.end.to_point(&buffer);
 3703                    if extra_newline_inserted {
 3704                        cursor.row -= 1;
 3705                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3706                    }
 3707                    new_selection.map(|_| cursor)
 3708                })
 3709                .collect();
 3710
 3711            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3712                s.select(new_selections)
 3713            });
 3714            this.refresh_inline_completion(true, false, window, cx);
 3715        });
 3716    }
 3717
 3718    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3719        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3720
 3721        let buffer = self.buffer.read(cx);
 3722        let snapshot = buffer.snapshot(cx);
 3723
 3724        let mut edits = Vec::new();
 3725        let mut rows = Vec::new();
 3726
 3727        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3728            let cursor = selection.head();
 3729            let row = cursor.row;
 3730
 3731            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3732
 3733            let newline = "\n".to_string();
 3734            edits.push((start_of_line..start_of_line, newline));
 3735
 3736            rows.push(row + rows_inserted as u32);
 3737        }
 3738
 3739        self.transact(window, cx, |editor, window, cx| {
 3740            editor.edit(edits, cx);
 3741
 3742            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3743                let mut index = 0;
 3744                s.move_cursors_with(|map, _, _| {
 3745                    let row = rows[index];
 3746                    index += 1;
 3747
 3748                    let point = Point::new(row, 0);
 3749                    let boundary = map.next_line_boundary(point).1;
 3750                    let clipped = map.clip_point(boundary, Bias::Left);
 3751
 3752                    (clipped, SelectionGoal::None)
 3753                });
 3754            });
 3755
 3756            let mut indent_edits = Vec::new();
 3757            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3758            for row in rows {
 3759                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3760                for (row, indent) in indents {
 3761                    if indent.len == 0 {
 3762                        continue;
 3763                    }
 3764
 3765                    let text = match indent.kind {
 3766                        IndentKind::Space => " ".repeat(indent.len as usize),
 3767                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3768                    };
 3769                    let point = Point::new(row.0, 0);
 3770                    indent_edits.push((point..point, text));
 3771                }
 3772            }
 3773            editor.edit(indent_edits, cx);
 3774        });
 3775    }
 3776
 3777    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3778        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3779
 3780        let buffer = self.buffer.read(cx);
 3781        let snapshot = buffer.snapshot(cx);
 3782
 3783        let mut edits = Vec::new();
 3784        let mut rows = Vec::new();
 3785        let mut rows_inserted = 0;
 3786
 3787        for selection in self.selections.all_adjusted(cx) {
 3788            let cursor = selection.head();
 3789            let row = cursor.row;
 3790
 3791            let point = Point::new(row + 1, 0);
 3792            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3793
 3794            let newline = "\n".to_string();
 3795            edits.push((start_of_line..start_of_line, newline));
 3796
 3797            rows_inserted += 1;
 3798            rows.push(row + rows_inserted);
 3799        }
 3800
 3801        self.transact(window, cx, |editor, window, cx| {
 3802            editor.edit(edits, cx);
 3803
 3804            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3805                let mut index = 0;
 3806                s.move_cursors_with(|map, _, _| {
 3807                    let row = rows[index];
 3808                    index += 1;
 3809
 3810                    let point = Point::new(row, 0);
 3811                    let boundary = map.next_line_boundary(point).1;
 3812                    let clipped = map.clip_point(boundary, Bias::Left);
 3813
 3814                    (clipped, SelectionGoal::None)
 3815                });
 3816            });
 3817
 3818            let mut indent_edits = Vec::new();
 3819            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3820            for row in rows {
 3821                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3822                for (row, indent) in indents {
 3823                    if indent.len == 0 {
 3824                        continue;
 3825                    }
 3826
 3827                    let text = match indent.kind {
 3828                        IndentKind::Space => " ".repeat(indent.len as usize),
 3829                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3830                    };
 3831                    let point = Point::new(row.0, 0);
 3832                    indent_edits.push((point..point, text));
 3833                }
 3834            }
 3835            editor.edit(indent_edits, cx);
 3836        });
 3837    }
 3838
 3839    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3840        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3841            original_indent_columns: Vec::new(),
 3842        });
 3843        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3844    }
 3845
 3846    fn insert_with_autoindent_mode(
 3847        &mut self,
 3848        text: &str,
 3849        autoindent_mode: Option<AutoindentMode>,
 3850        window: &mut Window,
 3851        cx: &mut Context<Self>,
 3852    ) {
 3853        if self.read_only(cx) {
 3854            return;
 3855        }
 3856
 3857        let text: Arc<str> = text.into();
 3858        self.transact(window, cx, |this, window, cx| {
 3859            let old_selections = this.selections.all_adjusted(cx);
 3860            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3861                let anchors = {
 3862                    let snapshot = buffer.read(cx);
 3863                    old_selections
 3864                        .iter()
 3865                        .map(|s| {
 3866                            let anchor = snapshot.anchor_after(s.head());
 3867                            s.map(|_| anchor)
 3868                        })
 3869                        .collect::<Vec<_>>()
 3870                };
 3871                buffer.edit(
 3872                    old_selections
 3873                        .iter()
 3874                        .map(|s| (s.start..s.end, text.clone())),
 3875                    autoindent_mode,
 3876                    cx,
 3877                );
 3878                anchors
 3879            });
 3880
 3881            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3882                s.select_anchors(selection_anchors);
 3883            });
 3884
 3885            cx.notify();
 3886        });
 3887    }
 3888
 3889    fn trigger_completion_on_input(
 3890        &mut self,
 3891        text: &str,
 3892        trigger_in_words: bool,
 3893        window: &mut Window,
 3894        cx: &mut Context<Self>,
 3895    ) {
 3896        let ignore_completion_provider = self
 3897            .context_menu
 3898            .borrow()
 3899            .as_ref()
 3900            .map(|menu| match menu {
 3901                CodeContextMenu::Completions(completions_menu) => {
 3902                    completions_menu.ignore_completion_provider
 3903                }
 3904                CodeContextMenu::CodeActions(_) => false,
 3905            })
 3906            .unwrap_or(false);
 3907
 3908        if ignore_completion_provider {
 3909            self.show_word_completions(&ShowWordCompletions, window, cx);
 3910        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3911            self.show_completions(
 3912                &ShowCompletions {
 3913                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3914                },
 3915                window,
 3916                cx,
 3917            );
 3918        } else {
 3919            self.hide_context_menu(window, cx);
 3920        }
 3921    }
 3922
 3923    fn is_completion_trigger(
 3924        &self,
 3925        text: &str,
 3926        trigger_in_words: bool,
 3927        cx: &mut Context<Self>,
 3928    ) -> bool {
 3929        let position = self.selections.newest_anchor().head();
 3930        let multibuffer = self.buffer.read(cx);
 3931        let Some(buffer) = position
 3932            .buffer_id
 3933            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3934        else {
 3935            return false;
 3936        };
 3937
 3938        if let Some(completion_provider) = &self.completion_provider {
 3939            completion_provider.is_completion_trigger(
 3940                &buffer,
 3941                position.text_anchor,
 3942                text,
 3943                trigger_in_words,
 3944                cx,
 3945            )
 3946        } else {
 3947            false
 3948        }
 3949    }
 3950
 3951    /// If any empty selections is touching the start of its innermost containing autoclose
 3952    /// region, expand it to select the brackets.
 3953    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3954        let selections = self.selections.all::<usize>(cx);
 3955        let buffer = self.buffer.read(cx).read(cx);
 3956        let new_selections = self
 3957            .selections_with_autoclose_regions(selections, &buffer)
 3958            .map(|(mut selection, region)| {
 3959                if !selection.is_empty() {
 3960                    return selection;
 3961                }
 3962
 3963                if let Some(region) = region {
 3964                    let mut range = region.range.to_offset(&buffer);
 3965                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3966                        range.start -= region.pair.start.len();
 3967                        if buffer.contains_str_at(range.start, &region.pair.start)
 3968                            && buffer.contains_str_at(range.end, &region.pair.end)
 3969                        {
 3970                            range.end += region.pair.end.len();
 3971                            selection.start = range.start;
 3972                            selection.end = range.end;
 3973
 3974                            return selection;
 3975                        }
 3976                    }
 3977                }
 3978
 3979                let always_treat_brackets_as_autoclosed = buffer
 3980                    .language_settings_at(selection.start, cx)
 3981                    .always_treat_brackets_as_autoclosed;
 3982
 3983                if !always_treat_brackets_as_autoclosed {
 3984                    return selection;
 3985                }
 3986
 3987                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3988                    for (pair, enabled) in scope.brackets() {
 3989                        if !enabled || !pair.close {
 3990                            continue;
 3991                        }
 3992
 3993                        if buffer.contains_str_at(selection.start, &pair.end) {
 3994                            let pair_start_len = pair.start.len();
 3995                            if buffer.contains_str_at(
 3996                                selection.start.saturating_sub(pair_start_len),
 3997                                &pair.start,
 3998                            ) {
 3999                                selection.start -= pair_start_len;
 4000                                selection.end += pair.end.len();
 4001
 4002                                return selection;
 4003                            }
 4004                        }
 4005                    }
 4006                }
 4007
 4008                selection
 4009            })
 4010            .collect();
 4011
 4012        drop(buffer);
 4013        self.change_selections(None, window, cx, |selections| {
 4014            selections.select(new_selections)
 4015        });
 4016    }
 4017
 4018    /// Iterate the given selections, and for each one, find the smallest surrounding
 4019    /// autoclose region. This uses the ordering of the selections and the autoclose
 4020    /// regions to avoid repeated comparisons.
 4021    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4022        &'a self,
 4023        selections: impl IntoIterator<Item = Selection<D>>,
 4024        buffer: &'a MultiBufferSnapshot,
 4025    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4026        let mut i = 0;
 4027        let mut regions = self.autoclose_regions.as_slice();
 4028        selections.into_iter().map(move |selection| {
 4029            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4030
 4031            let mut enclosing = None;
 4032            while let Some(pair_state) = regions.get(i) {
 4033                if pair_state.range.end.to_offset(buffer) < range.start {
 4034                    regions = &regions[i + 1..];
 4035                    i = 0;
 4036                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4037                    break;
 4038                } else {
 4039                    if pair_state.selection_id == selection.id {
 4040                        enclosing = Some(pair_state);
 4041                    }
 4042                    i += 1;
 4043                }
 4044            }
 4045
 4046            (selection, enclosing)
 4047        })
 4048    }
 4049
 4050    /// Remove any autoclose regions that no longer contain their selection.
 4051    fn invalidate_autoclose_regions(
 4052        &mut self,
 4053        mut selections: &[Selection<Anchor>],
 4054        buffer: &MultiBufferSnapshot,
 4055    ) {
 4056        self.autoclose_regions.retain(|state| {
 4057            let mut i = 0;
 4058            while let Some(selection) = selections.get(i) {
 4059                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4060                    selections = &selections[1..];
 4061                    continue;
 4062                }
 4063                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4064                    break;
 4065                }
 4066                if selection.id == state.selection_id {
 4067                    return true;
 4068                } else {
 4069                    i += 1;
 4070                }
 4071            }
 4072            false
 4073        });
 4074    }
 4075
 4076    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4077        let offset = position.to_offset(buffer);
 4078        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4079        if offset > word_range.start && kind == Some(CharKind::Word) {
 4080            Some(
 4081                buffer
 4082                    .text_for_range(word_range.start..offset)
 4083                    .collect::<String>(),
 4084            )
 4085        } else {
 4086            None
 4087        }
 4088    }
 4089
 4090    pub fn toggle_inlay_hints(
 4091        &mut self,
 4092        _: &ToggleInlayHints,
 4093        _: &mut Window,
 4094        cx: &mut Context<Self>,
 4095    ) {
 4096        self.refresh_inlay_hints(
 4097            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4098            cx,
 4099        );
 4100    }
 4101
 4102    pub fn inlay_hints_enabled(&self) -> bool {
 4103        self.inlay_hint_cache.enabled
 4104    }
 4105
 4106    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4107        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4108            return;
 4109        }
 4110
 4111        let reason_description = reason.description();
 4112        let ignore_debounce = matches!(
 4113            reason,
 4114            InlayHintRefreshReason::SettingsChange(_)
 4115                | InlayHintRefreshReason::Toggle(_)
 4116                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4117                | InlayHintRefreshReason::ModifiersChanged(_)
 4118        );
 4119        let (invalidate_cache, required_languages) = match reason {
 4120            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4121                match self.inlay_hint_cache.modifiers_override(enabled) {
 4122                    Some(enabled) => {
 4123                        if enabled {
 4124                            (InvalidationStrategy::RefreshRequested, None)
 4125                        } else {
 4126                            self.splice_inlays(
 4127                                &self
 4128                                    .visible_inlay_hints(cx)
 4129                                    .iter()
 4130                                    .map(|inlay| inlay.id)
 4131                                    .collect::<Vec<InlayId>>(),
 4132                                Vec::new(),
 4133                                cx,
 4134                            );
 4135                            return;
 4136                        }
 4137                    }
 4138                    None => return,
 4139                }
 4140            }
 4141            InlayHintRefreshReason::Toggle(enabled) => {
 4142                if self.inlay_hint_cache.toggle(enabled) {
 4143                    if enabled {
 4144                        (InvalidationStrategy::RefreshRequested, None)
 4145                    } else {
 4146                        self.splice_inlays(
 4147                            &self
 4148                                .visible_inlay_hints(cx)
 4149                                .iter()
 4150                                .map(|inlay| inlay.id)
 4151                                .collect::<Vec<InlayId>>(),
 4152                            Vec::new(),
 4153                            cx,
 4154                        );
 4155                        return;
 4156                    }
 4157                } else {
 4158                    return;
 4159                }
 4160            }
 4161            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4162                match self.inlay_hint_cache.update_settings(
 4163                    &self.buffer,
 4164                    new_settings,
 4165                    self.visible_inlay_hints(cx),
 4166                    cx,
 4167                ) {
 4168                    ControlFlow::Break(Some(InlaySplice {
 4169                        to_remove,
 4170                        to_insert,
 4171                    })) => {
 4172                        self.splice_inlays(&to_remove, to_insert, cx);
 4173                        return;
 4174                    }
 4175                    ControlFlow::Break(None) => return,
 4176                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4177                }
 4178            }
 4179            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4180                if let Some(InlaySplice {
 4181                    to_remove,
 4182                    to_insert,
 4183                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4184                {
 4185                    self.splice_inlays(&to_remove, to_insert, cx);
 4186                }
 4187                self.display_map.update(cx, |display_map, _| {
 4188                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4189                });
 4190                return;
 4191            }
 4192            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4193            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4194                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4195            }
 4196            InlayHintRefreshReason::RefreshRequested => {
 4197                (InvalidationStrategy::RefreshRequested, None)
 4198            }
 4199        };
 4200
 4201        if let Some(InlaySplice {
 4202            to_remove,
 4203            to_insert,
 4204        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4205            reason_description,
 4206            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4207            invalidate_cache,
 4208            ignore_debounce,
 4209            cx,
 4210        ) {
 4211            self.splice_inlays(&to_remove, to_insert, cx);
 4212        }
 4213    }
 4214
 4215    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4216        self.display_map
 4217            .read(cx)
 4218            .current_inlays()
 4219            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4220            .cloned()
 4221            .collect()
 4222    }
 4223
 4224    pub fn excerpts_for_inlay_hints_query(
 4225        &self,
 4226        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4227        cx: &mut Context<Editor>,
 4228    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4229        let Some(project) = self.project.as_ref() else {
 4230            return HashMap::default();
 4231        };
 4232        let project = project.read(cx);
 4233        let multi_buffer = self.buffer().read(cx);
 4234        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4235        let multi_buffer_visible_start = self
 4236            .scroll_manager
 4237            .anchor()
 4238            .anchor
 4239            .to_point(&multi_buffer_snapshot);
 4240        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4241            multi_buffer_visible_start
 4242                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4243            Bias::Left,
 4244        );
 4245        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4246        multi_buffer_snapshot
 4247            .range_to_buffer_ranges(multi_buffer_visible_range)
 4248            .into_iter()
 4249            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4250            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4251                let buffer_file = project::File::from_dyn(buffer.file())?;
 4252                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4253                let worktree_entry = buffer_worktree
 4254                    .read(cx)
 4255                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4256                if worktree_entry.is_ignored {
 4257                    return None;
 4258                }
 4259
 4260                let language = buffer.language()?;
 4261                if let Some(restrict_to_languages) = restrict_to_languages {
 4262                    if !restrict_to_languages.contains(language) {
 4263                        return None;
 4264                    }
 4265                }
 4266                Some((
 4267                    excerpt_id,
 4268                    (
 4269                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4270                        buffer.version().clone(),
 4271                        excerpt_visible_range,
 4272                    ),
 4273                ))
 4274            })
 4275            .collect()
 4276    }
 4277
 4278    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4279        TextLayoutDetails {
 4280            text_system: window.text_system().clone(),
 4281            editor_style: self.style.clone().unwrap(),
 4282            rem_size: window.rem_size(),
 4283            scroll_anchor: self.scroll_manager.anchor(),
 4284            visible_rows: self.visible_line_count(),
 4285            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4286        }
 4287    }
 4288
 4289    pub fn splice_inlays(
 4290        &self,
 4291        to_remove: &[InlayId],
 4292        to_insert: Vec<Inlay>,
 4293        cx: &mut Context<Self>,
 4294    ) {
 4295        self.display_map.update(cx, |display_map, cx| {
 4296            display_map.splice_inlays(to_remove, to_insert, cx)
 4297        });
 4298        cx.notify();
 4299    }
 4300
 4301    fn trigger_on_type_formatting(
 4302        &self,
 4303        input: String,
 4304        window: &mut Window,
 4305        cx: &mut Context<Self>,
 4306    ) -> Option<Task<Result<()>>> {
 4307        if input.len() != 1 {
 4308            return None;
 4309        }
 4310
 4311        let project = self.project.as_ref()?;
 4312        let position = self.selections.newest_anchor().head();
 4313        let (buffer, buffer_position) = self
 4314            .buffer
 4315            .read(cx)
 4316            .text_anchor_for_position(position, cx)?;
 4317
 4318        let settings = language_settings::language_settings(
 4319            buffer
 4320                .read(cx)
 4321                .language_at(buffer_position)
 4322                .map(|l| l.name()),
 4323            buffer.read(cx).file(),
 4324            cx,
 4325        );
 4326        if !settings.use_on_type_format {
 4327            return None;
 4328        }
 4329
 4330        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4331        // hence we do LSP request & edit on host side only — add formats to host's history.
 4332        let push_to_lsp_host_history = true;
 4333        // If this is not the host, append its history with new edits.
 4334        let push_to_client_history = project.read(cx).is_via_collab();
 4335
 4336        let on_type_formatting = project.update(cx, |project, cx| {
 4337            project.on_type_format(
 4338                buffer.clone(),
 4339                buffer_position,
 4340                input,
 4341                push_to_lsp_host_history,
 4342                cx,
 4343            )
 4344        });
 4345        Some(cx.spawn_in(window, async move |editor, cx| {
 4346            if let Some(transaction) = on_type_formatting.await? {
 4347                if push_to_client_history {
 4348                    buffer
 4349                        .update(cx, |buffer, _| {
 4350                            buffer.push_transaction(transaction, Instant::now());
 4351                            buffer.finalize_last_transaction();
 4352                        })
 4353                        .ok();
 4354                }
 4355                editor.update(cx, |editor, cx| {
 4356                    editor.refresh_document_highlights(cx);
 4357                })?;
 4358            }
 4359            Ok(())
 4360        }))
 4361    }
 4362
 4363    pub fn show_word_completions(
 4364        &mut self,
 4365        _: &ShowWordCompletions,
 4366        window: &mut Window,
 4367        cx: &mut Context<Self>,
 4368    ) {
 4369        self.open_completions_menu(true, None, window, cx);
 4370    }
 4371
 4372    pub fn show_completions(
 4373        &mut self,
 4374        options: &ShowCompletions,
 4375        window: &mut Window,
 4376        cx: &mut Context<Self>,
 4377    ) {
 4378        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4379    }
 4380
 4381    fn open_completions_menu(
 4382        &mut self,
 4383        ignore_completion_provider: bool,
 4384        trigger: Option<&str>,
 4385        window: &mut Window,
 4386        cx: &mut Context<Self>,
 4387    ) {
 4388        if self.pending_rename.is_some() {
 4389            return;
 4390        }
 4391        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4392            return;
 4393        }
 4394
 4395        let position = self.selections.newest_anchor().head();
 4396        if position.diff_base_anchor.is_some() {
 4397            return;
 4398        }
 4399        let (buffer, buffer_position) =
 4400            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4401                output
 4402            } else {
 4403                return;
 4404            };
 4405        let buffer_snapshot = buffer.read(cx).snapshot();
 4406        let show_completion_documentation = buffer_snapshot
 4407            .settings_at(buffer_position, cx)
 4408            .show_completion_documentation;
 4409
 4410        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4411
 4412        let trigger_kind = match trigger {
 4413            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4414                CompletionTriggerKind::TRIGGER_CHARACTER
 4415            }
 4416            _ => CompletionTriggerKind::INVOKED,
 4417        };
 4418        let completion_context = CompletionContext {
 4419            trigger_character: trigger.and_then(|trigger| {
 4420                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4421                    Some(String::from(trigger))
 4422                } else {
 4423                    None
 4424                }
 4425            }),
 4426            trigger_kind,
 4427        };
 4428
 4429        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4430        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4431            let word_to_exclude = buffer_snapshot
 4432                .text_for_range(old_range.clone())
 4433                .collect::<String>();
 4434            (
 4435                buffer_snapshot.anchor_before(old_range.start)
 4436                    ..buffer_snapshot.anchor_after(old_range.end),
 4437                Some(word_to_exclude),
 4438            )
 4439        } else {
 4440            (buffer_position..buffer_position, None)
 4441        };
 4442
 4443        let completion_settings = language_settings(
 4444            buffer_snapshot
 4445                .language_at(buffer_position)
 4446                .map(|language| language.name()),
 4447            buffer_snapshot.file(),
 4448            cx,
 4449        )
 4450        .completions;
 4451
 4452        // The document can be large, so stay in reasonable bounds when searching for words,
 4453        // otherwise completion pop-up might be slow to appear.
 4454        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4455        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4456        let min_word_search = buffer_snapshot.clip_point(
 4457            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4458            Bias::Left,
 4459        );
 4460        let max_word_search = buffer_snapshot.clip_point(
 4461            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4462            Bias::Right,
 4463        );
 4464        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4465            ..buffer_snapshot.point_to_offset(max_word_search);
 4466
 4467        let provider = self
 4468            .completion_provider
 4469            .as_ref()
 4470            .filter(|_| !ignore_completion_provider);
 4471        let skip_digits = query
 4472            .as_ref()
 4473            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4474
 4475        let (mut words, provided_completions) = match provider {
 4476            Some(provider) => {
 4477                let completions = provider.completions(
 4478                    position.excerpt_id,
 4479                    &buffer,
 4480                    buffer_position,
 4481                    completion_context,
 4482                    window,
 4483                    cx,
 4484                );
 4485
 4486                let words = match completion_settings.words {
 4487                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4488                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4489                        .background_spawn(async move {
 4490                            buffer_snapshot.words_in_range(WordsQuery {
 4491                                fuzzy_contents: None,
 4492                                range: word_search_range,
 4493                                skip_digits,
 4494                            })
 4495                        }),
 4496                };
 4497
 4498                (words, completions)
 4499            }
 4500            None => (
 4501                cx.background_spawn(async move {
 4502                    buffer_snapshot.words_in_range(WordsQuery {
 4503                        fuzzy_contents: None,
 4504                        range: word_search_range,
 4505                        skip_digits,
 4506                    })
 4507                }),
 4508                Task::ready(Ok(None)),
 4509            ),
 4510        };
 4511
 4512        let sort_completions = provider
 4513            .as_ref()
 4514            .map_or(false, |provider| provider.sort_completions());
 4515
 4516        let filter_completions = provider
 4517            .as_ref()
 4518            .map_or(true, |provider| provider.filter_completions());
 4519
 4520        let id = post_inc(&mut self.next_completion_id);
 4521        let task = cx.spawn_in(window, async move |editor, cx| {
 4522            async move {
 4523                editor.update(cx, |this, _| {
 4524                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4525                })?;
 4526
 4527                let mut completions = Vec::new();
 4528                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4529                    completions.extend(provided_completions);
 4530                    if completion_settings.words == WordsCompletionMode::Fallback {
 4531                        words = Task::ready(BTreeMap::default());
 4532                    }
 4533                }
 4534
 4535                let mut words = words.await;
 4536                if let Some(word_to_exclude) = &word_to_exclude {
 4537                    words.remove(word_to_exclude);
 4538                }
 4539                for lsp_completion in &completions {
 4540                    words.remove(&lsp_completion.new_text);
 4541                }
 4542                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4543                    replace_range: old_range.clone(),
 4544                    new_text: word.clone(),
 4545                    label: CodeLabel::plain(word, None),
 4546                    icon_path: None,
 4547                    documentation: None,
 4548                    source: CompletionSource::BufferWord {
 4549                        word_range,
 4550                        resolved: false,
 4551                    },
 4552                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4553                    confirm: None,
 4554                }));
 4555
 4556                let menu = if completions.is_empty() {
 4557                    None
 4558                } else {
 4559                    let mut menu = CompletionsMenu::new(
 4560                        id,
 4561                        sort_completions,
 4562                        show_completion_documentation,
 4563                        ignore_completion_provider,
 4564                        position,
 4565                        buffer.clone(),
 4566                        completions.into(),
 4567                    );
 4568
 4569                    menu.filter(
 4570                        if filter_completions {
 4571                            query.as_deref()
 4572                        } else {
 4573                            None
 4574                        },
 4575                        cx.background_executor().clone(),
 4576                    )
 4577                    .await;
 4578
 4579                    menu.visible().then_some(menu)
 4580                };
 4581
 4582                editor.update_in(cx, |editor, window, cx| {
 4583                    match editor.context_menu.borrow().as_ref() {
 4584                        None => {}
 4585                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4586                            if prev_menu.id > id {
 4587                                return;
 4588                            }
 4589                        }
 4590                        _ => return,
 4591                    }
 4592
 4593                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4594                        let mut menu = menu.unwrap();
 4595                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4596
 4597                        *editor.context_menu.borrow_mut() =
 4598                            Some(CodeContextMenu::Completions(menu));
 4599
 4600                        if editor.show_edit_predictions_in_menu() {
 4601                            editor.update_visible_inline_completion(window, cx);
 4602                        } else {
 4603                            editor.discard_inline_completion(false, cx);
 4604                        }
 4605
 4606                        cx.notify();
 4607                    } else if editor.completion_tasks.len() <= 1 {
 4608                        // If there are no more completion tasks and the last menu was
 4609                        // empty, we should hide it.
 4610                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4611                        // If it was already hidden and we don't show inline
 4612                        // completions in the menu, we should also show the
 4613                        // inline-completion when available.
 4614                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4615                            editor.update_visible_inline_completion(window, cx);
 4616                        }
 4617                    }
 4618                })?;
 4619
 4620                anyhow::Ok(())
 4621            }
 4622            .log_err()
 4623            .await
 4624        });
 4625
 4626        self.completion_tasks.push((id, task));
 4627    }
 4628
 4629    #[cfg(feature = "test-support")]
 4630    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4631        let menu = self.context_menu.borrow();
 4632        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4633            let completions = menu.completions.borrow();
 4634            Some(completions.to_vec())
 4635        } else {
 4636            None
 4637        }
 4638    }
 4639
 4640    pub fn confirm_completion(
 4641        &mut self,
 4642        action: &ConfirmCompletion,
 4643        window: &mut Window,
 4644        cx: &mut Context<Self>,
 4645    ) -> Option<Task<Result<()>>> {
 4646        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4647        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4648    }
 4649
 4650    pub fn confirm_completion_insert(
 4651        &mut self,
 4652        _: &ConfirmCompletionInsert,
 4653        window: &mut Window,
 4654        cx: &mut Context<Self>,
 4655    ) -> Option<Task<Result<()>>> {
 4656        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4657        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4658    }
 4659
 4660    pub fn confirm_completion_replace(
 4661        &mut self,
 4662        _: &ConfirmCompletionReplace,
 4663        window: &mut Window,
 4664        cx: &mut Context<Self>,
 4665    ) -> Option<Task<Result<()>>> {
 4666        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4667        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4668    }
 4669
 4670    pub fn compose_completion(
 4671        &mut self,
 4672        action: &ComposeCompletion,
 4673        window: &mut Window,
 4674        cx: &mut Context<Self>,
 4675    ) -> Option<Task<Result<()>>> {
 4676        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4677        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4678    }
 4679
 4680    fn do_completion(
 4681        &mut self,
 4682        item_ix: Option<usize>,
 4683        intent: CompletionIntent,
 4684        window: &mut Window,
 4685        cx: &mut Context<Editor>,
 4686    ) -> Option<Task<Result<()>>> {
 4687        use language::ToOffset as _;
 4688
 4689        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4690        else {
 4691            return None;
 4692        };
 4693
 4694        let candidate_id = {
 4695            let entries = completions_menu.entries.borrow();
 4696            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4697            if self.show_edit_predictions_in_menu() {
 4698                self.discard_inline_completion(true, cx);
 4699            }
 4700            mat.candidate_id
 4701        };
 4702
 4703        let buffer_handle = completions_menu.buffer;
 4704        let completion = completions_menu
 4705            .completions
 4706            .borrow()
 4707            .get(candidate_id)?
 4708            .clone();
 4709        cx.stop_propagation();
 4710
 4711        let snippet;
 4712        let new_text;
 4713        if completion.is_snippet() {
 4714            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4715            new_text = snippet.as_ref().unwrap().text.clone();
 4716        } else {
 4717            snippet = None;
 4718            new_text = completion.new_text.clone();
 4719        };
 4720
 4721        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4722        let buffer = buffer_handle.read(cx);
 4723        let snapshot = self.buffer.read(cx).snapshot(cx);
 4724        let replace_range_multibuffer = {
 4725            let excerpt = snapshot
 4726                .excerpt_containing(self.selections.newest_anchor().range())
 4727                .unwrap();
 4728            let multibuffer_anchor = snapshot
 4729                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4730                .unwrap()
 4731                ..snapshot
 4732                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4733                    .unwrap();
 4734            multibuffer_anchor.start.to_offset(&snapshot)
 4735                ..multibuffer_anchor.end.to_offset(&snapshot)
 4736        };
 4737        let newest_anchor = self.selections.newest_anchor();
 4738        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4739            return None;
 4740        }
 4741
 4742        let old_text = buffer
 4743            .text_for_range(replace_range.clone())
 4744            .collect::<String>();
 4745        let lookbehind = newest_anchor
 4746            .start
 4747            .text_anchor
 4748            .to_offset(buffer)
 4749            .saturating_sub(replace_range.start);
 4750        let lookahead = replace_range
 4751            .end
 4752            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4753        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4754        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4755
 4756        let selections = self.selections.all::<usize>(cx);
 4757        let mut ranges = Vec::new();
 4758        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4759
 4760        for selection in &selections {
 4761            let range = if selection.id == newest_anchor.id {
 4762                replace_range_multibuffer.clone()
 4763            } else {
 4764                let mut range = selection.range();
 4765
 4766                // if prefix is present, don't duplicate it
 4767                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 4768                    range.start = range.start.saturating_sub(lookbehind);
 4769
 4770                    // if suffix is also present, mimic the newest cursor and replace it
 4771                    if selection.id != newest_anchor.id
 4772                        && snapshot.contains_str_at(range.end, suffix)
 4773                    {
 4774                        range.end += lookahead;
 4775                    }
 4776                }
 4777                range
 4778            };
 4779
 4780            ranges.push(range);
 4781
 4782            if !self.linked_edit_ranges.is_empty() {
 4783                let start_anchor = snapshot.anchor_before(selection.head());
 4784                let end_anchor = snapshot.anchor_after(selection.tail());
 4785                if let Some(ranges) = self
 4786                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4787                {
 4788                    for (buffer, edits) in ranges {
 4789                        linked_edits
 4790                            .entry(buffer.clone())
 4791                            .or_default()
 4792                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 4793                    }
 4794                }
 4795            }
 4796        }
 4797
 4798        cx.emit(EditorEvent::InputHandled {
 4799            utf16_range_to_replace: None,
 4800            text: new_text.clone().into(),
 4801        });
 4802
 4803        self.transact(window, cx, |this, window, cx| {
 4804            if let Some(mut snippet) = snippet {
 4805                snippet.text = new_text.to_string();
 4806                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4807            } else {
 4808                this.buffer.update(cx, |buffer, cx| {
 4809                    let auto_indent = match completion.insert_text_mode {
 4810                        Some(InsertTextMode::AS_IS) => None,
 4811                        _ => this.autoindent_mode.clone(),
 4812                    };
 4813                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 4814                    buffer.edit(edits, auto_indent, cx);
 4815                });
 4816            }
 4817            for (buffer, edits) in linked_edits {
 4818                buffer.update(cx, |buffer, cx| {
 4819                    let snapshot = buffer.snapshot();
 4820                    let edits = edits
 4821                        .into_iter()
 4822                        .map(|(range, text)| {
 4823                            use text::ToPoint as TP;
 4824                            let end_point = TP::to_point(&range.end, &snapshot);
 4825                            let start_point = TP::to_point(&range.start, &snapshot);
 4826                            (start_point..end_point, text)
 4827                        })
 4828                        .sorted_by_key(|(range, _)| range.start);
 4829                    buffer.edit(edits, None, cx);
 4830                })
 4831            }
 4832
 4833            this.refresh_inline_completion(true, false, window, cx);
 4834        });
 4835
 4836        let show_new_completions_on_confirm = completion
 4837            .confirm
 4838            .as_ref()
 4839            .map_or(false, |confirm| confirm(intent, window, cx));
 4840        if show_new_completions_on_confirm {
 4841            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4842        }
 4843
 4844        let provider = self.completion_provider.as_ref()?;
 4845        drop(completion);
 4846        let apply_edits = provider.apply_additional_edits_for_completion(
 4847            buffer_handle,
 4848            completions_menu.completions.clone(),
 4849            candidate_id,
 4850            true,
 4851            cx,
 4852        );
 4853
 4854        let editor_settings = EditorSettings::get_global(cx);
 4855        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4856            // After the code completion is finished, users often want to know what signatures are needed.
 4857            // so we should automatically call signature_help
 4858            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4859        }
 4860
 4861        Some(cx.foreground_executor().spawn(async move {
 4862            apply_edits.await?;
 4863            Ok(())
 4864        }))
 4865    }
 4866
 4867    fn prepare_code_actions_task(
 4868        &mut self,
 4869        action: &ToggleCodeActions,
 4870        window: &mut Window,
 4871        cx: &mut Context<Self>,
 4872    ) -> Task<Option<(Entity<Buffer>, CodeActionContents)>> {
 4873        let snapshot = self.snapshot(window, cx);
 4874        let multibuffer_point = action
 4875            .deployed_from_indicator
 4876            .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4877            .unwrap_or_else(|| self.selections.newest::<Point>(cx).head());
 4878
 4879        let Some((buffer, buffer_row)) = snapshot
 4880            .buffer_snapshot
 4881            .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4882            .and_then(|(buffer_snapshot, range)| {
 4883                self.buffer
 4884                    .read(cx)
 4885                    .buffer(buffer_snapshot.remote_id())
 4886                    .map(|buffer| (buffer, range.start.row))
 4887            })
 4888        else {
 4889            return Task::ready(None);
 4890        };
 4891
 4892        let (_, code_actions) = self
 4893            .available_code_actions
 4894            .clone()
 4895            .and_then(|(location, code_actions)| {
 4896                let snapshot = location.buffer.read(cx).snapshot();
 4897                let point_range = location.range.to_point(&snapshot);
 4898                let point_range = point_range.start.row..=point_range.end.row;
 4899                if point_range.contains(&buffer_row) {
 4900                    Some((location, code_actions))
 4901                } else {
 4902                    None
 4903                }
 4904            })
 4905            .unzip();
 4906
 4907        let buffer_id = buffer.read(cx).remote_id();
 4908        let tasks = self
 4909            .tasks
 4910            .get(&(buffer_id, buffer_row))
 4911            .map(|t| Arc::new(t.to_owned()));
 4912
 4913        if tasks.is_none() && code_actions.is_none() {
 4914            return Task::ready(None);
 4915        }
 4916
 4917        self.completion_tasks.clear();
 4918        self.discard_inline_completion(false, cx);
 4919
 4920        let task_context = tasks
 4921            .as_ref()
 4922            .zip(self.project.clone())
 4923            .map(|(tasks, project)| {
 4924                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4925            });
 4926
 4927        cx.spawn_in(window, async move |_, cx| {
 4928            let task_context = match task_context {
 4929                Some(task_context) => task_context.await,
 4930                None => None,
 4931            };
 4932            let resolved_tasks =
 4933                tasks
 4934                    .zip(task_context)
 4935                    .map(|(tasks, task_context)| ResolvedTasks {
 4936                        templates: tasks.resolve(&task_context).collect(),
 4937                        position: snapshot
 4938                            .buffer_snapshot
 4939                            .anchor_before(Point::new(multibuffer_point.row, tasks.column)),
 4940                    });
 4941            let code_action_contents = cx
 4942                .update(|_, cx| CodeActionContents::new(resolved_tasks, code_actions, cx))
 4943                .ok()?;
 4944            Some((buffer, code_action_contents))
 4945        })
 4946    }
 4947
 4948    pub fn toggle_code_actions(
 4949        &mut self,
 4950        action: &ToggleCodeActions,
 4951        window: &mut Window,
 4952        cx: &mut Context<Self>,
 4953    ) {
 4954        let mut context_menu = self.context_menu.borrow_mut();
 4955        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4956            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4957                // Toggle if we're selecting the same one
 4958                *context_menu = None;
 4959                cx.notify();
 4960                return;
 4961            } else {
 4962                // Otherwise, clear it and start a new one
 4963                *context_menu = None;
 4964                cx.notify();
 4965            }
 4966        }
 4967        drop(context_menu);
 4968
 4969        let deployed_from_indicator = action.deployed_from_indicator;
 4970        let mut task = self.code_actions_task.take();
 4971        let action = action.clone();
 4972
 4973        cx.spawn_in(window, async move |editor, cx| {
 4974            while let Some(prev_task) = task {
 4975                prev_task.await.log_err();
 4976                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4977            }
 4978
 4979            let context_menu_task = editor.update_in(cx, |editor, window, cx| {
 4980                if !editor.focus_handle.is_focused(window) {
 4981                    return Some(Task::ready(Ok(())));
 4982                }
 4983                let debugger_flag = cx.has_flag::<Debugger>();
 4984                let code_actions_task = editor.prepare_code_actions_task(&action, window, cx);
 4985                Some(cx.spawn_in(window, async move |editor, cx| {
 4986                    if let Some((buffer, code_action_contents)) = code_actions_task.await {
 4987                        let spawn_straight_away =
 4988                            code_action_contents.tasks().map_or(false, |tasks| {
 4989                                tasks
 4990                                    .templates
 4991                                    .iter()
 4992                                    .filter(|task| {
 4993                                        if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 4994                                            debugger_flag
 4995                                        } else {
 4996                                            true
 4997                                        }
 4998                                    })
 4999                                    .count()
 5000                                    == 1
 5001                            }) && code_action_contents
 5002                                .actions
 5003                                .as_ref()
 5004                                .map_or(true, |actions| actions.is_empty());
 5005                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5006                            *editor.context_menu.borrow_mut() =
 5007                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5008                                    buffer,
 5009                                    actions: code_action_contents,
 5010                                    selected_item: Default::default(),
 5011                                    scroll_handle: UniformListScrollHandle::default(),
 5012                                    deployed_from_indicator,
 5013                                }));
 5014                            if spawn_straight_away {
 5015                                if let Some(task) = editor.confirm_code_action(
 5016                                    &ConfirmCodeAction {
 5017                                        item_ix: Some(0),
 5018                                        from_mouse_context_menu: false,
 5019                                    },
 5020                                    window,
 5021                                    cx,
 5022                                ) {
 5023                                    cx.notify();
 5024                                    return task;
 5025                                }
 5026                            }
 5027                            cx.notify();
 5028                            Task::ready(Ok(()))
 5029                        }) {
 5030                            task.await
 5031                        } else {
 5032                            Ok(())
 5033                        }
 5034                    } else {
 5035                        Ok(())
 5036                    }
 5037                }))
 5038            })?;
 5039            if let Some(task) = context_menu_task {
 5040                task.await?;
 5041            }
 5042
 5043            Ok::<_, anyhow::Error>(())
 5044        })
 5045        .detach_and_log_err(cx);
 5046    }
 5047
 5048    pub fn confirm_code_action(
 5049        &mut self,
 5050        action: &ConfirmCodeAction,
 5051        window: &mut Window,
 5052        cx: &mut Context<Self>,
 5053    ) -> Option<Task<Result<()>>> {
 5054        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5055
 5056        let (action, buffer) = if action.from_mouse_context_menu {
 5057            if let Some(menu) = self.mouse_context_menu.take() {
 5058                let code_action = menu.code_action?;
 5059                let index = action.item_ix?;
 5060                let action = code_action.actions.get(index)?;
 5061                (action, code_action.buffer)
 5062            } else {
 5063                return None;
 5064            }
 5065        } else {
 5066            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5067                let action_ix = action.item_ix.unwrap_or(menu.selected_item);
 5068                let action = menu.actions.get(action_ix)?;
 5069                let buffer = menu.buffer;
 5070                (action, buffer)
 5071            } else {
 5072                return None;
 5073            }
 5074        };
 5075
 5076        let title = action.label();
 5077        let workspace = self.workspace()?;
 5078
 5079        match action {
 5080            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5081                match resolved_task.task_type() {
 5082                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5083                        workspace::tasks::schedule_resolved_task(
 5084                            workspace,
 5085                            task_source_kind,
 5086                            resolved_task,
 5087                            false,
 5088                            cx,
 5089                        );
 5090
 5091                        Some(Task::ready(Ok(())))
 5092                    }),
 5093                    task::TaskType::Debug(debug_args) => {
 5094                        if debug_args.locator.is_some() {
 5095                            workspace.update(cx, |workspace, cx| {
 5096                                workspace::tasks::schedule_resolved_task(
 5097                                    workspace,
 5098                                    task_source_kind,
 5099                                    resolved_task,
 5100                                    false,
 5101                                    cx,
 5102                                );
 5103                            });
 5104
 5105                            return Some(Task::ready(Ok(())));
 5106                        }
 5107
 5108                        if let Some(project) = self.project.as_ref() {
 5109                            project
 5110                                .update(cx, |project, cx| {
 5111                                    project.start_debug_session(
 5112                                        resolved_task.resolved_debug_adapter_config().unwrap(),
 5113                                        cx,
 5114                                    )
 5115                                })
 5116                                .detach_and_log_err(cx);
 5117                            Some(Task::ready(Ok(())))
 5118                        } else {
 5119                            Some(Task::ready(Ok(())))
 5120                        }
 5121                    }
 5122                }
 5123            }
 5124            CodeActionsItem::CodeAction {
 5125                excerpt_id,
 5126                action,
 5127                provider,
 5128            } => {
 5129                let apply_code_action =
 5130                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5131                let workspace = workspace.downgrade();
 5132                Some(cx.spawn_in(window, async move |editor, cx| {
 5133                    let project_transaction = apply_code_action.await?;
 5134                    Self::open_project_transaction(
 5135                        &editor,
 5136                        workspace,
 5137                        project_transaction,
 5138                        title,
 5139                        cx,
 5140                    )
 5141                    .await
 5142                }))
 5143            }
 5144        }
 5145    }
 5146
 5147    pub async fn open_project_transaction(
 5148        this: &WeakEntity<Editor>,
 5149        workspace: WeakEntity<Workspace>,
 5150        transaction: ProjectTransaction,
 5151        title: String,
 5152        cx: &mut AsyncWindowContext,
 5153    ) -> Result<()> {
 5154        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5155        cx.update(|_, cx| {
 5156            entries.sort_unstable_by_key(|(buffer, _)| {
 5157                buffer.read(cx).file().map(|f| f.path().clone())
 5158            });
 5159        })?;
 5160
 5161        // If the project transaction's edits are all contained within this editor, then
 5162        // avoid opening a new editor to display them.
 5163
 5164        if let Some((buffer, transaction)) = entries.first() {
 5165            if entries.len() == 1 {
 5166                let excerpt = this.update(cx, |editor, cx| {
 5167                    editor
 5168                        .buffer()
 5169                        .read(cx)
 5170                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5171                })?;
 5172                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5173                    if excerpted_buffer == *buffer {
 5174                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5175                            let excerpt_range = excerpt_range.to_offset(buffer);
 5176                            buffer
 5177                                .edited_ranges_for_transaction::<usize>(transaction)
 5178                                .all(|range| {
 5179                                    excerpt_range.start <= range.start
 5180                                        && excerpt_range.end >= range.end
 5181                                })
 5182                        })?;
 5183
 5184                        if all_edits_within_excerpt {
 5185                            return Ok(());
 5186                        }
 5187                    }
 5188                }
 5189            }
 5190        } else {
 5191            return Ok(());
 5192        }
 5193
 5194        let mut ranges_to_highlight = Vec::new();
 5195        let excerpt_buffer = cx.new(|cx| {
 5196            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5197            for (buffer_handle, transaction) in &entries {
 5198                let edited_ranges = buffer_handle
 5199                    .read(cx)
 5200                    .edited_ranges_for_transaction::<Point>(transaction)
 5201                    .collect::<Vec<_>>();
 5202                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5203                    PathKey::for_buffer(buffer_handle, cx),
 5204                    buffer_handle.clone(),
 5205                    edited_ranges,
 5206                    DEFAULT_MULTIBUFFER_CONTEXT,
 5207                    cx,
 5208                );
 5209
 5210                ranges_to_highlight.extend(ranges);
 5211            }
 5212            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5213            multibuffer
 5214        })?;
 5215
 5216        workspace.update_in(cx, |workspace, window, cx| {
 5217            let project = workspace.project().clone();
 5218            let editor =
 5219                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5220            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5221            editor.update(cx, |editor, cx| {
 5222                editor.highlight_background::<Self>(
 5223                    &ranges_to_highlight,
 5224                    |theme| theme.editor_highlighted_line_background,
 5225                    cx,
 5226                );
 5227            });
 5228        })?;
 5229
 5230        Ok(())
 5231    }
 5232
 5233    pub fn clear_code_action_providers(&mut self) {
 5234        self.code_action_providers.clear();
 5235        self.available_code_actions.take();
 5236    }
 5237
 5238    pub fn add_code_action_provider(
 5239        &mut self,
 5240        provider: Rc<dyn CodeActionProvider>,
 5241        window: &mut Window,
 5242        cx: &mut Context<Self>,
 5243    ) {
 5244        if self
 5245            .code_action_providers
 5246            .iter()
 5247            .any(|existing_provider| existing_provider.id() == provider.id())
 5248        {
 5249            return;
 5250        }
 5251
 5252        self.code_action_providers.push(provider);
 5253        self.refresh_code_actions(window, cx);
 5254    }
 5255
 5256    pub fn remove_code_action_provider(
 5257        &mut self,
 5258        id: Arc<str>,
 5259        window: &mut Window,
 5260        cx: &mut Context<Self>,
 5261    ) {
 5262        self.code_action_providers
 5263            .retain(|provider| provider.id() != id);
 5264        self.refresh_code_actions(window, cx);
 5265    }
 5266
 5267    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5268        let newest_selection = self.selections.newest_anchor().clone();
 5269        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5270        let buffer = self.buffer.read(cx);
 5271        if newest_selection.head().diff_base_anchor.is_some() {
 5272            return None;
 5273        }
 5274        let (start_buffer, start) =
 5275            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5276        let (end_buffer, end) =
 5277            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5278        if start_buffer != end_buffer {
 5279            return None;
 5280        }
 5281
 5282        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5283            cx.background_executor()
 5284                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5285                .await;
 5286
 5287            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5288                let providers = this.code_action_providers.clone();
 5289                let tasks = this
 5290                    .code_action_providers
 5291                    .iter()
 5292                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5293                    .collect::<Vec<_>>();
 5294                (providers, tasks)
 5295            })?;
 5296
 5297            let mut actions = Vec::new();
 5298            for (provider, provider_actions) in
 5299                providers.into_iter().zip(future::join_all(tasks).await)
 5300            {
 5301                if let Some(provider_actions) = provider_actions.log_err() {
 5302                    actions.extend(provider_actions.into_iter().map(|action| {
 5303                        AvailableCodeAction {
 5304                            excerpt_id: newest_selection.start.excerpt_id,
 5305                            action,
 5306                            provider: provider.clone(),
 5307                        }
 5308                    }));
 5309                }
 5310            }
 5311
 5312            this.update(cx, |this, cx| {
 5313                this.available_code_actions = if actions.is_empty() {
 5314                    None
 5315                } else {
 5316                    Some((
 5317                        Location {
 5318                            buffer: start_buffer,
 5319                            range: start..end,
 5320                        },
 5321                        actions.into(),
 5322                    ))
 5323                };
 5324                cx.notify();
 5325            })
 5326        }));
 5327        None
 5328    }
 5329
 5330    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5331        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5332            self.show_git_blame_inline = false;
 5333
 5334            self.show_git_blame_inline_delay_task =
 5335                Some(cx.spawn_in(window, async move |this, cx| {
 5336                    cx.background_executor().timer(delay).await;
 5337
 5338                    this.update(cx, |this, cx| {
 5339                        this.show_git_blame_inline = true;
 5340                        cx.notify();
 5341                    })
 5342                    .log_err();
 5343                }));
 5344        }
 5345    }
 5346
 5347    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5348        if self.pending_rename.is_some() {
 5349            return None;
 5350        }
 5351
 5352        let provider = self.semantics_provider.clone()?;
 5353        let buffer = self.buffer.read(cx);
 5354        let newest_selection = self.selections.newest_anchor().clone();
 5355        let cursor_position = newest_selection.head();
 5356        let (cursor_buffer, cursor_buffer_position) =
 5357            buffer.text_anchor_for_position(cursor_position, cx)?;
 5358        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5359        if cursor_buffer != tail_buffer {
 5360            return None;
 5361        }
 5362        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5363        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5364            cx.background_executor()
 5365                .timer(Duration::from_millis(debounce))
 5366                .await;
 5367
 5368            let highlights = if let Some(highlights) = cx
 5369                .update(|cx| {
 5370                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5371                })
 5372                .ok()
 5373                .flatten()
 5374            {
 5375                highlights.await.log_err()
 5376            } else {
 5377                None
 5378            };
 5379
 5380            if let Some(highlights) = highlights {
 5381                this.update(cx, |this, cx| {
 5382                    if this.pending_rename.is_some() {
 5383                        return;
 5384                    }
 5385
 5386                    let buffer_id = cursor_position.buffer_id;
 5387                    let buffer = this.buffer.read(cx);
 5388                    if !buffer
 5389                        .text_anchor_for_position(cursor_position, cx)
 5390                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5391                    {
 5392                        return;
 5393                    }
 5394
 5395                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5396                    let mut write_ranges = Vec::new();
 5397                    let mut read_ranges = Vec::new();
 5398                    for highlight in highlights {
 5399                        for (excerpt_id, excerpt_range) in
 5400                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5401                        {
 5402                            let start = highlight
 5403                                .range
 5404                                .start
 5405                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5406                            let end = highlight
 5407                                .range
 5408                                .end
 5409                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5410                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5411                                continue;
 5412                            }
 5413
 5414                            let range = Anchor {
 5415                                buffer_id,
 5416                                excerpt_id,
 5417                                text_anchor: start,
 5418                                diff_base_anchor: None,
 5419                            }..Anchor {
 5420                                buffer_id,
 5421                                excerpt_id,
 5422                                text_anchor: end,
 5423                                diff_base_anchor: None,
 5424                            };
 5425                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5426                                write_ranges.push(range);
 5427                            } else {
 5428                                read_ranges.push(range);
 5429                            }
 5430                        }
 5431                    }
 5432
 5433                    this.highlight_background::<DocumentHighlightRead>(
 5434                        &read_ranges,
 5435                        |theme| theme.editor_document_highlight_read_background,
 5436                        cx,
 5437                    );
 5438                    this.highlight_background::<DocumentHighlightWrite>(
 5439                        &write_ranges,
 5440                        |theme| theme.editor_document_highlight_write_background,
 5441                        cx,
 5442                    );
 5443                    cx.notify();
 5444                })
 5445                .log_err();
 5446            }
 5447        }));
 5448        None
 5449    }
 5450
 5451    fn prepare_highlight_query_from_selection(
 5452        &mut self,
 5453        cx: &mut Context<Editor>,
 5454    ) -> Option<(String, Range<Anchor>)> {
 5455        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5456            return None;
 5457        }
 5458        if !EditorSettings::get_global(cx).selection_highlight {
 5459            return None;
 5460        }
 5461        if self.selections.count() != 1 || self.selections.line_mode {
 5462            return None;
 5463        }
 5464        let selection = self.selections.newest::<Point>(cx);
 5465        if selection.is_empty() || selection.start.row != selection.end.row {
 5466            return None;
 5467        }
 5468        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5469        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5470        let query = multi_buffer_snapshot
 5471            .text_for_range(selection_anchor_range.clone())
 5472            .collect::<String>();
 5473        if query.trim().is_empty() {
 5474            return None;
 5475        }
 5476        Some((query, selection_anchor_range))
 5477    }
 5478
 5479    fn update_selection_occurrence_highlights(
 5480        &mut self,
 5481        query_text: String,
 5482        query_range: Range<Anchor>,
 5483        multi_buffer_range_to_query: Range<Point>,
 5484        use_debounce: bool,
 5485        window: &mut Window,
 5486        cx: &mut Context<Editor>,
 5487    ) -> Task<()> {
 5488        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5489        cx.spawn_in(window, async move |editor, cx| {
 5490            if use_debounce {
 5491                cx.background_executor()
 5492                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5493                    .await;
 5494            }
 5495            let match_task = cx.background_spawn(async move {
 5496                let buffer_ranges = multi_buffer_snapshot
 5497                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5498                    .into_iter()
 5499                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5500                let mut match_ranges = Vec::new();
 5501                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5502                    match_ranges.extend(
 5503                        project::search::SearchQuery::text(
 5504                            query_text.clone(),
 5505                            false,
 5506                            false,
 5507                            false,
 5508                            Default::default(),
 5509                            Default::default(),
 5510                            false,
 5511                            None,
 5512                        )
 5513                        .unwrap()
 5514                        .search(&buffer_snapshot, Some(search_range.clone()))
 5515                        .await
 5516                        .into_iter()
 5517                        .filter_map(|match_range| {
 5518                            let match_start = buffer_snapshot
 5519                                .anchor_after(search_range.start + match_range.start);
 5520                            let match_end =
 5521                                buffer_snapshot.anchor_before(search_range.start + match_range.end);
 5522                            let match_anchor_range = Anchor::range_in_buffer(
 5523                                excerpt_id,
 5524                                buffer_snapshot.remote_id(),
 5525                                match_start..match_end,
 5526                            );
 5527                            (match_anchor_range != query_range).then_some(match_anchor_range)
 5528                        }),
 5529                    );
 5530                }
 5531                match_ranges
 5532            });
 5533            let match_ranges = match_task.await;
 5534            editor
 5535                .update_in(cx, |editor, _, cx| {
 5536                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5537                    if !match_ranges.is_empty() {
 5538                        editor.highlight_background::<SelectedTextHighlight>(
 5539                            &match_ranges,
 5540                            |theme| theme.editor_document_highlight_bracket_background,
 5541                            cx,
 5542                        )
 5543                    }
 5544                })
 5545                .log_err();
 5546        })
 5547    }
 5548
 5549    fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
 5550        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5551        else {
 5552            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5553            self.quick_selection_highlight_task.take();
 5554            self.debounced_selection_highlight_task.take();
 5555            return;
 5556        };
 5557        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5558        if self
 5559            .quick_selection_highlight_task
 5560            .as_ref()
 5561            .map_or(true, |(prev_anchor_range, _)| {
 5562                prev_anchor_range != &query_range
 5563            })
 5564        {
 5565            let multi_buffer_visible_start = self
 5566                .scroll_manager
 5567                .anchor()
 5568                .anchor
 5569                .to_point(&multi_buffer_snapshot);
 5570            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5571                multi_buffer_visible_start
 5572                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5573                Bias::Left,
 5574            );
 5575            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5576            self.quick_selection_highlight_task = Some((
 5577                query_range.clone(),
 5578                self.update_selection_occurrence_highlights(
 5579                    query_text.clone(),
 5580                    query_range.clone(),
 5581                    multi_buffer_visible_range,
 5582                    false,
 5583                    window,
 5584                    cx,
 5585                ),
 5586            ));
 5587        }
 5588        if self
 5589            .debounced_selection_highlight_task
 5590            .as_ref()
 5591            .map_or(true, |(prev_anchor_range, _)| {
 5592                prev_anchor_range != &query_range
 5593            })
 5594        {
 5595            let multi_buffer_start = multi_buffer_snapshot
 5596                .anchor_before(0)
 5597                .to_point(&multi_buffer_snapshot);
 5598            let multi_buffer_end = multi_buffer_snapshot
 5599                .anchor_after(multi_buffer_snapshot.len())
 5600                .to_point(&multi_buffer_snapshot);
 5601            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5602            self.debounced_selection_highlight_task = Some((
 5603                query_range.clone(),
 5604                self.update_selection_occurrence_highlights(
 5605                    query_text,
 5606                    query_range,
 5607                    multi_buffer_full_range,
 5608                    true,
 5609                    window,
 5610                    cx,
 5611                ),
 5612            ));
 5613        }
 5614    }
 5615
 5616    pub fn refresh_inline_completion(
 5617        &mut self,
 5618        debounce: bool,
 5619        user_requested: bool,
 5620        window: &mut Window,
 5621        cx: &mut Context<Self>,
 5622    ) -> Option<()> {
 5623        let provider = self.edit_prediction_provider()?;
 5624        let cursor = self.selections.newest_anchor().head();
 5625        let (buffer, cursor_buffer_position) =
 5626            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5627
 5628        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5629            self.discard_inline_completion(false, cx);
 5630            return None;
 5631        }
 5632
 5633        if !user_requested
 5634            && (!self.should_show_edit_predictions()
 5635                || !self.is_focused(window)
 5636                || buffer.read(cx).is_empty())
 5637        {
 5638            self.discard_inline_completion(false, cx);
 5639            return None;
 5640        }
 5641
 5642        self.update_visible_inline_completion(window, cx);
 5643        provider.refresh(
 5644            self.project.clone(),
 5645            buffer,
 5646            cursor_buffer_position,
 5647            debounce,
 5648            cx,
 5649        );
 5650        Some(())
 5651    }
 5652
 5653    fn show_edit_predictions_in_menu(&self) -> bool {
 5654        match self.edit_prediction_settings {
 5655            EditPredictionSettings::Disabled => false,
 5656            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5657        }
 5658    }
 5659
 5660    pub fn edit_predictions_enabled(&self) -> bool {
 5661        match self.edit_prediction_settings {
 5662            EditPredictionSettings::Disabled => false,
 5663            EditPredictionSettings::Enabled { .. } => true,
 5664        }
 5665    }
 5666
 5667    fn edit_prediction_requires_modifier(&self) -> bool {
 5668        match self.edit_prediction_settings {
 5669            EditPredictionSettings::Disabled => false,
 5670            EditPredictionSettings::Enabled {
 5671                preview_requires_modifier,
 5672                ..
 5673            } => preview_requires_modifier,
 5674        }
 5675    }
 5676
 5677    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5678        if self.edit_prediction_provider.is_none() {
 5679            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5680        } else {
 5681            let selection = self.selections.newest_anchor();
 5682            let cursor = selection.head();
 5683
 5684            if let Some((buffer, cursor_buffer_position)) =
 5685                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5686            {
 5687                self.edit_prediction_settings =
 5688                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5689            }
 5690        }
 5691    }
 5692
 5693    fn edit_prediction_settings_at_position(
 5694        &self,
 5695        buffer: &Entity<Buffer>,
 5696        buffer_position: language::Anchor,
 5697        cx: &App,
 5698    ) -> EditPredictionSettings {
 5699        if !self.mode.is_full()
 5700            || !self.show_inline_completions_override.unwrap_or(true)
 5701            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5702        {
 5703            return EditPredictionSettings::Disabled;
 5704        }
 5705
 5706        let buffer = buffer.read(cx);
 5707
 5708        let file = buffer.file();
 5709
 5710        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5711            return EditPredictionSettings::Disabled;
 5712        };
 5713
 5714        let by_provider = matches!(
 5715            self.menu_inline_completions_policy,
 5716            MenuInlineCompletionsPolicy::ByProvider
 5717        );
 5718
 5719        let show_in_menu = by_provider
 5720            && self
 5721                .edit_prediction_provider
 5722                .as_ref()
 5723                .map_or(false, |provider| {
 5724                    provider.provider.show_completions_in_menu()
 5725                });
 5726
 5727        let preview_requires_modifier =
 5728            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5729
 5730        EditPredictionSettings::Enabled {
 5731            show_in_menu,
 5732            preview_requires_modifier,
 5733        }
 5734    }
 5735
 5736    fn should_show_edit_predictions(&self) -> bool {
 5737        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5738    }
 5739
 5740    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5741        matches!(
 5742            self.edit_prediction_preview,
 5743            EditPredictionPreview::Active { .. }
 5744        )
 5745    }
 5746
 5747    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5748        let cursor = self.selections.newest_anchor().head();
 5749        if let Some((buffer, cursor_position)) =
 5750            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5751        {
 5752            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5753        } else {
 5754            false
 5755        }
 5756    }
 5757
 5758    fn edit_predictions_enabled_in_buffer(
 5759        &self,
 5760        buffer: &Entity<Buffer>,
 5761        buffer_position: language::Anchor,
 5762        cx: &App,
 5763    ) -> bool {
 5764        maybe!({
 5765            if self.read_only(cx) {
 5766                return Some(false);
 5767            }
 5768            let provider = self.edit_prediction_provider()?;
 5769            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5770                return Some(false);
 5771            }
 5772            let buffer = buffer.read(cx);
 5773            let Some(file) = buffer.file() else {
 5774                return Some(true);
 5775            };
 5776            let settings = all_language_settings(Some(file), cx);
 5777            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5778        })
 5779        .unwrap_or(false)
 5780    }
 5781
 5782    fn cycle_inline_completion(
 5783        &mut self,
 5784        direction: Direction,
 5785        window: &mut Window,
 5786        cx: &mut Context<Self>,
 5787    ) -> Option<()> {
 5788        let provider = self.edit_prediction_provider()?;
 5789        let cursor = self.selections.newest_anchor().head();
 5790        let (buffer, cursor_buffer_position) =
 5791            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5792        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5793            return None;
 5794        }
 5795
 5796        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5797        self.update_visible_inline_completion(window, cx);
 5798
 5799        Some(())
 5800    }
 5801
 5802    pub fn show_inline_completion(
 5803        &mut self,
 5804        _: &ShowEditPrediction,
 5805        window: &mut Window,
 5806        cx: &mut Context<Self>,
 5807    ) {
 5808        if !self.has_active_inline_completion() {
 5809            self.refresh_inline_completion(false, true, window, cx);
 5810            return;
 5811        }
 5812
 5813        self.update_visible_inline_completion(window, cx);
 5814    }
 5815
 5816    pub fn display_cursor_names(
 5817        &mut self,
 5818        _: &DisplayCursorNames,
 5819        window: &mut Window,
 5820        cx: &mut Context<Self>,
 5821    ) {
 5822        self.show_cursor_names(window, cx);
 5823    }
 5824
 5825    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5826        self.show_cursor_names = true;
 5827        cx.notify();
 5828        cx.spawn_in(window, async move |this, cx| {
 5829            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5830            this.update(cx, |this, cx| {
 5831                this.show_cursor_names = false;
 5832                cx.notify()
 5833            })
 5834            .ok()
 5835        })
 5836        .detach();
 5837    }
 5838
 5839    pub fn next_edit_prediction(
 5840        &mut self,
 5841        _: &NextEditPrediction,
 5842        window: &mut Window,
 5843        cx: &mut Context<Self>,
 5844    ) {
 5845        if self.has_active_inline_completion() {
 5846            self.cycle_inline_completion(Direction::Next, window, cx);
 5847        } else {
 5848            let is_copilot_disabled = self
 5849                .refresh_inline_completion(false, true, window, cx)
 5850                .is_none();
 5851            if is_copilot_disabled {
 5852                cx.propagate();
 5853            }
 5854        }
 5855    }
 5856
 5857    pub fn previous_edit_prediction(
 5858        &mut self,
 5859        _: &PreviousEditPrediction,
 5860        window: &mut Window,
 5861        cx: &mut Context<Self>,
 5862    ) {
 5863        if self.has_active_inline_completion() {
 5864            self.cycle_inline_completion(Direction::Prev, window, cx);
 5865        } else {
 5866            let is_copilot_disabled = self
 5867                .refresh_inline_completion(false, true, window, cx)
 5868                .is_none();
 5869            if is_copilot_disabled {
 5870                cx.propagate();
 5871            }
 5872        }
 5873    }
 5874
 5875    pub fn accept_edit_prediction(
 5876        &mut self,
 5877        _: &AcceptEditPrediction,
 5878        window: &mut Window,
 5879        cx: &mut Context<Self>,
 5880    ) {
 5881        if self.show_edit_predictions_in_menu() {
 5882            self.hide_context_menu(window, cx);
 5883        }
 5884
 5885        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5886            return;
 5887        };
 5888
 5889        self.report_inline_completion_event(
 5890            active_inline_completion.completion_id.clone(),
 5891            true,
 5892            cx,
 5893        );
 5894
 5895        match &active_inline_completion.completion {
 5896            InlineCompletion::Move { target, .. } => {
 5897                let target = *target;
 5898
 5899                if let Some(position_map) = &self.last_position_map {
 5900                    if position_map
 5901                        .visible_row_range
 5902                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5903                        || !self.edit_prediction_requires_modifier()
 5904                    {
 5905                        self.unfold_ranges(&[target..target], true, false, cx);
 5906                        // Note that this is also done in vim's handler of the Tab action.
 5907                        self.change_selections(
 5908                            Some(Autoscroll::newest()),
 5909                            window,
 5910                            cx,
 5911                            |selections| {
 5912                                selections.select_anchor_ranges([target..target]);
 5913                            },
 5914                        );
 5915                        self.clear_row_highlights::<EditPredictionPreview>();
 5916
 5917                        self.edit_prediction_preview
 5918                            .set_previous_scroll_position(None);
 5919                    } else {
 5920                        self.edit_prediction_preview
 5921                            .set_previous_scroll_position(Some(
 5922                                position_map.snapshot.scroll_anchor,
 5923                            ));
 5924
 5925                        self.highlight_rows::<EditPredictionPreview>(
 5926                            target..target,
 5927                            cx.theme().colors().editor_highlighted_line_background,
 5928                            true,
 5929                            cx,
 5930                        );
 5931                        self.request_autoscroll(Autoscroll::fit(), cx);
 5932                    }
 5933                }
 5934            }
 5935            InlineCompletion::Edit { edits, .. } => {
 5936                if let Some(provider) = self.edit_prediction_provider() {
 5937                    provider.accept(cx);
 5938                }
 5939
 5940                let snapshot = self.buffer.read(cx).snapshot(cx);
 5941                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5942
 5943                self.buffer.update(cx, |buffer, cx| {
 5944                    buffer.edit(edits.iter().cloned(), None, cx)
 5945                });
 5946
 5947                self.change_selections(None, window, cx, |s| {
 5948                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5949                });
 5950
 5951                self.update_visible_inline_completion(window, cx);
 5952                if self.active_inline_completion.is_none() {
 5953                    self.refresh_inline_completion(true, true, window, cx);
 5954                }
 5955
 5956                cx.notify();
 5957            }
 5958        }
 5959
 5960        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5961    }
 5962
 5963    pub fn accept_partial_inline_completion(
 5964        &mut self,
 5965        _: &AcceptPartialEditPrediction,
 5966        window: &mut Window,
 5967        cx: &mut Context<Self>,
 5968    ) {
 5969        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5970            return;
 5971        };
 5972        if self.selections.count() != 1 {
 5973            return;
 5974        }
 5975
 5976        self.report_inline_completion_event(
 5977            active_inline_completion.completion_id.clone(),
 5978            true,
 5979            cx,
 5980        );
 5981
 5982        match &active_inline_completion.completion {
 5983            InlineCompletion::Move { target, .. } => {
 5984                let target = *target;
 5985                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5986                    selections.select_anchor_ranges([target..target]);
 5987                });
 5988            }
 5989            InlineCompletion::Edit { edits, .. } => {
 5990                // Find an insertion that starts at the cursor position.
 5991                let snapshot = self.buffer.read(cx).snapshot(cx);
 5992                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5993                let insertion = edits.iter().find_map(|(range, text)| {
 5994                    let range = range.to_offset(&snapshot);
 5995                    if range.is_empty() && range.start == cursor_offset {
 5996                        Some(text)
 5997                    } else {
 5998                        None
 5999                    }
 6000                });
 6001
 6002                if let Some(text) = insertion {
 6003                    let mut partial_completion = text
 6004                        .chars()
 6005                        .by_ref()
 6006                        .take_while(|c| c.is_alphabetic())
 6007                        .collect::<String>();
 6008                    if partial_completion.is_empty() {
 6009                        partial_completion = text
 6010                            .chars()
 6011                            .by_ref()
 6012                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6013                            .collect::<String>();
 6014                    }
 6015
 6016                    cx.emit(EditorEvent::InputHandled {
 6017                        utf16_range_to_replace: None,
 6018                        text: partial_completion.clone().into(),
 6019                    });
 6020
 6021                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6022
 6023                    self.refresh_inline_completion(true, true, window, cx);
 6024                    cx.notify();
 6025                } else {
 6026                    self.accept_edit_prediction(&Default::default(), window, cx);
 6027                }
 6028            }
 6029        }
 6030    }
 6031
 6032    fn discard_inline_completion(
 6033        &mut self,
 6034        should_report_inline_completion_event: bool,
 6035        cx: &mut Context<Self>,
 6036    ) -> bool {
 6037        if should_report_inline_completion_event {
 6038            let completion_id = self
 6039                .active_inline_completion
 6040                .as_ref()
 6041                .and_then(|active_completion| active_completion.completion_id.clone());
 6042
 6043            self.report_inline_completion_event(completion_id, false, cx);
 6044        }
 6045
 6046        if let Some(provider) = self.edit_prediction_provider() {
 6047            provider.discard(cx);
 6048        }
 6049
 6050        self.take_active_inline_completion(cx)
 6051    }
 6052
 6053    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6054        let Some(provider) = self.edit_prediction_provider() else {
 6055            return;
 6056        };
 6057
 6058        let Some((_, buffer, _)) = self
 6059            .buffer
 6060            .read(cx)
 6061            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6062        else {
 6063            return;
 6064        };
 6065
 6066        let extension = buffer
 6067            .read(cx)
 6068            .file()
 6069            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6070
 6071        let event_type = match accepted {
 6072            true => "Edit Prediction Accepted",
 6073            false => "Edit Prediction Discarded",
 6074        };
 6075        telemetry::event!(
 6076            event_type,
 6077            provider = provider.name(),
 6078            prediction_id = id,
 6079            suggestion_accepted = accepted,
 6080            file_extension = extension,
 6081        );
 6082    }
 6083
 6084    pub fn has_active_inline_completion(&self) -> bool {
 6085        self.active_inline_completion.is_some()
 6086    }
 6087
 6088    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6089        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6090            return false;
 6091        };
 6092
 6093        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6094        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6095        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6096        true
 6097    }
 6098
 6099    /// Returns true when we're displaying the edit prediction popover below the cursor
 6100    /// like we are not previewing and the LSP autocomplete menu is visible
 6101    /// or we are in `when_holding_modifier` mode.
 6102    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6103        if self.edit_prediction_preview_is_active()
 6104            || !self.show_edit_predictions_in_menu()
 6105            || !self.edit_predictions_enabled()
 6106        {
 6107            return false;
 6108        }
 6109
 6110        if self.has_visible_completions_menu() {
 6111            return true;
 6112        }
 6113
 6114        has_completion && self.edit_prediction_requires_modifier()
 6115    }
 6116
 6117    fn handle_modifiers_changed(
 6118        &mut self,
 6119        modifiers: Modifiers,
 6120        position_map: &PositionMap,
 6121        window: &mut Window,
 6122        cx: &mut Context<Self>,
 6123    ) {
 6124        if self.show_edit_predictions_in_menu() {
 6125            self.update_edit_prediction_preview(&modifiers, window, cx);
 6126        }
 6127
 6128        self.update_selection_mode(&modifiers, position_map, window, cx);
 6129
 6130        let mouse_position = window.mouse_position();
 6131        if !position_map.text_hitbox.is_hovered(window) {
 6132            return;
 6133        }
 6134
 6135        self.update_hovered_link(
 6136            position_map.point_for_position(mouse_position),
 6137            &position_map.snapshot,
 6138            modifiers,
 6139            window,
 6140            cx,
 6141        )
 6142    }
 6143
 6144    fn update_selection_mode(
 6145        &mut self,
 6146        modifiers: &Modifiers,
 6147        position_map: &PositionMap,
 6148        window: &mut Window,
 6149        cx: &mut Context<Self>,
 6150    ) {
 6151        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6152            return;
 6153        }
 6154
 6155        let mouse_position = window.mouse_position();
 6156        let point_for_position = position_map.point_for_position(mouse_position);
 6157        let position = point_for_position.previous_valid;
 6158
 6159        self.select(
 6160            SelectPhase::BeginColumnar {
 6161                position,
 6162                reset: false,
 6163                goal_column: point_for_position.exact_unclipped.column(),
 6164            },
 6165            window,
 6166            cx,
 6167        );
 6168    }
 6169
 6170    fn update_edit_prediction_preview(
 6171        &mut self,
 6172        modifiers: &Modifiers,
 6173        window: &mut Window,
 6174        cx: &mut Context<Self>,
 6175    ) {
 6176        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6177        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6178            return;
 6179        };
 6180
 6181        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6182            if matches!(
 6183                self.edit_prediction_preview,
 6184                EditPredictionPreview::Inactive { .. }
 6185            ) {
 6186                self.edit_prediction_preview = EditPredictionPreview::Active {
 6187                    previous_scroll_position: None,
 6188                    since: Instant::now(),
 6189                };
 6190
 6191                self.update_visible_inline_completion(window, cx);
 6192                cx.notify();
 6193            }
 6194        } else if let EditPredictionPreview::Active {
 6195            previous_scroll_position,
 6196            since,
 6197        } = self.edit_prediction_preview
 6198        {
 6199            if let (Some(previous_scroll_position), Some(position_map)) =
 6200                (previous_scroll_position, self.last_position_map.as_ref())
 6201            {
 6202                self.set_scroll_position(
 6203                    previous_scroll_position
 6204                        .scroll_position(&position_map.snapshot.display_snapshot),
 6205                    window,
 6206                    cx,
 6207                );
 6208            }
 6209
 6210            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6211                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6212            };
 6213            self.clear_row_highlights::<EditPredictionPreview>();
 6214            self.update_visible_inline_completion(window, cx);
 6215            cx.notify();
 6216        }
 6217    }
 6218
 6219    fn update_visible_inline_completion(
 6220        &mut self,
 6221        _window: &mut Window,
 6222        cx: &mut Context<Self>,
 6223    ) -> Option<()> {
 6224        let selection = self.selections.newest_anchor();
 6225        let cursor = selection.head();
 6226        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6227        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6228        let excerpt_id = cursor.excerpt_id;
 6229
 6230        let show_in_menu = self.show_edit_predictions_in_menu();
 6231        let completions_menu_has_precedence = !show_in_menu
 6232            && (self.context_menu.borrow().is_some()
 6233                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6234
 6235        if completions_menu_has_precedence
 6236            || !offset_selection.is_empty()
 6237            || self
 6238                .active_inline_completion
 6239                .as_ref()
 6240                .map_or(false, |completion| {
 6241                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6242                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6243                    !invalidation_range.contains(&offset_selection.head())
 6244                })
 6245        {
 6246            self.discard_inline_completion(false, cx);
 6247            return None;
 6248        }
 6249
 6250        self.take_active_inline_completion(cx);
 6251        let Some(provider) = self.edit_prediction_provider() else {
 6252            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6253            return None;
 6254        };
 6255
 6256        let (buffer, cursor_buffer_position) =
 6257            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6258
 6259        self.edit_prediction_settings =
 6260            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6261
 6262        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6263
 6264        if self.edit_prediction_indent_conflict {
 6265            let cursor_point = cursor.to_point(&multibuffer);
 6266
 6267            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6268
 6269            if let Some((_, indent)) = indents.iter().next() {
 6270                if indent.len == cursor_point.column {
 6271                    self.edit_prediction_indent_conflict = false;
 6272                }
 6273            }
 6274        }
 6275
 6276        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6277        let edits = inline_completion
 6278            .edits
 6279            .into_iter()
 6280            .flat_map(|(range, new_text)| {
 6281                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6282                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6283                Some((start..end, new_text))
 6284            })
 6285            .collect::<Vec<_>>();
 6286        if edits.is_empty() {
 6287            return None;
 6288        }
 6289
 6290        let first_edit_start = edits.first().unwrap().0.start;
 6291        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6292        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6293
 6294        let last_edit_end = edits.last().unwrap().0.end;
 6295        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6296        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6297
 6298        let cursor_row = cursor.to_point(&multibuffer).row;
 6299
 6300        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6301
 6302        let mut inlay_ids = Vec::new();
 6303        let invalidation_row_range;
 6304        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6305            Some(cursor_row..edit_end_row)
 6306        } else if cursor_row > edit_end_row {
 6307            Some(edit_start_row..cursor_row)
 6308        } else {
 6309            None
 6310        };
 6311        let is_move =
 6312            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6313        let completion = if is_move {
 6314            invalidation_row_range =
 6315                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6316            let target = first_edit_start;
 6317            InlineCompletion::Move { target, snapshot }
 6318        } else {
 6319            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6320                && !self.inline_completions_hidden_for_vim_mode;
 6321
 6322            if show_completions_in_buffer {
 6323                if edits
 6324                    .iter()
 6325                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6326                {
 6327                    let mut inlays = Vec::new();
 6328                    for (range, new_text) in &edits {
 6329                        let inlay = Inlay::inline_completion(
 6330                            post_inc(&mut self.next_inlay_id),
 6331                            range.start,
 6332                            new_text.as_str(),
 6333                        );
 6334                        inlay_ids.push(inlay.id);
 6335                        inlays.push(inlay);
 6336                    }
 6337
 6338                    self.splice_inlays(&[], inlays, cx);
 6339                } else {
 6340                    let background_color = cx.theme().status().deleted_background;
 6341                    self.highlight_text::<InlineCompletionHighlight>(
 6342                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6343                        HighlightStyle {
 6344                            background_color: Some(background_color),
 6345                            ..Default::default()
 6346                        },
 6347                        cx,
 6348                    );
 6349                }
 6350            }
 6351
 6352            invalidation_row_range = edit_start_row..edit_end_row;
 6353
 6354            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6355                if provider.show_tab_accept_marker() {
 6356                    EditDisplayMode::TabAccept
 6357                } else {
 6358                    EditDisplayMode::Inline
 6359                }
 6360            } else {
 6361                EditDisplayMode::DiffPopover
 6362            };
 6363
 6364            InlineCompletion::Edit {
 6365                edits,
 6366                edit_preview: inline_completion.edit_preview,
 6367                display_mode,
 6368                snapshot,
 6369            }
 6370        };
 6371
 6372        let invalidation_range = multibuffer
 6373            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6374            ..multibuffer.anchor_after(Point::new(
 6375                invalidation_row_range.end,
 6376                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6377            ));
 6378
 6379        self.stale_inline_completion_in_menu = None;
 6380        self.active_inline_completion = Some(InlineCompletionState {
 6381            inlay_ids,
 6382            completion,
 6383            completion_id: inline_completion.id,
 6384            invalidation_range,
 6385        });
 6386
 6387        cx.notify();
 6388
 6389        Some(())
 6390    }
 6391
 6392    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6393        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6394    }
 6395
 6396    fn render_code_actions_indicator(
 6397        &self,
 6398        _style: &EditorStyle,
 6399        row: DisplayRow,
 6400        is_active: bool,
 6401        breakpoint: Option<&(Anchor, Breakpoint)>,
 6402        cx: &mut Context<Self>,
 6403    ) -> Option<IconButton> {
 6404        let color = Color::Muted;
 6405        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6406        let show_tooltip = !self.context_menu_visible();
 6407
 6408        if self.available_code_actions.is_some() {
 6409            Some(
 6410                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6411                    .shape(ui::IconButtonShape::Square)
 6412                    .icon_size(IconSize::XSmall)
 6413                    .icon_color(color)
 6414                    .toggle_state(is_active)
 6415                    .when(show_tooltip, |this| {
 6416                        this.tooltip({
 6417                            let focus_handle = self.focus_handle.clone();
 6418                            move |window, cx| {
 6419                                Tooltip::for_action_in(
 6420                                    "Toggle Code Actions",
 6421                                    &ToggleCodeActions {
 6422                                        deployed_from_indicator: None,
 6423                                    },
 6424                                    &focus_handle,
 6425                                    window,
 6426                                    cx,
 6427                                )
 6428                            }
 6429                        })
 6430                    })
 6431                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6432                        window.focus(&editor.focus_handle(cx));
 6433                        editor.toggle_code_actions(
 6434                            &ToggleCodeActions {
 6435                                deployed_from_indicator: Some(row),
 6436                            },
 6437                            window,
 6438                            cx,
 6439                        );
 6440                    }))
 6441                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6442                        editor.set_breakpoint_context_menu(
 6443                            row,
 6444                            position,
 6445                            event.down.position,
 6446                            window,
 6447                            cx,
 6448                        );
 6449                    })),
 6450            )
 6451        } else {
 6452            None
 6453        }
 6454    }
 6455
 6456    fn clear_tasks(&mut self) {
 6457        self.tasks.clear()
 6458    }
 6459
 6460    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6461        if self.tasks.insert(key, value).is_some() {
 6462            // This case should hopefully be rare, but just in case...
 6463            log::error!(
 6464                "multiple different run targets found on a single line, only the last target will be rendered"
 6465            )
 6466        }
 6467    }
 6468
 6469    /// Get all display points of breakpoints that will be rendered within editor
 6470    ///
 6471    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6472    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6473    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6474    fn active_breakpoints(
 6475        &self,
 6476        range: Range<DisplayRow>,
 6477        window: &mut Window,
 6478        cx: &mut Context<Self>,
 6479    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6480        let mut breakpoint_display_points = HashMap::default();
 6481
 6482        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6483            return breakpoint_display_points;
 6484        };
 6485
 6486        let snapshot = self.snapshot(window, cx);
 6487
 6488        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6489        let Some(project) = self.project.as_ref() else {
 6490            return breakpoint_display_points;
 6491        };
 6492
 6493        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6494            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6495
 6496        for (buffer_snapshot, range, excerpt_id) in
 6497            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6498        {
 6499            let Some(buffer) = project.read_with(cx, |this, cx| {
 6500                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6501            }) else {
 6502                continue;
 6503            };
 6504            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6505                &buffer,
 6506                Some(
 6507                    buffer_snapshot.anchor_before(range.start)
 6508                        ..buffer_snapshot.anchor_after(range.end),
 6509                ),
 6510                buffer_snapshot,
 6511                cx,
 6512            );
 6513            for (anchor, breakpoint) in breakpoints {
 6514                let multi_buffer_anchor =
 6515                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6516                let position = multi_buffer_anchor
 6517                    .to_point(&multi_buffer_snapshot)
 6518                    .to_display_point(&snapshot);
 6519
 6520                breakpoint_display_points
 6521                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6522            }
 6523        }
 6524
 6525        breakpoint_display_points
 6526    }
 6527
 6528    fn breakpoint_context_menu(
 6529        &self,
 6530        anchor: Anchor,
 6531        window: &mut Window,
 6532        cx: &mut Context<Self>,
 6533    ) -> Entity<ui::ContextMenu> {
 6534        let weak_editor = cx.weak_entity();
 6535        let focus_handle = self.focus_handle(cx);
 6536
 6537        let row = self
 6538            .buffer
 6539            .read(cx)
 6540            .snapshot(cx)
 6541            .summary_for_anchor::<Point>(&anchor)
 6542            .row;
 6543
 6544        let breakpoint = self
 6545            .breakpoint_at_row(row, window, cx)
 6546            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6547
 6548        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6549            "Edit Log Breakpoint"
 6550        } else {
 6551            "Set Log Breakpoint"
 6552        };
 6553
 6554        let condition_breakpoint_msg = if breakpoint
 6555            .as_ref()
 6556            .is_some_and(|bp| bp.1.condition.is_some())
 6557        {
 6558            "Edit Condition Breakpoint"
 6559        } else {
 6560            "Set Condition Breakpoint"
 6561        };
 6562
 6563        let hit_condition_breakpoint_msg = if breakpoint
 6564            .as_ref()
 6565            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6566        {
 6567            "Edit Hit Condition Breakpoint"
 6568        } else {
 6569            "Set Hit Condition Breakpoint"
 6570        };
 6571
 6572        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6573            "Unset Breakpoint"
 6574        } else {
 6575            "Set Breakpoint"
 6576        };
 6577
 6578        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6579            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6580
 6581        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6582            BreakpointState::Enabled => Some("Disable"),
 6583            BreakpointState::Disabled => Some("Enable"),
 6584        });
 6585
 6586        let (anchor, breakpoint) =
 6587            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6588
 6589        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6590            menu.on_blur_subscription(Subscription::new(|| {}))
 6591                .context(focus_handle)
 6592                .when(run_to_cursor, |this| {
 6593                    let weak_editor = weak_editor.clone();
 6594                    this.entry("Run to cursor", None, move |window, cx| {
 6595                        weak_editor
 6596                            .update(cx, |editor, cx| {
 6597                                editor.change_selections(None, window, cx, |s| {
 6598                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6599                                });
 6600                            })
 6601                            .ok();
 6602
 6603                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6604                    })
 6605                    .separator()
 6606                })
 6607                .when_some(toggle_state_msg, |this, msg| {
 6608                    this.entry(msg, None, {
 6609                        let weak_editor = weak_editor.clone();
 6610                        let breakpoint = breakpoint.clone();
 6611                        move |_window, cx| {
 6612                            weak_editor
 6613                                .update(cx, |this, cx| {
 6614                                    this.edit_breakpoint_at_anchor(
 6615                                        anchor,
 6616                                        breakpoint.as_ref().clone(),
 6617                                        BreakpointEditAction::InvertState,
 6618                                        cx,
 6619                                    );
 6620                                })
 6621                                .log_err();
 6622                        }
 6623                    })
 6624                })
 6625                .entry(set_breakpoint_msg, None, {
 6626                    let weak_editor = weak_editor.clone();
 6627                    let breakpoint = breakpoint.clone();
 6628                    move |_window, cx| {
 6629                        weak_editor
 6630                            .update(cx, |this, cx| {
 6631                                this.edit_breakpoint_at_anchor(
 6632                                    anchor,
 6633                                    breakpoint.as_ref().clone(),
 6634                                    BreakpointEditAction::Toggle,
 6635                                    cx,
 6636                                );
 6637                            })
 6638                            .log_err();
 6639                    }
 6640                })
 6641                .entry(log_breakpoint_msg, None, {
 6642                    let breakpoint = breakpoint.clone();
 6643                    let weak_editor = weak_editor.clone();
 6644                    move |window, cx| {
 6645                        weak_editor
 6646                            .update(cx, |this, cx| {
 6647                                this.add_edit_breakpoint_block(
 6648                                    anchor,
 6649                                    breakpoint.as_ref(),
 6650                                    BreakpointPromptEditAction::Log,
 6651                                    window,
 6652                                    cx,
 6653                                );
 6654                            })
 6655                            .log_err();
 6656                    }
 6657                })
 6658                .entry(condition_breakpoint_msg, None, {
 6659                    let breakpoint = breakpoint.clone();
 6660                    let weak_editor = weak_editor.clone();
 6661                    move |window, cx| {
 6662                        weak_editor
 6663                            .update(cx, |this, cx| {
 6664                                this.add_edit_breakpoint_block(
 6665                                    anchor,
 6666                                    breakpoint.as_ref(),
 6667                                    BreakpointPromptEditAction::Condition,
 6668                                    window,
 6669                                    cx,
 6670                                );
 6671                            })
 6672                            .log_err();
 6673                    }
 6674                })
 6675                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6676                    weak_editor
 6677                        .update(cx, |this, cx| {
 6678                            this.add_edit_breakpoint_block(
 6679                                anchor,
 6680                                breakpoint.as_ref(),
 6681                                BreakpointPromptEditAction::HitCondition,
 6682                                window,
 6683                                cx,
 6684                            );
 6685                        })
 6686                        .log_err();
 6687                })
 6688        })
 6689    }
 6690
 6691    fn render_breakpoint(
 6692        &self,
 6693        position: Anchor,
 6694        row: DisplayRow,
 6695        breakpoint: &Breakpoint,
 6696        cx: &mut Context<Self>,
 6697    ) -> IconButton {
 6698        let (color, icon) = {
 6699            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6700                (false, false) => ui::IconName::DebugBreakpoint,
 6701                (true, false) => ui::IconName::DebugLogBreakpoint,
 6702                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6703                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6704            };
 6705
 6706            let color = if self
 6707                .gutter_breakpoint_indicator
 6708                .0
 6709                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6710            {
 6711                Color::Hint
 6712            } else {
 6713                Color::Debugger
 6714            };
 6715
 6716            (color, icon)
 6717        };
 6718
 6719        let breakpoint = Arc::from(breakpoint.clone());
 6720
 6721        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6722            .icon_size(IconSize::XSmall)
 6723            .size(ui::ButtonSize::None)
 6724            .icon_color(color)
 6725            .style(ButtonStyle::Transparent)
 6726            .on_click(cx.listener({
 6727                let breakpoint = breakpoint.clone();
 6728
 6729                move |editor, event: &ClickEvent, window, cx| {
 6730                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6731                        BreakpointEditAction::InvertState
 6732                    } else {
 6733                        BreakpointEditAction::Toggle
 6734                    };
 6735
 6736                    window.focus(&editor.focus_handle(cx));
 6737                    editor.edit_breakpoint_at_anchor(
 6738                        position,
 6739                        breakpoint.as_ref().clone(),
 6740                        edit_action,
 6741                        cx,
 6742                    );
 6743                }
 6744            }))
 6745            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6746                editor.set_breakpoint_context_menu(
 6747                    row,
 6748                    Some(position),
 6749                    event.down.position,
 6750                    window,
 6751                    cx,
 6752                );
 6753            }))
 6754    }
 6755
 6756    fn build_tasks_context(
 6757        project: &Entity<Project>,
 6758        buffer: &Entity<Buffer>,
 6759        buffer_row: u32,
 6760        tasks: &Arc<RunnableTasks>,
 6761        cx: &mut Context<Self>,
 6762    ) -> Task<Option<task::TaskContext>> {
 6763        let position = Point::new(buffer_row, tasks.column);
 6764        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6765        let location = Location {
 6766            buffer: buffer.clone(),
 6767            range: range_start..range_start,
 6768        };
 6769        // Fill in the environmental variables from the tree-sitter captures
 6770        let mut captured_task_variables = TaskVariables::default();
 6771        for (capture_name, value) in tasks.extra_variables.clone() {
 6772            captured_task_variables.insert(
 6773                task::VariableName::Custom(capture_name.into()),
 6774                value.clone(),
 6775            );
 6776        }
 6777        project.update(cx, |project, cx| {
 6778            project.task_store().update(cx, |task_store, cx| {
 6779                task_store.task_context_for_location(captured_task_variables, location, cx)
 6780            })
 6781        })
 6782    }
 6783
 6784    pub fn spawn_nearest_task(
 6785        &mut self,
 6786        action: &SpawnNearestTask,
 6787        window: &mut Window,
 6788        cx: &mut Context<Self>,
 6789    ) {
 6790        let Some((workspace, _)) = self.workspace.clone() else {
 6791            return;
 6792        };
 6793        let Some(project) = self.project.clone() else {
 6794            return;
 6795        };
 6796
 6797        // Try to find a closest, enclosing node using tree-sitter that has a
 6798        // task
 6799        let Some((buffer, buffer_row, tasks)) = self
 6800            .find_enclosing_node_task(cx)
 6801            // Or find the task that's closest in row-distance.
 6802            .or_else(|| self.find_closest_task(cx))
 6803        else {
 6804            return;
 6805        };
 6806
 6807        let reveal_strategy = action.reveal;
 6808        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6809        cx.spawn_in(window, async move |_, cx| {
 6810            let context = task_context.await?;
 6811            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6812
 6813            let resolved = resolved_task.resolved.as_mut()?;
 6814            resolved.reveal = reveal_strategy;
 6815
 6816            workspace
 6817                .update(cx, |workspace, cx| {
 6818                    workspace::tasks::schedule_resolved_task(
 6819                        workspace,
 6820                        task_source_kind,
 6821                        resolved_task,
 6822                        false,
 6823                        cx,
 6824                    );
 6825                })
 6826                .ok()
 6827        })
 6828        .detach();
 6829    }
 6830
 6831    fn find_closest_task(
 6832        &mut self,
 6833        cx: &mut Context<Self>,
 6834    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6835        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6836
 6837        let ((buffer_id, row), tasks) = self
 6838            .tasks
 6839            .iter()
 6840            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6841
 6842        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6843        let tasks = Arc::new(tasks.to_owned());
 6844        Some((buffer, *row, tasks))
 6845    }
 6846
 6847    fn find_enclosing_node_task(
 6848        &mut self,
 6849        cx: &mut Context<Self>,
 6850    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6851        let snapshot = self.buffer.read(cx).snapshot(cx);
 6852        let offset = self.selections.newest::<usize>(cx).head();
 6853        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6854        let buffer_id = excerpt.buffer().remote_id();
 6855
 6856        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6857        let mut cursor = layer.node().walk();
 6858
 6859        while cursor.goto_first_child_for_byte(offset).is_some() {
 6860            if cursor.node().end_byte() == offset {
 6861                cursor.goto_next_sibling();
 6862            }
 6863        }
 6864
 6865        // Ascend to the smallest ancestor that contains the range and has a task.
 6866        loop {
 6867            let node = cursor.node();
 6868            let node_range = node.byte_range();
 6869            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6870
 6871            // Check if this node contains our offset
 6872            if node_range.start <= offset && node_range.end >= offset {
 6873                // If it contains offset, check for task
 6874                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6875                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6876                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6877                }
 6878            }
 6879
 6880            if !cursor.goto_parent() {
 6881                break;
 6882            }
 6883        }
 6884        None
 6885    }
 6886
 6887    fn render_run_indicator(
 6888        &self,
 6889        _style: &EditorStyle,
 6890        is_active: bool,
 6891        row: DisplayRow,
 6892        breakpoint: Option<(Anchor, Breakpoint)>,
 6893        cx: &mut Context<Self>,
 6894    ) -> IconButton {
 6895        let color = Color::Muted;
 6896        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6897
 6898        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6899            .shape(ui::IconButtonShape::Square)
 6900            .icon_size(IconSize::XSmall)
 6901            .icon_color(color)
 6902            .toggle_state(is_active)
 6903            .on_click(cx.listener(move |editor, _e, window, cx| {
 6904                window.focus(&editor.focus_handle(cx));
 6905                editor.toggle_code_actions(
 6906                    &ToggleCodeActions {
 6907                        deployed_from_indicator: Some(row),
 6908                    },
 6909                    window,
 6910                    cx,
 6911                );
 6912            }))
 6913            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6914                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6915            }))
 6916    }
 6917
 6918    pub fn context_menu_visible(&self) -> bool {
 6919        !self.edit_prediction_preview_is_active()
 6920            && self
 6921                .context_menu
 6922                .borrow()
 6923                .as_ref()
 6924                .map_or(false, |menu| menu.visible())
 6925    }
 6926
 6927    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6928        self.context_menu
 6929            .borrow()
 6930            .as_ref()
 6931            .map(|menu| menu.origin())
 6932    }
 6933
 6934    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6935        self.context_menu_options = Some(options);
 6936    }
 6937
 6938    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6939    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6940
 6941    fn render_edit_prediction_popover(
 6942        &mut self,
 6943        text_bounds: &Bounds<Pixels>,
 6944        content_origin: gpui::Point<Pixels>,
 6945        editor_snapshot: &EditorSnapshot,
 6946        visible_row_range: Range<DisplayRow>,
 6947        scroll_top: f32,
 6948        scroll_bottom: f32,
 6949        line_layouts: &[LineWithInvisibles],
 6950        line_height: Pixels,
 6951        scroll_pixel_position: gpui::Point<Pixels>,
 6952        newest_selection_head: Option<DisplayPoint>,
 6953        editor_width: Pixels,
 6954        style: &EditorStyle,
 6955        window: &mut Window,
 6956        cx: &mut App,
 6957    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6958        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6959
 6960        if self.edit_prediction_visible_in_cursor_popover(true) {
 6961            return None;
 6962        }
 6963
 6964        match &active_inline_completion.completion {
 6965            InlineCompletion::Move { target, .. } => {
 6966                let target_display_point = target.to_display_point(editor_snapshot);
 6967
 6968                if self.edit_prediction_requires_modifier() {
 6969                    if !self.edit_prediction_preview_is_active() {
 6970                        return None;
 6971                    }
 6972
 6973                    self.render_edit_prediction_modifier_jump_popover(
 6974                        text_bounds,
 6975                        content_origin,
 6976                        visible_row_range,
 6977                        line_layouts,
 6978                        line_height,
 6979                        scroll_pixel_position,
 6980                        newest_selection_head,
 6981                        target_display_point,
 6982                        window,
 6983                        cx,
 6984                    )
 6985                } else {
 6986                    self.render_edit_prediction_eager_jump_popover(
 6987                        text_bounds,
 6988                        content_origin,
 6989                        editor_snapshot,
 6990                        visible_row_range,
 6991                        scroll_top,
 6992                        scroll_bottom,
 6993                        line_height,
 6994                        scroll_pixel_position,
 6995                        target_display_point,
 6996                        editor_width,
 6997                        window,
 6998                        cx,
 6999                    )
 7000                }
 7001            }
 7002            InlineCompletion::Edit {
 7003                display_mode: EditDisplayMode::Inline,
 7004                ..
 7005            } => None,
 7006            InlineCompletion::Edit {
 7007                display_mode: EditDisplayMode::TabAccept,
 7008                edits,
 7009                ..
 7010            } => {
 7011                let range = &edits.first()?.0;
 7012                let target_display_point = range.end.to_display_point(editor_snapshot);
 7013
 7014                self.render_edit_prediction_end_of_line_popover(
 7015                    "Accept",
 7016                    editor_snapshot,
 7017                    visible_row_range,
 7018                    target_display_point,
 7019                    line_height,
 7020                    scroll_pixel_position,
 7021                    content_origin,
 7022                    editor_width,
 7023                    window,
 7024                    cx,
 7025                )
 7026            }
 7027            InlineCompletion::Edit {
 7028                edits,
 7029                edit_preview,
 7030                display_mode: EditDisplayMode::DiffPopover,
 7031                snapshot,
 7032            } => self.render_edit_prediction_diff_popover(
 7033                text_bounds,
 7034                content_origin,
 7035                editor_snapshot,
 7036                visible_row_range,
 7037                line_layouts,
 7038                line_height,
 7039                scroll_pixel_position,
 7040                newest_selection_head,
 7041                editor_width,
 7042                style,
 7043                edits,
 7044                edit_preview,
 7045                snapshot,
 7046                window,
 7047                cx,
 7048            ),
 7049        }
 7050    }
 7051
 7052    fn render_edit_prediction_modifier_jump_popover(
 7053        &mut self,
 7054        text_bounds: &Bounds<Pixels>,
 7055        content_origin: gpui::Point<Pixels>,
 7056        visible_row_range: Range<DisplayRow>,
 7057        line_layouts: &[LineWithInvisibles],
 7058        line_height: Pixels,
 7059        scroll_pixel_position: gpui::Point<Pixels>,
 7060        newest_selection_head: Option<DisplayPoint>,
 7061        target_display_point: DisplayPoint,
 7062        window: &mut Window,
 7063        cx: &mut App,
 7064    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7065        let scrolled_content_origin =
 7066            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7067
 7068        const SCROLL_PADDING_Y: Pixels = px(12.);
 7069
 7070        if target_display_point.row() < visible_row_range.start {
 7071            return self.render_edit_prediction_scroll_popover(
 7072                |_| SCROLL_PADDING_Y,
 7073                IconName::ArrowUp,
 7074                visible_row_range,
 7075                line_layouts,
 7076                newest_selection_head,
 7077                scrolled_content_origin,
 7078                window,
 7079                cx,
 7080            );
 7081        } else if target_display_point.row() >= visible_row_range.end {
 7082            return self.render_edit_prediction_scroll_popover(
 7083                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7084                IconName::ArrowDown,
 7085                visible_row_range,
 7086                line_layouts,
 7087                newest_selection_head,
 7088                scrolled_content_origin,
 7089                window,
 7090                cx,
 7091            );
 7092        }
 7093
 7094        const POLE_WIDTH: Pixels = px(2.);
 7095
 7096        let line_layout =
 7097            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7098        let target_column = target_display_point.column() as usize;
 7099
 7100        let target_x = line_layout.x_for_index(target_column);
 7101        let target_y =
 7102            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7103
 7104        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7105
 7106        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7107        border_color.l += 0.001;
 7108
 7109        let mut element = v_flex()
 7110            .items_end()
 7111            .when(flag_on_right, |el| el.items_start())
 7112            .child(if flag_on_right {
 7113                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7114                    .rounded_bl(px(0.))
 7115                    .rounded_tl(px(0.))
 7116                    .border_l_2()
 7117                    .border_color(border_color)
 7118            } else {
 7119                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7120                    .rounded_br(px(0.))
 7121                    .rounded_tr(px(0.))
 7122                    .border_r_2()
 7123                    .border_color(border_color)
 7124            })
 7125            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7126            .into_any();
 7127
 7128        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7129
 7130        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7131            - point(
 7132                if flag_on_right {
 7133                    POLE_WIDTH
 7134                } else {
 7135                    size.width - POLE_WIDTH
 7136                },
 7137                size.height - line_height,
 7138            );
 7139
 7140        origin.x = origin.x.max(content_origin.x);
 7141
 7142        element.prepaint_at(origin, window, cx);
 7143
 7144        Some((element, origin))
 7145    }
 7146
 7147    fn render_edit_prediction_scroll_popover(
 7148        &mut self,
 7149        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7150        scroll_icon: IconName,
 7151        visible_row_range: Range<DisplayRow>,
 7152        line_layouts: &[LineWithInvisibles],
 7153        newest_selection_head: Option<DisplayPoint>,
 7154        scrolled_content_origin: gpui::Point<Pixels>,
 7155        window: &mut Window,
 7156        cx: &mut App,
 7157    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7158        let mut element = self
 7159            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7160            .into_any();
 7161
 7162        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7163
 7164        let cursor = newest_selection_head?;
 7165        let cursor_row_layout =
 7166            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7167        let cursor_column = cursor.column() as usize;
 7168
 7169        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7170
 7171        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7172
 7173        element.prepaint_at(origin, window, cx);
 7174        Some((element, origin))
 7175    }
 7176
 7177    fn render_edit_prediction_eager_jump_popover(
 7178        &mut self,
 7179        text_bounds: &Bounds<Pixels>,
 7180        content_origin: gpui::Point<Pixels>,
 7181        editor_snapshot: &EditorSnapshot,
 7182        visible_row_range: Range<DisplayRow>,
 7183        scroll_top: f32,
 7184        scroll_bottom: f32,
 7185        line_height: Pixels,
 7186        scroll_pixel_position: gpui::Point<Pixels>,
 7187        target_display_point: DisplayPoint,
 7188        editor_width: Pixels,
 7189        window: &mut Window,
 7190        cx: &mut App,
 7191    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7192        if target_display_point.row().as_f32() < scroll_top {
 7193            let mut element = self
 7194                .render_edit_prediction_line_popover(
 7195                    "Jump to Edit",
 7196                    Some(IconName::ArrowUp),
 7197                    window,
 7198                    cx,
 7199                )?
 7200                .into_any();
 7201
 7202            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7203            let offset = point(
 7204                (text_bounds.size.width - size.width) / 2.,
 7205                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7206            );
 7207
 7208            let origin = text_bounds.origin + offset;
 7209            element.prepaint_at(origin, window, cx);
 7210            Some((element, origin))
 7211        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7212            let mut element = self
 7213                .render_edit_prediction_line_popover(
 7214                    "Jump to Edit",
 7215                    Some(IconName::ArrowDown),
 7216                    window,
 7217                    cx,
 7218                )?
 7219                .into_any();
 7220
 7221            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7222            let offset = point(
 7223                (text_bounds.size.width - size.width) / 2.,
 7224                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7225            );
 7226
 7227            let origin = text_bounds.origin + offset;
 7228            element.prepaint_at(origin, window, cx);
 7229            Some((element, origin))
 7230        } else {
 7231            self.render_edit_prediction_end_of_line_popover(
 7232                "Jump to Edit",
 7233                editor_snapshot,
 7234                visible_row_range,
 7235                target_display_point,
 7236                line_height,
 7237                scroll_pixel_position,
 7238                content_origin,
 7239                editor_width,
 7240                window,
 7241                cx,
 7242            )
 7243        }
 7244    }
 7245
 7246    fn render_edit_prediction_end_of_line_popover(
 7247        self: &mut Editor,
 7248        label: &'static str,
 7249        editor_snapshot: &EditorSnapshot,
 7250        visible_row_range: Range<DisplayRow>,
 7251        target_display_point: DisplayPoint,
 7252        line_height: Pixels,
 7253        scroll_pixel_position: gpui::Point<Pixels>,
 7254        content_origin: gpui::Point<Pixels>,
 7255        editor_width: Pixels,
 7256        window: &mut Window,
 7257        cx: &mut App,
 7258    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7259        let target_line_end = DisplayPoint::new(
 7260            target_display_point.row(),
 7261            editor_snapshot.line_len(target_display_point.row()),
 7262        );
 7263
 7264        let mut element = self
 7265            .render_edit_prediction_line_popover(label, None, window, cx)?
 7266            .into_any();
 7267
 7268        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7269
 7270        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7271
 7272        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7273        let mut origin = start_point
 7274            + line_origin
 7275            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7276        origin.x = origin.x.max(content_origin.x);
 7277
 7278        let max_x = content_origin.x + editor_width - size.width;
 7279
 7280        if origin.x > max_x {
 7281            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7282
 7283            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7284                origin.y += offset;
 7285                IconName::ArrowUp
 7286            } else {
 7287                origin.y -= offset;
 7288                IconName::ArrowDown
 7289            };
 7290
 7291            element = self
 7292                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7293                .into_any();
 7294
 7295            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7296
 7297            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7298        }
 7299
 7300        element.prepaint_at(origin, window, cx);
 7301        Some((element, origin))
 7302    }
 7303
 7304    fn render_edit_prediction_diff_popover(
 7305        self: &Editor,
 7306        text_bounds: &Bounds<Pixels>,
 7307        content_origin: gpui::Point<Pixels>,
 7308        editor_snapshot: &EditorSnapshot,
 7309        visible_row_range: Range<DisplayRow>,
 7310        line_layouts: &[LineWithInvisibles],
 7311        line_height: Pixels,
 7312        scroll_pixel_position: gpui::Point<Pixels>,
 7313        newest_selection_head: Option<DisplayPoint>,
 7314        editor_width: Pixels,
 7315        style: &EditorStyle,
 7316        edits: &Vec<(Range<Anchor>, String)>,
 7317        edit_preview: &Option<language::EditPreview>,
 7318        snapshot: &language::BufferSnapshot,
 7319        window: &mut Window,
 7320        cx: &mut App,
 7321    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7322        let edit_start = edits
 7323            .first()
 7324            .unwrap()
 7325            .0
 7326            .start
 7327            .to_display_point(editor_snapshot);
 7328        let edit_end = edits
 7329            .last()
 7330            .unwrap()
 7331            .0
 7332            .end
 7333            .to_display_point(editor_snapshot);
 7334
 7335        let is_visible = visible_row_range.contains(&edit_start.row())
 7336            || visible_row_range.contains(&edit_end.row());
 7337        if !is_visible {
 7338            return None;
 7339        }
 7340
 7341        let highlighted_edits =
 7342            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7343
 7344        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7345        let line_count = highlighted_edits.text.lines().count();
 7346
 7347        const BORDER_WIDTH: Pixels = px(1.);
 7348
 7349        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7350        let has_keybind = keybind.is_some();
 7351
 7352        let mut element = h_flex()
 7353            .items_start()
 7354            .child(
 7355                h_flex()
 7356                    .bg(cx.theme().colors().editor_background)
 7357                    .border(BORDER_WIDTH)
 7358                    .shadow_sm()
 7359                    .border_color(cx.theme().colors().border)
 7360                    .rounded_l_lg()
 7361                    .when(line_count > 1, |el| el.rounded_br_lg())
 7362                    .pr_1()
 7363                    .child(styled_text),
 7364            )
 7365            .child(
 7366                h_flex()
 7367                    .h(line_height + BORDER_WIDTH * 2.)
 7368                    .px_1p5()
 7369                    .gap_1()
 7370                    // Workaround: For some reason, there's a gap if we don't do this
 7371                    .ml(-BORDER_WIDTH)
 7372                    .shadow(smallvec![gpui::BoxShadow {
 7373                        color: gpui::black().opacity(0.05),
 7374                        offset: point(px(1.), px(1.)),
 7375                        blur_radius: px(2.),
 7376                        spread_radius: px(0.),
 7377                    }])
 7378                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7379                    .border(BORDER_WIDTH)
 7380                    .border_color(cx.theme().colors().border)
 7381                    .rounded_r_lg()
 7382                    .id("edit_prediction_diff_popover_keybind")
 7383                    .when(!has_keybind, |el| {
 7384                        let status_colors = cx.theme().status();
 7385
 7386                        el.bg(status_colors.error_background)
 7387                            .border_color(status_colors.error.opacity(0.6))
 7388                            .child(Icon::new(IconName::Info).color(Color::Error))
 7389                            .cursor_default()
 7390                            .hoverable_tooltip(move |_window, cx| {
 7391                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7392                            })
 7393                    })
 7394                    .children(keybind),
 7395            )
 7396            .into_any();
 7397
 7398        let longest_row =
 7399            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7400        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7401            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7402        } else {
 7403            layout_line(
 7404                longest_row,
 7405                editor_snapshot,
 7406                style,
 7407                editor_width,
 7408                |_| false,
 7409                window,
 7410                cx,
 7411            )
 7412            .width
 7413        };
 7414
 7415        let viewport_bounds =
 7416            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7417                right: -EditorElement::SCROLLBAR_WIDTH,
 7418                ..Default::default()
 7419            });
 7420
 7421        let x_after_longest =
 7422            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7423                - scroll_pixel_position.x;
 7424
 7425        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7426
 7427        // Fully visible if it can be displayed within the window (allow overlapping other
 7428        // panes). However, this is only allowed if the popover starts within text_bounds.
 7429        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7430            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7431
 7432        let mut origin = if can_position_to_the_right {
 7433            point(
 7434                x_after_longest,
 7435                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7436                    - scroll_pixel_position.y,
 7437            )
 7438        } else {
 7439            let cursor_row = newest_selection_head.map(|head| head.row());
 7440            let above_edit = edit_start
 7441                .row()
 7442                .0
 7443                .checked_sub(line_count as u32)
 7444                .map(DisplayRow);
 7445            let below_edit = Some(edit_end.row() + 1);
 7446            let above_cursor =
 7447                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7448            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7449
 7450            // Place the edit popover adjacent to the edit if there is a location
 7451            // available that is onscreen and does not obscure the cursor. Otherwise,
 7452            // place it adjacent to the cursor.
 7453            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7454                .into_iter()
 7455                .flatten()
 7456                .find(|&start_row| {
 7457                    let end_row = start_row + line_count as u32;
 7458                    visible_row_range.contains(&start_row)
 7459                        && visible_row_range.contains(&end_row)
 7460                        && cursor_row.map_or(true, |cursor_row| {
 7461                            !((start_row..end_row).contains(&cursor_row))
 7462                        })
 7463                })?;
 7464
 7465            content_origin
 7466                + point(
 7467                    -scroll_pixel_position.x,
 7468                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7469                )
 7470        };
 7471
 7472        origin.x -= BORDER_WIDTH;
 7473
 7474        window.defer_draw(element, origin, 1);
 7475
 7476        // Do not return an element, since it will already be drawn due to defer_draw.
 7477        None
 7478    }
 7479
 7480    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7481        px(30.)
 7482    }
 7483
 7484    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7485        if self.read_only(cx) {
 7486            cx.theme().players().read_only()
 7487        } else {
 7488            self.style.as_ref().unwrap().local_player
 7489        }
 7490    }
 7491
 7492    fn render_edit_prediction_accept_keybind(
 7493        &self,
 7494        window: &mut Window,
 7495        cx: &App,
 7496    ) -> Option<AnyElement> {
 7497        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7498        let accept_keystroke = accept_binding.keystroke()?;
 7499
 7500        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7501
 7502        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7503            Color::Accent
 7504        } else {
 7505            Color::Muted
 7506        };
 7507
 7508        h_flex()
 7509            .px_0p5()
 7510            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7511            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7512            .text_size(TextSize::XSmall.rems(cx))
 7513            .child(h_flex().children(ui::render_modifiers(
 7514                &accept_keystroke.modifiers,
 7515                PlatformStyle::platform(),
 7516                Some(modifiers_color),
 7517                Some(IconSize::XSmall.rems().into()),
 7518                true,
 7519            )))
 7520            .when(is_platform_style_mac, |parent| {
 7521                parent.child(accept_keystroke.key.clone())
 7522            })
 7523            .when(!is_platform_style_mac, |parent| {
 7524                parent.child(
 7525                    Key::new(
 7526                        util::capitalize(&accept_keystroke.key),
 7527                        Some(Color::Default),
 7528                    )
 7529                    .size(Some(IconSize::XSmall.rems().into())),
 7530                )
 7531            })
 7532            .into_any()
 7533            .into()
 7534    }
 7535
 7536    fn render_edit_prediction_line_popover(
 7537        &self,
 7538        label: impl Into<SharedString>,
 7539        icon: Option<IconName>,
 7540        window: &mut Window,
 7541        cx: &App,
 7542    ) -> Option<Stateful<Div>> {
 7543        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7544
 7545        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7546        let has_keybind = keybind.is_some();
 7547
 7548        let result = h_flex()
 7549            .id("ep-line-popover")
 7550            .py_0p5()
 7551            .pl_1()
 7552            .pr(padding_right)
 7553            .gap_1()
 7554            .rounded_md()
 7555            .border_1()
 7556            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7557            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7558            .shadow_sm()
 7559            .when(!has_keybind, |el| {
 7560                let status_colors = cx.theme().status();
 7561
 7562                el.bg(status_colors.error_background)
 7563                    .border_color(status_colors.error.opacity(0.6))
 7564                    .pl_2()
 7565                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7566                    .cursor_default()
 7567                    .hoverable_tooltip(move |_window, cx| {
 7568                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7569                    })
 7570            })
 7571            .children(keybind)
 7572            .child(
 7573                Label::new(label)
 7574                    .size(LabelSize::Small)
 7575                    .when(!has_keybind, |el| {
 7576                        el.color(cx.theme().status().error.into()).strikethrough()
 7577                    }),
 7578            )
 7579            .when(!has_keybind, |el| {
 7580                el.child(
 7581                    h_flex().ml_1().child(
 7582                        Icon::new(IconName::Info)
 7583                            .size(IconSize::Small)
 7584                            .color(cx.theme().status().error.into()),
 7585                    ),
 7586                )
 7587            })
 7588            .when_some(icon, |element, icon| {
 7589                element.child(
 7590                    div()
 7591                        .mt(px(1.5))
 7592                        .child(Icon::new(icon).size(IconSize::Small)),
 7593                )
 7594            });
 7595
 7596        Some(result)
 7597    }
 7598
 7599    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7600        let accent_color = cx.theme().colors().text_accent;
 7601        let editor_bg_color = cx.theme().colors().editor_background;
 7602        editor_bg_color.blend(accent_color.opacity(0.1))
 7603    }
 7604
 7605    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7606        let accent_color = cx.theme().colors().text_accent;
 7607        let editor_bg_color = cx.theme().colors().editor_background;
 7608        editor_bg_color.blend(accent_color.opacity(0.6))
 7609    }
 7610
 7611    fn render_edit_prediction_cursor_popover(
 7612        &self,
 7613        min_width: Pixels,
 7614        max_width: Pixels,
 7615        cursor_point: Point,
 7616        style: &EditorStyle,
 7617        accept_keystroke: Option<&gpui::Keystroke>,
 7618        _window: &Window,
 7619        cx: &mut Context<Editor>,
 7620    ) -> Option<AnyElement> {
 7621        let provider = self.edit_prediction_provider.as_ref()?;
 7622
 7623        if provider.provider.needs_terms_acceptance(cx) {
 7624            return Some(
 7625                h_flex()
 7626                    .min_w(min_width)
 7627                    .flex_1()
 7628                    .px_2()
 7629                    .py_1()
 7630                    .gap_3()
 7631                    .elevation_2(cx)
 7632                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7633                    .id("accept-terms")
 7634                    .cursor_pointer()
 7635                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7636                    .on_click(cx.listener(|this, _event, window, cx| {
 7637                        cx.stop_propagation();
 7638                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7639                        window.dispatch_action(
 7640                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7641                            cx,
 7642                        );
 7643                    }))
 7644                    .child(
 7645                        h_flex()
 7646                            .flex_1()
 7647                            .gap_2()
 7648                            .child(Icon::new(IconName::ZedPredict))
 7649                            .child(Label::new("Accept Terms of Service"))
 7650                            .child(div().w_full())
 7651                            .child(
 7652                                Icon::new(IconName::ArrowUpRight)
 7653                                    .color(Color::Muted)
 7654                                    .size(IconSize::Small),
 7655                            )
 7656                            .into_any_element(),
 7657                    )
 7658                    .into_any(),
 7659            );
 7660        }
 7661
 7662        let is_refreshing = provider.provider.is_refreshing(cx);
 7663
 7664        fn pending_completion_container() -> Div {
 7665            h_flex()
 7666                .h_full()
 7667                .flex_1()
 7668                .gap_2()
 7669                .child(Icon::new(IconName::ZedPredict))
 7670        }
 7671
 7672        let completion = match &self.active_inline_completion {
 7673            Some(prediction) => {
 7674                if !self.has_visible_completions_menu() {
 7675                    const RADIUS: Pixels = px(6.);
 7676                    const BORDER_WIDTH: Pixels = px(1.);
 7677
 7678                    return Some(
 7679                        h_flex()
 7680                            .elevation_2(cx)
 7681                            .border(BORDER_WIDTH)
 7682                            .border_color(cx.theme().colors().border)
 7683                            .when(accept_keystroke.is_none(), |el| {
 7684                                el.border_color(cx.theme().status().error)
 7685                            })
 7686                            .rounded(RADIUS)
 7687                            .rounded_tl(px(0.))
 7688                            .overflow_hidden()
 7689                            .child(div().px_1p5().child(match &prediction.completion {
 7690                                InlineCompletion::Move { target, snapshot } => {
 7691                                    use text::ToPoint as _;
 7692                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7693                                    {
 7694                                        Icon::new(IconName::ZedPredictDown)
 7695                                    } else {
 7696                                        Icon::new(IconName::ZedPredictUp)
 7697                                    }
 7698                                }
 7699                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7700                            }))
 7701                            .child(
 7702                                h_flex()
 7703                                    .gap_1()
 7704                                    .py_1()
 7705                                    .px_2()
 7706                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7707                                    .border_l_1()
 7708                                    .border_color(cx.theme().colors().border)
 7709                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7710                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7711                                        el.child(
 7712                                            Label::new("Hold")
 7713                                                .size(LabelSize::Small)
 7714                                                .when(accept_keystroke.is_none(), |el| {
 7715                                                    el.strikethrough()
 7716                                                })
 7717                                                .line_height_style(LineHeightStyle::UiLabel),
 7718                                        )
 7719                                    })
 7720                                    .id("edit_prediction_cursor_popover_keybind")
 7721                                    .when(accept_keystroke.is_none(), |el| {
 7722                                        let status_colors = cx.theme().status();
 7723
 7724                                        el.bg(status_colors.error_background)
 7725                                            .border_color(status_colors.error.opacity(0.6))
 7726                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7727                                            .cursor_default()
 7728                                            .hoverable_tooltip(move |_window, cx| {
 7729                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7730                                                    .into()
 7731                                            })
 7732                                    })
 7733                                    .when_some(
 7734                                        accept_keystroke.as_ref(),
 7735                                        |el, accept_keystroke| {
 7736                                            el.child(h_flex().children(ui::render_modifiers(
 7737                                                &accept_keystroke.modifiers,
 7738                                                PlatformStyle::platform(),
 7739                                                Some(Color::Default),
 7740                                                Some(IconSize::XSmall.rems().into()),
 7741                                                false,
 7742                                            )))
 7743                                        },
 7744                                    ),
 7745                            )
 7746                            .into_any(),
 7747                    );
 7748                }
 7749
 7750                self.render_edit_prediction_cursor_popover_preview(
 7751                    prediction,
 7752                    cursor_point,
 7753                    style,
 7754                    cx,
 7755                )?
 7756            }
 7757
 7758            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7759                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7760                    stale_completion,
 7761                    cursor_point,
 7762                    style,
 7763                    cx,
 7764                )?,
 7765
 7766                None => {
 7767                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7768                }
 7769            },
 7770
 7771            None => pending_completion_container().child(Label::new("No Prediction")),
 7772        };
 7773
 7774        let completion = if is_refreshing {
 7775            completion
 7776                .with_animation(
 7777                    "loading-completion",
 7778                    Animation::new(Duration::from_secs(2))
 7779                        .repeat()
 7780                        .with_easing(pulsating_between(0.4, 0.8)),
 7781                    |label, delta| label.opacity(delta),
 7782                )
 7783                .into_any_element()
 7784        } else {
 7785            completion.into_any_element()
 7786        };
 7787
 7788        let has_completion = self.active_inline_completion.is_some();
 7789
 7790        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7791        Some(
 7792            h_flex()
 7793                .min_w(min_width)
 7794                .max_w(max_width)
 7795                .flex_1()
 7796                .elevation_2(cx)
 7797                .border_color(cx.theme().colors().border)
 7798                .child(
 7799                    div()
 7800                        .flex_1()
 7801                        .py_1()
 7802                        .px_2()
 7803                        .overflow_hidden()
 7804                        .child(completion),
 7805                )
 7806                .when_some(accept_keystroke, |el, accept_keystroke| {
 7807                    if !accept_keystroke.modifiers.modified() {
 7808                        return el;
 7809                    }
 7810
 7811                    el.child(
 7812                        h_flex()
 7813                            .h_full()
 7814                            .border_l_1()
 7815                            .rounded_r_lg()
 7816                            .border_color(cx.theme().colors().border)
 7817                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7818                            .gap_1()
 7819                            .py_1()
 7820                            .px_2()
 7821                            .child(
 7822                                h_flex()
 7823                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7824                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7825                                    .child(h_flex().children(ui::render_modifiers(
 7826                                        &accept_keystroke.modifiers,
 7827                                        PlatformStyle::platform(),
 7828                                        Some(if !has_completion {
 7829                                            Color::Muted
 7830                                        } else {
 7831                                            Color::Default
 7832                                        }),
 7833                                        None,
 7834                                        false,
 7835                                    ))),
 7836                            )
 7837                            .child(Label::new("Preview").into_any_element())
 7838                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7839                    )
 7840                })
 7841                .into_any(),
 7842        )
 7843    }
 7844
 7845    fn render_edit_prediction_cursor_popover_preview(
 7846        &self,
 7847        completion: &InlineCompletionState,
 7848        cursor_point: Point,
 7849        style: &EditorStyle,
 7850        cx: &mut Context<Editor>,
 7851    ) -> Option<Div> {
 7852        use text::ToPoint as _;
 7853
 7854        fn render_relative_row_jump(
 7855            prefix: impl Into<String>,
 7856            current_row: u32,
 7857            target_row: u32,
 7858        ) -> Div {
 7859            let (row_diff, arrow) = if target_row < current_row {
 7860                (current_row - target_row, IconName::ArrowUp)
 7861            } else {
 7862                (target_row - current_row, IconName::ArrowDown)
 7863            };
 7864
 7865            h_flex()
 7866                .child(
 7867                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7868                        .color(Color::Muted)
 7869                        .size(LabelSize::Small),
 7870                )
 7871                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7872        }
 7873
 7874        match &completion.completion {
 7875            InlineCompletion::Move {
 7876                target, snapshot, ..
 7877            } => Some(
 7878                h_flex()
 7879                    .px_2()
 7880                    .gap_2()
 7881                    .flex_1()
 7882                    .child(
 7883                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7884                            Icon::new(IconName::ZedPredictDown)
 7885                        } else {
 7886                            Icon::new(IconName::ZedPredictUp)
 7887                        },
 7888                    )
 7889                    .child(Label::new("Jump to Edit")),
 7890            ),
 7891
 7892            InlineCompletion::Edit {
 7893                edits,
 7894                edit_preview,
 7895                snapshot,
 7896                display_mode: _,
 7897            } => {
 7898                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7899
 7900                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7901                    &snapshot,
 7902                    &edits,
 7903                    edit_preview.as_ref()?,
 7904                    true,
 7905                    cx,
 7906                )
 7907                .first_line_preview();
 7908
 7909                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7910                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7911
 7912                let preview = h_flex()
 7913                    .gap_1()
 7914                    .min_w_16()
 7915                    .child(styled_text)
 7916                    .when(has_more_lines, |parent| parent.child(""));
 7917
 7918                let left = if first_edit_row != cursor_point.row {
 7919                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7920                        .into_any_element()
 7921                } else {
 7922                    Icon::new(IconName::ZedPredict).into_any_element()
 7923                };
 7924
 7925                Some(
 7926                    h_flex()
 7927                        .h_full()
 7928                        .flex_1()
 7929                        .gap_2()
 7930                        .pr_1()
 7931                        .overflow_x_hidden()
 7932                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7933                        .child(left)
 7934                        .child(preview),
 7935                )
 7936            }
 7937        }
 7938    }
 7939
 7940    fn render_context_menu(
 7941        &self,
 7942        style: &EditorStyle,
 7943        max_height_in_lines: u32,
 7944        window: &mut Window,
 7945        cx: &mut Context<Editor>,
 7946    ) -> Option<AnyElement> {
 7947        let menu = self.context_menu.borrow();
 7948        let menu = menu.as_ref()?;
 7949        if !menu.visible() {
 7950            return None;
 7951        };
 7952        Some(menu.render(style, max_height_in_lines, window, cx))
 7953    }
 7954
 7955    fn render_context_menu_aside(
 7956        &mut self,
 7957        max_size: Size<Pixels>,
 7958        window: &mut Window,
 7959        cx: &mut Context<Editor>,
 7960    ) -> Option<AnyElement> {
 7961        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7962            if menu.visible() {
 7963                menu.render_aside(self, max_size, window, cx)
 7964            } else {
 7965                None
 7966            }
 7967        })
 7968    }
 7969
 7970    fn hide_context_menu(
 7971        &mut self,
 7972        window: &mut Window,
 7973        cx: &mut Context<Self>,
 7974    ) -> Option<CodeContextMenu> {
 7975        cx.notify();
 7976        self.completion_tasks.clear();
 7977        let context_menu = self.context_menu.borrow_mut().take();
 7978        self.stale_inline_completion_in_menu.take();
 7979        self.update_visible_inline_completion(window, cx);
 7980        context_menu
 7981    }
 7982
 7983    fn show_snippet_choices(
 7984        &mut self,
 7985        choices: &Vec<String>,
 7986        selection: Range<Anchor>,
 7987        cx: &mut Context<Self>,
 7988    ) {
 7989        if selection.start.buffer_id.is_none() {
 7990            return;
 7991        }
 7992        let buffer_id = selection.start.buffer_id.unwrap();
 7993        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7994        let id = post_inc(&mut self.next_completion_id);
 7995
 7996        if let Some(buffer) = buffer {
 7997            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7998                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7999            ));
 8000        }
 8001    }
 8002
 8003    pub fn insert_snippet(
 8004        &mut self,
 8005        insertion_ranges: &[Range<usize>],
 8006        snippet: Snippet,
 8007        window: &mut Window,
 8008        cx: &mut Context<Self>,
 8009    ) -> Result<()> {
 8010        struct Tabstop<T> {
 8011            is_end_tabstop: bool,
 8012            ranges: Vec<Range<T>>,
 8013            choices: Option<Vec<String>>,
 8014        }
 8015
 8016        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8017            let snippet_text: Arc<str> = snippet.text.clone().into();
 8018            let edits = insertion_ranges
 8019                .iter()
 8020                .cloned()
 8021                .map(|range| (range, snippet_text.clone()));
 8022            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8023
 8024            let snapshot = &*buffer.read(cx);
 8025            let snippet = &snippet;
 8026            snippet
 8027                .tabstops
 8028                .iter()
 8029                .map(|tabstop| {
 8030                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8031                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8032                    });
 8033                    let mut tabstop_ranges = tabstop
 8034                        .ranges
 8035                        .iter()
 8036                        .flat_map(|tabstop_range| {
 8037                            let mut delta = 0_isize;
 8038                            insertion_ranges.iter().map(move |insertion_range| {
 8039                                let insertion_start = insertion_range.start as isize + delta;
 8040                                delta +=
 8041                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8042
 8043                                let start = ((insertion_start + tabstop_range.start) as usize)
 8044                                    .min(snapshot.len());
 8045                                let end = ((insertion_start + tabstop_range.end) as usize)
 8046                                    .min(snapshot.len());
 8047                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8048                            })
 8049                        })
 8050                        .collect::<Vec<_>>();
 8051                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8052
 8053                    Tabstop {
 8054                        is_end_tabstop,
 8055                        ranges: tabstop_ranges,
 8056                        choices: tabstop.choices.clone(),
 8057                    }
 8058                })
 8059                .collect::<Vec<_>>()
 8060        });
 8061        if let Some(tabstop) = tabstops.first() {
 8062            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8063                s.select_ranges(tabstop.ranges.iter().cloned());
 8064            });
 8065
 8066            if let Some(choices) = &tabstop.choices {
 8067                if let Some(selection) = tabstop.ranges.first() {
 8068                    self.show_snippet_choices(choices, selection.clone(), cx)
 8069                }
 8070            }
 8071
 8072            // If we're already at the last tabstop and it's at the end of the snippet,
 8073            // we're done, we don't need to keep the state around.
 8074            if !tabstop.is_end_tabstop {
 8075                let choices = tabstops
 8076                    .iter()
 8077                    .map(|tabstop| tabstop.choices.clone())
 8078                    .collect();
 8079
 8080                let ranges = tabstops
 8081                    .into_iter()
 8082                    .map(|tabstop| tabstop.ranges)
 8083                    .collect::<Vec<_>>();
 8084
 8085                self.snippet_stack.push(SnippetState {
 8086                    active_index: 0,
 8087                    ranges,
 8088                    choices,
 8089                });
 8090            }
 8091
 8092            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8093            if self.autoclose_regions.is_empty() {
 8094                let snapshot = self.buffer.read(cx).snapshot(cx);
 8095                for selection in &mut self.selections.all::<Point>(cx) {
 8096                    let selection_head = selection.head();
 8097                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8098                        continue;
 8099                    };
 8100
 8101                    let mut bracket_pair = None;
 8102                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8103                    let prev_chars = snapshot
 8104                        .reversed_chars_at(selection_head)
 8105                        .collect::<String>();
 8106                    for (pair, enabled) in scope.brackets() {
 8107                        if enabled
 8108                            && pair.close
 8109                            && prev_chars.starts_with(pair.start.as_str())
 8110                            && next_chars.starts_with(pair.end.as_str())
 8111                        {
 8112                            bracket_pair = Some(pair.clone());
 8113                            break;
 8114                        }
 8115                    }
 8116                    if let Some(pair) = bracket_pair {
 8117                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8118                        let autoclose_enabled =
 8119                            self.use_autoclose && snapshot_settings.use_autoclose;
 8120                        if autoclose_enabled {
 8121                            let start = snapshot.anchor_after(selection_head);
 8122                            let end = snapshot.anchor_after(selection_head);
 8123                            self.autoclose_regions.push(AutocloseRegion {
 8124                                selection_id: selection.id,
 8125                                range: start..end,
 8126                                pair,
 8127                            });
 8128                        }
 8129                    }
 8130                }
 8131            }
 8132        }
 8133        Ok(())
 8134    }
 8135
 8136    pub fn move_to_next_snippet_tabstop(
 8137        &mut self,
 8138        window: &mut Window,
 8139        cx: &mut Context<Self>,
 8140    ) -> bool {
 8141        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8142    }
 8143
 8144    pub fn move_to_prev_snippet_tabstop(
 8145        &mut self,
 8146        window: &mut Window,
 8147        cx: &mut Context<Self>,
 8148    ) -> bool {
 8149        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8150    }
 8151
 8152    pub fn move_to_snippet_tabstop(
 8153        &mut self,
 8154        bias: Bias,
 8155        window: &mut Window,
 8156        cx: &mut Context<Self>,
 8157    ) -> bool {
 8158        if let Some(mut snippet) = self.snippet_stack.pop() {
 8159            match bias {
 8160                Bias::Left => {
 8161                    if snippet.active_index > 0 {
 8162                        snippet.active_index -= 1;
 8163                    } else {
 8164                        self.snippet_stack.push(snippet);
 8165                        return false;
 8166                    }
 8167                }
 8168                Bias::Right => {
 8169                    if snippet.active_index + 1 < snippet.ranges.len() {
 8170                        snippet.active_index += 1;
 8171                    } else {
 8172                        self.snippet_stack.push(snippet);
 8173                        return false;
 8174                    }
 8175                }
 8176            }
 8177            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8178                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8179                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8180                });
 8181
 8182                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8183                    if let Some(selection) = current_ranges.first() {
 8184                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8185                    }
 8186                }
 8187
 8188                // If snippet state is not at the last tabstop, push it back on the stack
 8189                if snippet.active_index + 1 < snippet.ranges.len() {
 8190                    self.snippet_stack.push(snippet);
 8191                }
 8192                return true;
 8193            }
 8194        }
 8195
 8196        false
 8197    }
 8198
 8199    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8200        self.transact(window, cx, |this, window, cx| {
 8201            this.select_all(&SelectAll, window, cx);
 8202            this.insert("", window, cx);
 8203        });
 8204    }
 8205
 8206    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8207        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8208        self.transact(window, cx, |this, window, cx| {
 8209            this.select_autoclose_pair(window, cx);
 8210            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8211            if !this.linked_edit_ranges.is_empty() {
 8212                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8213                let snapshot = this.buffer.read(cx).snapshot(cx);
 8214
 8215                for selection in selections.iter() {
 8216                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8217                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8218                    if selection_start.buffer_id != selection_end.buffer_id {
 8219                        continue;
 8220                    }
 8221                    if let Some(ranges) =
 8222                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8223                    {
 8224                        for (buffer, entries) in ranges {
 8225                            linked_ranges.entry(buffer).or_default().extend(entries);
 8226                        }
 8227                    }
 8228                }
 8229            }
 8230
 8231            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8232            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8233            for selection in &mut selections {
 8234                if selection.is_empty() {
 8235                    let old_head = selection.head();
 8236                    let mut new_head =
 8237                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8238                            .to_point(&display_map);
 8239                    if let Some((buffer, line_buffer_range)) = display_map
 8240                        .buffer_snapshot
 8241                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8242                    {
 8243                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8244                        let indent_len = match indent_size.kind {
 8245                            IndentKind::Space => {
 8246                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8247                            }
 8248                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8249                        };
 8250                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8251                            let indent_len = indent_len.get();
 8252                            new_head = cmp::min(
 8253                                new_head,
 8254                                MultiBufferPoint::new(
 8255                                    old_head.row,
 8256                                    ((old_head.column - 1) / indent_len) * indent_len,
 8257                                ),
 8258                            );
 8259                        }
 8260                    }
 8261
 8262                    selection.set_head(new_head, SelectionGoal::None);
 8263                }
 8264            }
 8265
 8266            this.signature_help_state.set_backspace_pressed(true);
 8267            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8268                s.select(selections)
 8269            });
 8270            this.insert("", window, cx);
 8271            let empty_str: Arc<str> = Arc::from("");
 8272            for (buffer, edits) in linked_ranges {
 8273                let snapshot = buffer.read(cx).snapshot();
 8274                use text::ToPoint as TP;
 8275
 8276                let edits = edits
 8277                    .into_iter()
 8278                    .map(|range| {
 8279                        let end_point = TP::to_point(&range.end, &snapshot);
 8280                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8281
 8282                        if end_point == start_point {
 8283                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8284                                .saturating_sub(1);
 8285                            start_point =
 8286                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8287                        };
 8288
 8289                        (start_point..end_point, empty_str.clone())
 8290                    })
 8291                    .sorted_by_key(|(range, _)| range.start)
 8292                    .collect::<Vec<_>>();
 8293                buffer.update(cx, |this, cx| {
 8294                    this.edit(edits, None, cx);
 8295                })
 8296            }
 8297            this.refresh_inline_completion(true, false, window, cx);
 8298            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8299        });
 8300    }
 8301
 8302    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8303        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8304        self.transact(window, cx, |this, window, cx| {
 8305            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8306                s.move_with(|map, selection| {
 8307                    if selection.is_empty() {
 8308                        let cursor = movement::right(map, selection.head());
 8309                        selection.end = cursor;
 8310                        selection.reversed = true;
 8311                        selection.goal = SelectionGoal::None;
 8312                    }
 8313                })
 8314            });
 8315            this.insert("", window, cx);
 8316            this.refresh_inline_completion(true, false, window, cx);
 8317        });
 8318    }
 8319
 8320    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8321        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8322        if self.move_to_prev_snippet_tabstop(window, cx) {
 8323            return;
 8324        }
 8325        self.outdent(&Outdent, window, cx);
 8326    }
 8327
 8328    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8329        if self.move_to_next_snippet_tabstop(window, cx) {
 8330            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8331            return;
 8332        }
 8333        if self.read_only(cx) {
 8334            return;
 8335        }
 8336        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8337        let mut selections = self.selections.all_adjusted(cx);
 8338        let buffer = self.buffer.read(cx);
 8339        let snapshot = buffer.snapshot(cx);
 8340        let rows_iter = selections.iter().map(|s| s.head().row);
 8341        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8342
 8343        let mut edits = Vec::new();
 8344        let mut prev_edited_row = 0;
 8345        let mut row_delta = 0;
 8346        for selection in &mut selections {
 8347            if selection.start.row != prev_edited_row {
 8348                row_delta = 0;
 8349            }
 8350            prev_edited_row = selection.end.row;
 8351
 8352            // If the selection is non-empty, then increase the indentation of the selected lines.
 8353            if !selection.is_empty() {
 8354                row_delta =
 8355                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8356                continue;
 8357            }
 8358
 8359            // If the selection is empty and the cursor is in the leading whitespace before the
 8360            // suggested indentation, then auto-indent the line.
 8361            let cursor = selection.head();
 8362            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8363            if let Some(suggested_indent) =
 8364                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8365            {
 8366                if cursor.column < suggested_indent.len
 8367                    && cursor.column <= current_indent.len
 8368                    && current_indent.len <= suggested_indent.len
 8369                {
 8370                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8371                    selection.end = selection.start;
 8372                    if row_delta == 0 {
 8373                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8374                            cursor.row,
 8375                            current_indent,
 8376                            suggested_indent,
 8377                        ));
 8378                        row_delta = suggested_indent.len - current_indent.len;
 8379                    }
 8380                    continue;
 8381                }
 8382            }
 8383
 8384            // Otherwise, insert a hard or soft tab.
 8385            let settings = buffer.language_settings_at(cursor, cx);
 8386            let tab_size = if settings.hard_tabs {
 8387                IndentSize::tab()
 8388            } else {
 8389                let tab_size = settings.tab_size.get();
 8390                let indent_remainder = snapshot
 8391                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8392                    .flat_map(str::chars)
 8393                    .fold(row_delta % tab_size, |counter: u32, c| {
 8394                        if c == '\t' {
 8395                            0
 8396                        } else {
 8397                            (counter + 1) % tab_size
 8398                        }
 8399                    });
 8400
 8401                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8402                IndentSize::spaces(chars_to_next_tab_stop)
 8403            };
 8404            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8405            selection.end = selection.start;
 8406            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8407            row_delta += tab_size.len;
 8408        }
 8409
 8410        self.transact(window, cx, |this, window, cx| {
 8411            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8412            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8413                s.select(selections)
 8414            });
 8415            this.refresh_inline_completion(true, false, window, cx);
 8416        });
 8417    }
 8418
 8419    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8420        if self.read_only(cx) {
 8421            return;
 8422        }
 8423        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8424        let mut selections = self.selections.all::<Point>(cx);
 8425        let mut prev_edited_row = 0;
 8426        let mut row_delta = 0;
 8427        let mut edits = Vec::new();
 8428        let buffer = self.buffer.read(cx);
 8429        let snapshot = buffer.snapshot(cx);
 8430        for selection in &mut selections {
 8431            if selection.start.row != prev_edited_row {
 8432                row_delta = 0;
 8433            }
 8434            prev_edited_row = selection.end.row;
 8435
 8436            row_delta =
 8437                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8438        }
 8439
 8440        self.transact(window, cx, |this, window, cx| {
 8441            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8442            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8443                s.select(selections)
 8444            });
 8445        });
 8446    }
 8447
 8448    fn indent_selection(
 8449        buffer: &MultiBuffer,
 8450        snapshot: &MultiBufferSnapshot,
 8451        selection: &mut Selection<Point>,
 8452        edits: &mut Vec<(Range<Point>, String)>,
 8453        delta_for_start_row: u32,
 8454        cx: &App,
 8455    ) -> u32 {
 8456        let settings = buffer.language_settings_at(selection.start, cx);
 8457        let tab_size = settings.tab_size.get();
 8458        let indent_kind = if settings.hard_tabs {
 8459            IndentKind::Tab
 8460        } else {
 8461            IndentKind::Space
 8462        };
 8463        let mut start_row = selection.start.row;
 8464        let mut end_row = selection.end.row + 1;
 8465
 8466        // If a selection ends at the beginning of a line, don't indent
 8467        // that last line.
 8468        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8469            end_row -= 1;
 8470        }
 8471
 8472        // Avoid re-indenting a row that has already been indented by a
 8473        // previous selection, but still update this selection's column
 8474        // to reflect that indentation.
 8475        if delta_for_start_row > 0 {
 8476            start_row += 1;
 8477            selection.start.column += delta_for_start_row;
 8478            if selection.end.row == selection.start.row {
 8479                selection.end.column += delta_for_start_row;
 8480            }
 8481        }
 8482
 8483        let mut delta_for_end_row = 0;
 8484        let has_multiple_rows = start_row + 1 != end_row;
 8485        for row in start_row..end_row {
 8486            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8487            let indent_delta = match (current_indent.kind, indent_kind) {
 8488                (IndentKind::Space, IndentKind::Space) => {
 8489                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8490                    IndentSize::spaces(columns_to_next_tab_stop)
 8491                }
 8492                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8493                (_, IndentKind::Tab) => IndentSize::tab(),
 8494            };
 8495
 8496            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8497                0
 8498            } else {
 8499                selection.start.column
 8500            };
 8501            let row_start = Point::new(row, start);
 8502            edits.push((
 8503                row_start..row_start,
 8504                indent_delta.chars().collect::<String>(),
 8505            ));
 8506
 8507            // Update this selection's endpoints to reflect the indentation.
 8508            if row == selection.start.row {
 8509                selection.start.column += indent_delta.len;
 8510            }
 8511            if row == selection.end.row {
 8512                selection.end.column += indent_delta.len;
 8513                delta_for_end_row = indent_delta.len;
 8514            }
 8515        }
 8516
 8517        if selection.start.row == selection.end.row {
 8518            delta_for_start_row + delta_for_end_row
 8519        } else {
 8520            delta_for_end_row
 8521        }
 8522    }
 8523
 8524    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8525        if self.read_only(cx) {
 8526            return;
 8527        }
 8528        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8529        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8530        let selections = self.selections.all::<Point>(cx);
 8531        let mut deletion_ranges = Vec::new();
 8532        let mut last_outdent = None;
 8533        {
 8534            let buffer = self.buffer.read(cx);
 8535            let snapshot = buffer.snapshot(cx);
 8536            for selection in &selections {
 8537                let settings = buffer.language_settings_at(selection.start, cx);
 8538                let tab_size = settings.tab_size.get();
 8539                let mut rows = selection.spanned_rows(false, &display_map);
 8540
 8541                // Avoid re-outdenting a row that has already been outdented by a
 8542                // previous selection.
 8543                if let Some(last_row) = last_outdent {
 8544                    if last_row == rows.start {
 8545                        rows.start = rows.start.next_row();
 8546                    }
 8547                }
 8548                let has_multiple_rows = rows.len() > 1;
 8549                for row in rows.iter_rows() {
 8550                    let indent_size = snapshot.indent_size_for_line(row);
 8551                    if indent_size.len > 0 {
 8552                        let deletion_len = match indent_size.kind {
 8553                            IndentKind::Space => {
 8554                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8555                                if columns_to_prev_tab_stop == 0 {
 8556                                    tab_size
 8557                                } else {
 8558                                    columns_to_prev_tab_stop
 8559                                }
 8560                            }
 8561                            IndentKind::Tab => 1,
 8562                        };
 8563                        let start = if has_multiple_rows
 8564                            || deletion_len > selection.start.column
 8565                            || indent_size.len < selection.start.column
 8566                        {
 8567                            0
 8568                        } else {
 8569                            selection.start.column - deletion_len
 8570                        };
 8571                        deletion_ranges.push(
 8572                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8573                        );
 8574                        last_outdent = Some(row);
 8575                    }
 8576                }
 8577            }
 8578        }
 8579
 8580        self.transact(window, cx, |this, window, cx| {
 8581            this.buffer.update(cx, |buffer, cx| {
 8582                let empty_str: Arc<str> = Arc::default();
 8583                buffer.edit(
 8584                    deletion_ranges
 8585                        .into_iter()
 8586                        .map(|range| (range, empty_str.clone())),
 8587                    None,
 8588                    cx,
 8589                );
 8590            });
 8591            let selections = this.selections.all::<usize>(cx);
 8592            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8593                s.select(selections)
 8594            });
 8595        });
 8596    }
 8597
 8598    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8599        if self.read_only(cx) {
 8600            return;
 8601        }
 8602        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8603        let selections = self
 8604            .selections
 8605            .all::<usize>(cx)
 8606            .into_iter()
 8607            .map(|s| s.range());
 8608
 8609        self.transact(window, cx, |this, window, cx| {
 8610            this.buffer.update(cx, |buffer, cx| {
 8611                buffer.autoindent_ranges(selections, cx);
 8612            });
 8613            let selections = this.selections.all::<usize>(cx);
 8614            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8615                s.select(selections)
 8616            });
 8617        });
 8618    }
 8619
 8620    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8621        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8622        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8623        let selections = self.selections.all::<Point>(cx);
 8624
 8625        let mut new_cursors = Vec::new();
 8626        let mut edit_ranges = Vec::new();
 8627        let mut selections = selections.iter().peekable();
 8628        while let Some(selection) = selections.next() {
 8629            let mut rows = selection.spanned_rows(false, &display_map);
 8630            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8631
 8632            // Accumulate contiguous regions of rows that we want to delete.
 8633            while let Some(next_selection) = selections.peek() {
 8634                let next_rows = next_selection.spanned_rows(false, &display_map);
 8635                if next_rows.start <= rows.end {
 8636                    rows.end = next_rows.end;
 8637                    selections.next().unwrap();
 8638                } else {
 8639                    break;
 8640                }
 8641            }
 8642
 8643            let buffer = &display_map.buffer_snapshot;
 8644            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8645            let edit_end;
 8646            let cursor_buffer_row;
 8647            if buffer.max_point().row >= rows.end.0 {
 8648                // If there's a line after the range, delete the \n from the end of the row range
 8649                // and position the cursor on the next line.
 8650                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8651                cursor_buffer_row = rows.end;
 8652            } else {
 8653                // If there isn't a line after the range, delete the \n from the line before the
 8654                // start of the row range and position the cursor there.
 8655                edit_start = edit_start.saturating_sub(1);
 8656                edit_end = buffer.len();
 8657                cursor_buffer_row = rows.start.previous_row();
 8658            }
 8659
 8660            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8661            *cursor.column_mut() =
 8662                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8663
 8664            new_cursors.push((
 8665                selection.id,
 8666                buffer.anchor_after(cursor.to_point(&display_map)),
 8667            ));
 8668            edit_ranges.push(edit_start..edit_end);
 8669        }
 8670
 8671        self.transact(window, cx, |this, window, cx| {
 8672            let buffer = this.buffer.update(cx, |buffer, cx| {
 8673                let empty_str: Arc<str> = Arc::default();
 8674                buffer.edit(
 8675                    edit_ranges
 8676                        .into_iter()
 8677                        .map(|range| (range, empty_str.clone())),
 8678                    None,
 8679                    cx,
 8680                );
 8681                buffer.snapshot(cx)
 8682            });
 8683            let new_selections = new_cursors
 8684                .into_iter()
 8685                .map(|(id, cursor)| {
 8686                    let cursor = cursor.to_point(&buffer);
 8687                    Selection {
 8688                        id,
 8689                        start: cursor,
 8690                        end: cursor,
 8691                        reversed: false,
 8692                        goal: SelectionGoal::None,
 8693                    }
 8694                })
 8695                .collect();
 8696
 8697            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8698                s.select(new_selections);
 8699            });
 8700        });
 8701    }
 8702
 8703    pub fn join_lines_impl(
 8704        &mut self,
 8705        insert_whitespace: bool,
 8706        window: &mut Window,
 8707        cx: &mut Context<Self>,
 8708    ) {
 8709        if self.read_only(cx) {
 8710            return;
 8711        }
 8712        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8713        for selection in self.selections.all::<Point>(cx) {
 8714            let start = MultiBufferRow(selection.start.row);
 8715            // Treat single line selections as if they include the next line. Otherwise this action
 8716            // would do nothing for single line selections individual cursors.
 8717            let end = if selection.start.row == selection.end.row {
 8718                MultiBufferRow(selection.start.row + 1)
 8719            } else {
 8720                MultiBufferRow(selection.end.row)
 8721            };
 8722
 8723            if let Some(last_row_range) = row_ranges.last_mut() {
 8724                if start <= last_row_range.end {
 8725                    last_row_range.end = end;
 8726                    continue;
 8727                }
 8728            }
 8729            row_ranges.push(start..end);
 8730        }
 8731
 8732        let snapshot = self.buffer.read(cx).snapshot(cx);
 8733        let mut cursor_positions = Vec::new();
 8734        for row_range in &row_ranges {
 8735            let anchor = snapshot.anchor_before(Point::new(
 8736                row_range.end.previous_row().0,
 8737                snapshot.line_len(row_range.end.previous_row()),
 8738            ));
 8739            cursor_positions.push(anchor..anchor);
 8740        }
 8741
 8742        self.transact(window, cx, |this, window, cx| {
 8743            for row_range in row_ranges.into_iter().rev() {
 8744                for row in row_range.iter_rows().rev() {
 8745                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8746                    let next_line_row = row.next_row();
 8747                    let indent = snapshot.indent_size_for_line(next_line_row);
 8748                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8749
 8750                    let replace =
 8751                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8752                            " "
 8753                        } else {
 8754                            ""
 8755                        };
 8756
 8757                    this.buffer.update(cx, |buffer, cx| {
 8758                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8759                    });
 8760                }
 8761            }
 8762
 8763            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8764                s.select_anchor_ranges(cursor_positions)
 8765            });
 8766        });
 8767    }
 8768
 8769    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8770        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8771        self.join_lines_impl(true, window, cx);
 8772    }
 8773
 8774    pub fn sort_lines_case_sensitive(
 8775        &mut self,
 8776        _: &SortLinesCaseSensitive,
 8777        window: &mut Window,
 8778        cx: &mut Context<Self>,
 8779    ) {
 8780        self.manipulate_lines(window, cx, |lines| lines.sort())
 8781    }
 8782
 8783    pub fn sort_lines_case_insensitive(
 8784        &mut self,
 8785        _: &SortLinesCaseInsensitive,
 8786        window: &mut Window,
 8787        cx: &mut Context<Self>,
 8788    ) {
 8789        self.manipulate_lines(window, cx, |lines| {
 8790            lines.sort_by_key(|line| line.to_lowercase())
 8791        })
 8792    }
 8793
 8794    pub fn unique_lines_case_insensitive(
 8795        &mut self,
 8796        _: &UniqueLinesCaseInsensitive,
 8797        window: &mut Window,
 8798        cx: &mut Context<Self>,
 8799    ) {
 8800        self.manipulate_lines(window, cx, |lines| {
 8801            let mut seen = HashSet::default();
 8802            lines.retain(|line| seen.insert(line.to_lowercase()));
 8803        })
 8804    }
 8805
 8806    pub fn unique_lines_case_sensitive(
 8807        &mut self,
 8808        _: &UniqueLinesCaseSensitive,
 8809        window: &mut Window,
 8810        cx: &mut Context<Self>,
 8811    ) {
 8812        self.manipulate_lines(window, cx, |lines| {
 8813            let mut seen = HashSet::default();
 8814            lines.retain(|line| seen.insert(*line));
 8815        })
 8816    }
 8817
 8818    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8819        let Some(project) = self.project.clone() else {
 8820            return;
 8821        };
 8822        self.reload(project, window, cx)
 8823            .detach_and_notify_err(window, cx);
 8824    }
 8825
 8826    pub fn restore_file(
 8827        &mut self,
 8828        _: &::git::RestoreFile,
 8829        window: &mut Window,
 8830        cx: &mut Context<Self>,
 8831    ) {
 8832        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8833        let mut buffer_ids = HashSet::default();
 8834        let snapshot = self.buffer().read(cx).snapshot(cx);
 8835        for selection in self.selections.all::<usize>(cx) {
 8836            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8837        }
 8838
 8839        let buffer = self.buffer().read(cx);
 8840        let ranges = buffer_ids
 8841            .into_iter()
 8842            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8843            .collect::<Vec<_>>();
 8844
 8845        self.restore_hunks_in_ranges(ranges, window, cx);
 8846    }
 8847
 8848    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8849        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8850        let selections = self
 8851            .selections
 8852            .all(cx)
 8853            .into_iter()
 8854            .map(|s| s.range())
 8855            .collect();
 8856        self.restore_hunks_in_ranges(selections, window, cx);
 8857    }
 8858
 8859    pub fn restore_hunks_in_ranges(
 8860        &mut self,
 8861        ranges: Vec<Range<Point>>,
 8862        window: &mut Window,
 8863        cx: &mut Context<Editor>,
 8864    ) {
 8865        let mut revert_changes = HashMap::default();
 8866        let chunk_by = self
 8867            .snapshot(window, cx)
 8868            .hunks_for_ranges(ranges)
 8869            .into_iter()
 8870            .chunk_by(|hunk| hunk.buffer_id);
 8871        for (buffer_id, hunks) in &chunk_by {
 8872            let hunks = hunks.collect::<Vec<_>>();
 8873            for hunk in &hunks {
 8874                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8875            }
 8876            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8877        }
 8878        drop(chunk_by);
 8879        if !revert_changes.is_empty() {
 8880            self.transact(window, cx, |editor, window, cx| {
 8881                editor.restore(revert_changes, window, cx);
 8882            });
 8883        }
 8884    }
 8885
 8886    pub fn open_active_item_in_terminal(
 8887        &mut self,
 8888        _: &OpenInTerminal,
 8889        window: &mut Window,
 8890        cx: &mut Context<Self>,
 8891    ) {
 8892        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8893            let project_path = buffer.read(cx).project_path(cx)?;
 8894            let project = self.project.as_ref()?.read(cx);
 8895            let entry = project.entry_for_path(&project_path, cx)?;
 8896            let parent = match &entry.canonical_path {
 8897                Some(canonical_path) => canonical_path.to_path_buf(),
 8898                None => project.absolute_path(&project_path, cx)?,
 8899            }
 8900            .parent()?
 8901            .to_path_buf();
 8902            Some(parent)
 8903        }) {
 8904            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8905        }
 8906    }
 8907
 8908    fn set_breakpoint_context_menu(
 8909        &mut self,
 8910        display_row: DisplayRow,
 8911        position: Option<Anchor>,
 8912        clicked_point: gpui::Point<Pixels>,
 8913        window: &mut Window,
 8914        cx: &mut Context<Self>,
 8915    ) {
 8916        if !cx.has_flag::<Debugger>() {
 8917            return;
 8918        }
 8919        let source = self
 8920            .buffer
 8921            .read(cx)
 8922            .snapshot(cx)
 8923            .anchor_before(Point::new(display_row.0, 0u32));
 8924
 8925        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8926
 8927        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8928            self,
 8929            source,
 8930            clicked_point,
 8931            None,
 8932            context_menu,
 8933            window,
 8934            cx,
 8935        );
 8936    }
 8937
 8938    fn add_edit_breakpoint_block(
 8939        &mut self,
 8940        anchor: Anchor,
 8941        breakpoint: &Breakpoint,
 8942        edit_action: BreakpointPromptEditAction,
 8943        window: &mut Window,
 8944        cx: &mut Context<Self>,
 8945    ) {
 8946        let weak_editor = cx.weak_entity();
 8947        let bp_prompt = cx.new(|cx| {
 8948            BreakpointPromptEditor::new(
 8949                weak_editor,
 8950                anchor,
 8951                breakpoint.clone(),
 8952                edit_action,
 8953                window,
 8954                cx,
 8955            )
 8956        });
 8957
 8958        let height = bp_prompt.update(cx, |this, cx| {
 8959            this.prompt
 8960                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8961        });
 8962        let cloned_prompt = bp_prompt.clone();
 8963        let blocks = vec![BlockProperties {
 8964            style: BlockStyle::Sticky,
 8965            placement: BlockPlacement::Above(anchor),
 8966            height: Some(height),
 8967            render: Arc::new(move |cx| {
 8968                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8969                cloned_prompt.clone().into_any_element()
 8970            }),
 8971            priority: 0,
 8972        }];
 8973
 8974        let focus_handle = bp_prompt.focus_handle(cx);
 8975        window.focus(&focus_handle);
 8976
 8977        let block_ids = self.insert_blocks(blocks, None, cx);
 8978        bp_prompt.update(cx, |prompt, _| {
 8979            prompt.add_block_ids(block_ids);
 8980        });
 8981    }
 8982
 8983    pub(crate) fn breakpoint_at_row(
 8984        &self,
 8985        row: u32,
 8986        window: &mut Window,
 8987        cx: &mut Context<Self>,
 8988    ) -> Option<(Anchor, Breakpoint)> {
 8989        let snapshot = self.snapshot(window, cx);
 8990        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8991
 8992        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 8993    }
 8994
 8995    pub(crate) fn breakpoint_at_anchor(
 8996        &self,
 8997        breakpoint_position: Anchor,
 8998        snapshot: &EditorSnapshot,
 8999        cx: &mut Context<Self>,
 9000    ) -> Option<(Anchor, Breakpoint)> {
 9001        let project = self.project.clone()?;
 9002
 9003        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9004            snapshot
 9005                .buffer_snapshot
 9006                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9007        })?;
 9008
 9009        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9010        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9011        let buffer_snapshot = buffer.read(cx).snapshot();
 9012
 9013        let row = buffer_snapshot
 9014            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9015            .row;
 9016
 9017        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9018        let anchor_end = snapshot
 9019            .buffer_snapshot
 9020            .anchor_after(Point::new(row, line_len));
 9021
 9022        let bp = self
 9023            .breakpoint_store
 9024            .as_ref()?
 9025            .read_with(cx, |breakpoint_store, cx| {
 9026                breakpoint_store
 9027                    .breakpoints(
 9028                        &buffer,
 9029                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9030                        &buffer_snapshot,
 9031                        cx,
 9032                    )
 9033                    .next()
 9034                    .and_then(|(anchor, bp)| {
 9035                        let breakpoint_row = buffer_snapshot
 9036                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9037                            .row;
 9038
 9039                        if breakpoint_row == row {
 9040                            snapshot
 9041                                .buffer_snapshot
 9042                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9043                                .map(|anchor| (anchor, bp.clone()))
 9044                        } else {
 9045                            None
 9046                        }
 9047                    })
 9048            });
 9049        bp
 9050    }
 9051
 9052    pub fn edit_log_breakpoint(
 9053        &mut self,
 9054        _: &EditLogBreakpoint,
 9055        window: &mut Window,
 9056        cx: &mut Context<Self>,
 9057    ) {
 9058        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9059            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9060                message: None,
 9061                state: BreakpointState::Enabled,
 9062                condition: None,
 9063                hit_condition: None,
 9064            });
 9065
 9066            self.add_edit_breakpoint_block(
 9067                anchor,
 9068                &breakpoint,
 9069                BreakpointPromptEditAction::Log,
 9070                window,
 9071                cx,
 9072            );
 9073        }
 9074    }
 9075
 9076    fn breakpoints_at_cursors(
 9077        &self,
 9078        window: &mut Window,
 9079        cx: &mut Context<Self>,
 9080    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9081        let snapshot = self.snapshot(window, cx);
 9082        let cursors = self
 9083            .selections
 9084            .disjoint_anchors()
 9085            .into_iter()
 9086            .map(|selection| {
 9087                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9088
 9089                let breakpoint_position = self
 9090                    .breakpoint_at_row(cursor_position.row, window, cx)
 9091                    .map(|bp| bp.0)
 9092                    .unwrap_or_else(|| {
 9093                        snapshot
 9094                            .display_snapshot
 9095                            .buffer_snapshot
 9096                            .anchor_after(Point::new(cursor_position.row, 0))
 9097                    });
 9098
 9099                let breakpoint = self
 9100                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9101                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9102
 9103                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9104            })
 9105            // 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.
 9106            .collect::<HashMap<Anchor, _>>();
 9107
 9108        cursors.into_iter().collect()
 9109    }
 9110
 9111    pub fn enable_breakpoint(
 9112        &mut self,
 9113        _: &crate::actions::EnableBreakpoint,
 9114        window: &mut Window,
 9115        cx: &mut Context<Self>,
 9116    ) {
 9117        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9118            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9119                continue;
 9120            };
 9121            self.edit_breakpoint_at_anchor(
 9122                anchor,
 9123                breakpoint,
 9124                BreakpointEditAction::InvertState,
 9125                cx,
 9126            );
 9127        }
 9128    }
 9129
 9130    pub fn disable_breakpoint(
 9131        &mut self,
 9132        _: &crate::actions::DisableBreakpoint,
 9133        window: &mut Window,
 9134        cx: &mut Context<Self>,
 9135    ) {
 9136        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9137            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9138                continue;
 9139            };
 9140            self.edit_breakpoint_at_anchor(
 9141                anchor,
 9142                breakpoint,
 9143                BreakpointEditAction::InvertState,
 9144                cx,
 9145            );
 9146        }
 9147    }
 9148
 9149    pub fn toggle_breakpoint(
 9150        &mut self,
 9151        _: &crate::actions::ToggleBreakpoint,
 9152        window: &mut Window,
 9153        cx: &mut Context<Self>,
 9154    ) {
 9155        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9156            if let Some(breakpoint) = breakpoint {
 9157                self.edit_breakpoint_at_anchor(
 9158                    anchor,
 9159                    breakpoint,
 9160                    BreakpointEditAction::Toggle,
 9161                    cx,
 9162                );
 9163            } else {
 9164                self.edit_breakpoint_at_anchor(
 9165                    anchor,
 9166                    Breakpoint::new_standard(),
 9167                    BreakpointEditAction::Toggle,
 9168                    cx,
 9169                );
 9170            }
 9171        }
 9172    }
 9173
 9174    pub fn edit_breakpoint_at_anchor(
 9175        &mut self,
 9176        breakpoint_position: Anchor,
 9177        breakpoint: Breakpoint,
 9178        edit_action: BreakpointEditAction,
 9179        cx: &mut Context<Self>,
 9180    ) {
 9181        let Some(breakpoint_store) = &self.breakpoint_store else {
 9182            return;
 9183        };
 9184
 9185        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9186            if breakpoint_position == Anchor::min() {
 9187                self.buffer()
 9188                    .read(cx)
 9189                    .excerpt_buffer_ids()
 9190                    .into_iter()
 9191                    .next()
 9192            } else {
 9193                None
 9194            }
 9195        }) else {
 9196            return;
 9197        };
 9198
 9199        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9200            return;
 9201        };
 9202
 9203        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9204            breakpoint_store.toggle_breakpoint(
 9205                buffer,
 9206                (breakpoint_position.text_anchor, breakpoint),
 9207                edit_action,
 9208                cx,
 9209            );
 9210        });
 9211
 9212        cx.notify();
 9213    }
 9214
 9215    #[cfg(any(test, feature = "test-support"))]
 9216    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9217        self.breakpoint_store.clone()
 9218    }
 9219
 9220    pub fn prepare_restore_change(
 9221        &self,
 9222        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9223        hunk: &MultiBufferDiffHunk,
 9224        cx: &mut App,
 9225    ) -> Option<()> {
 9226        if hunk.is_created_file() {
 9227            return None;
 9228        }
 9229        let buffer = self.buffer.read(cx);
 9230        let diff = buffer.diff_for(hunk.buffer_id)?;
 9231        let buffer = buffer.buffer(hunk.buffer_id)?;
 9232        let buffer = buffer.read(cx);
 9233        let original_text = diff
 9234            .read(cx)
 9235            .base_text()
 9236            .as_rope()
 9237            .slice(hunk.diff_base_byte_range.clone());
 9238        let buffer_snapshot = buffer.snapshot();
 9239        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9240        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9241            probe
 9242                .0
 9243                .start
 9244                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9245                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9246        }) {
 9247            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9248            Some(())
 9249        } else {
 9250            None
 9251        }
 9252    }
 9253
 9254    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9255        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9256    }
 9257
 9258    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9259        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9260    }
 9261
 9262    fn manipulate_lines<Fn>(
 9263        &mut self,
 9264        window: &mut Window,
 9265        cx: &mut Context<Self>,
 9266        mut callback: Fn,
 9267    ) where
 9268        Fn: FnMut(&mut Vec<&str>),
 9269    {
 9270        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9271
 9272        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9273        let buffer = self.buffer.read(cx).snapshot(cx);
 9274
 9275        let mut edits = Vec::new();
 9276
 9277        let selections = self.selections.all::<Point>(cx);
 9278        let mut selections = selections.iter().peekable();
 9279        let mut contiguous_row_selections = Vec::new();
 9280        let mut new_selections = Vec::new();
 9281        let mut added_lines = 0;
 9282        let mut removed_lines = 0;
 9283
 9284        while let Some(selection) = selections.next() {
 9285            let (start_row, end_row) = consume_contiguous_rows(
 9286                &mut contiguous_row_selections,
 9287                selection,
 9288                &display_map,
 9289                &mut selections,
 9290            );
 9291
 9292            let start_point = Point::new(start_row.0, 0);
 9293            let end_point = Point::new(
 9294                end_row.previous_row().0,
 9295                buffer.line_len(end_row.previous_row()),
 9296            );
 9297            let text = buffer
 9298                .text_for_range(start_point..end_point)
 9299                .collect::<String>();
 9300
 9301            let mut lines = text.split('\n').collect_vec();
 9302
 9303            let lines_before = lines.len();
 9304            callback(&mut lines);
 9305            let lines_after = lines.len();
 9306
 9307            edits.push((start_point..end_point, lines.join("\n")));
 9308
 9309            // Selections must change based on added and removed line count
 9310            let start_row =
 9311                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9312            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9313            new_selections.push(Selection {
 9314                id: selection.id,
 9315                start: start_row,
 9316                end: end_row,
 9317                goal: SelectionGoal::None,
 9318                reversed: selection.reversed,
 9319            });
 9320
 9321            if lines_after > lines_before {
 9322                added_lines += lines_after - lines_before;
 9323            } else if lines_before > lines_after {
 9324                removed_lines += lines_before - lines_after;
 9325            }
 9326        }
 9327
 9328        self.transact(window, cx, |this, window, cx| {
 9329            let buffer = this.buffer.update(cx, |buffer, cx| {
 9330                buffer.edit(edits, None, cx);
 9331                buffer.snapshot(cx)
 9332            });
 9333
 9334            // Recalculate offsets on newly edited buffer
 9335            let new_selections = new_selections
 9336                .iter()
 9337                .map(|s| {
 9338                    let start_point = Point::new(s.start.0, 0);
 9339                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9340                    Selection {
 9341                        id: s.id,
 9342                        start: buffer.point_to_offset(start_point),
 9343                        end: buffer.point_to_offset(end_point),
 9344                        goal: s.goal,
 9345                        reversed: s.reversed,
 9346                    }
 9347                })
 9348                .collect();
 9349
 9350            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9351                s.select(new_selections);
 9352            });
 9353
 9354            this.request_autoscroll(Autoscroll::fit(), cx);
 9355        });
 9356    }
 9357
 9358    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9359        self.manipulate_text(window, cx, |text| {
 9360            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9361            if has_upper_case_characters {
 9362                text.to_lowercase()
 9363            } else {
 9364                text.to_uppercase()
 9365            }
 9366        })
 9367    }
 9368
 9369    pub fn convert_to_upper_case(
 9370        &mut self,
 9371        _: &ConvertToUpperCase,
 9372        window: &mut Window,
 9373        cx: &mut Context<Self>,
 9374    ) {
 9375        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9376    }
 9377
 9378    pub fn convert_to_lower_case(
 9379        &mut self,
 9380        _: &ConvertToLowerCase,
 9381        window: &mut Window,
 9382        cx: &mut Context<Self>,
 9383    ) {
 9384        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9385    }
 9386
 9387    pub fn convert_to_title_case(
 9388        &mut self,
 9389        _: &ConvertToTitleCase,
 9390        window: &mut Window,
 9391        cx: &mut Context<Self>,
 9392    ) {
 9393        self.manipulate_text(window, cx, |text| {
 9394            text.split('\n')
 9395                .map(|line| line.to_case(Case::Title))
 9396                .join("\n")
 9397        })
 9398    }
 9399
 9400    pub fn convert_to_snake_case(
 9401        &mut self,
 9402        _: &ConvertToSnakeCase,
 9403        window: &mut Window,
 9404        cx: &mut Context<Self>,
 9405    ) {
 9406        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9407    }
 9408
 9409    pub fn convert_to_kebab_case(
 9410        &mut self,
 9411        _: &ConvertToKebabCase,
 9412        window: &mut Window,
 9413        cx: &mut Context<Self>,
 9414    ) {
 9415        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9416    }
 9417
 9418    pub fn convert_to_upper_camel_case(
 9419        &mut self,
 9420        _: &ConvertToUpperCamelCase,
 9421        window: &mut Window,
 9422        cx: &mut Context<Self>,
 9423    ) {
 9424        self.manipulate_text(window, cx, |text| {
 9425            text.split('\n')
 9426                .map(|line| line.to_case(Case::UpperCamel))
 9427                .join("\n")
 9428        })
 9429    }
 9430
 9431    pub fn convert_to_lower_camel_case(
 9432        &mut self,
 9433        _: &ConvertToLowerCamelCase,
 9434        window: &mut Window,
 9435        cx: &mut Context<Self>,
 9436    ) {
 9437        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9438    }
 9439
 9440    pub fn convert_to_opposite_case(
 9441        &mut self,
 9442        _: &ConvertToOppositeCase,
 9443        window: &mut Window,
 9444        cx: &mut Context<Self>,
 9445    ) {
 9446        self.manipulate_text(window, cx, |text| {
 9447            text.chars()
 9448                .fold(String::with_capacity(text.len()), |mut t, c| {
 9449                    if c.is_uppercase() {
 9450                        t.extend(c.to_lowercase());
 9451                    } else {
 9452                        t.extend(c.to_uppercase());
 9453                    }
 9454                    t
 9455                })
 9456        })
 9457    }
 9458
 9459    pub fn convert_to_rot13(
 9460        &mut self,
 9461        _: &ConvertToRot13,
 9462        window: &mut Window,
 9463        cx: &mut Context<Self>,
 9464    ) {
 9465        self.manipulate_text(window, cx, |text| {
 9466            text.chars()
 9467                .map(|c| match c {
 9468                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9469                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9470                    _ => c,
 9471                })
 9472                .collect()
 9473        })
 9474    }
 9475
 9476    pub fn convert_to_rot47(
 9477        &mut self,
 9478        _: &ConvertToRot47,
 9479        window: &mut Window,
 9480        cx: &mut Context<Self>,
 9481    ) {
 9482        self.manipulate_text(window, cx, |text| {
 9483            text.chars()
 9484                .map(|c| {
 9485                    let code_point = c as u32;
 9486                    if code_point >= 33 && code_point <= 126 {
 9487                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9488                    }
 9489                    c
 9490                })
 9491                .collect()
 9492        })
 9493    }
 9494
 9495    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9496    where
 9497        Fn: FnMut(&str) -> String,
 9498    {
 9499        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9500        let buffer = self.buffer.read(cx).snapshot(cx);
 9501
 9502        let mut new_selections = Vec::new();
 9503        let mut edits = Vec::new();
 9504        let mut selection_adjustment = 0i32;
 9505
 9506        for selection in self.selections.all::<usize>(cx) {
 9507            let selection_is_empty = selection.is_empty();
 9508
 9509            let (start, end) = if selection_is_empty {
 9510                let word_range = movement::surrounding_word(
 9511                    &display_map,
 9512                    selection.start.to_display_point(&display_map),
 9513                );
 9514                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9515                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9516                (start, end)
 9517            } else {
 9518                (selection.start, selection.end)
 9519            };
 9520
 9521            let text = buffer.text_for_range(start..end).collect::<String>();
 9522            let old_length = text.len() as i32;
 9523            let text = callback(&text);
 9524
 9525            new_selections.push(Selection {
 9526                start: (start as i32 - selection_adjustment) as usize,
 9527                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9528                goal: SelectionGoal::None,
 9529                ..selection
 9530            });
 9531
 9532            selection_adjustment += old_length - text.len() as i32;
 9533
 9534            edits.push((start..end, text));
 9535        }
 9536
 9537        self.transact(window, cx, |this, window, cx| {
 9538            this.buffer.update(cx, |buffer, cx| {
 9539                buffer.edit(edits, None, cx);
 9540            });
 9541
 9542            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9543                s.select(new_selections);
 9544            });
 9545
 9546            this.request_autoscroll(Autoscroll::fit(), cx);
 9547        });
 9548    }
 9549
 9550    pub fn duplicate(
 9551        &mut self,
 9552        upwards: bool,
 9553        whole_lines: bool,
 9554        window: &mut Window,
 9555        cx: &mut Context<Self>,
 9556    ) {
 9557        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9558
 9559        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9560        let buffer = &display_map.buffer_snapshot;
 9561        let selections = self.selections.all::<Point>(cx);
 9562
 9563        let mut edits = Vec::new();
 9564        let mut selections_iter = selections.iter().peekable();
 9565        while let Some(selection) = selections_iter.next() {
 9566            let mut rows = selection.spanned_rows(false, &display_map);
 9567            // duplicate line-wise
 9568            if whole_lines || selection.start == selection.end {
 9569                // Avoid duplicating the same lines twice.
 9570                while let Some(next_selection) = selections_iter.peek() {
 9571                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9572                    if next_rows.start < rows.end {
 9573                        rows.end = next_rows.end;
 9574                        selections_iter.next().unwrap();
 9575                    } else {
 9576                        break;
 9577                    }
 9578                }
 9579
 9580                // Copy the text from the selected row region and splice it either at the start
 9581                // or end of the region.
 9582                let start = Point::new(rows.start.0, 0);
 9583                let end = Point::new(
 9584                    rows.end.previous_row().0,
 9585                    buffer.line_len(rows.end.previous_row()),
 9586                );
 9587                let text = buffer
 9588                    .text_for_range(start..end)
 9589                    .chain(Some("\n"))
 9590                    .collect::<String>();
 9591                let insert_location = if upwards {
 9592                    Point::new(rows.end.0, 0)
 9593                } else {
 9594                    start
 9595                };
 9596                edits.push((insert_location..insert_location, text));
 9597            } else {
 9598                // duplicate character-wise
 9599                let start = selection.start;
 9600                let end = selection.end;
 9601                let text = buffer.text_for_range(start..end).collect::<String>();
 9602                edits.push((selection.end..selection.end, text));
 9603            }
 9604        }
 9605
 9606        self.transact(window, cx, |this, _, cx| {
 9607            this.buffer.update(cx, |buffer, cx| {
 9608                buffer.edit(edits, None, cx);
 9609            });
 9610
 9611            this.request_autoscroll(Autoscroll::fit(), cx);
 9612        });
 9613    }
 9614
 9615    pub fn duplicate_line_up(
 9616        &mut self,
 9617        _: &DuplicateLineUp,
 9618        window: &mut Window,
 9619        cx: &mut Context<Self>,
 9620    ) {
 9621        self.duplicate(true, true, window, cx);
 9622    }
 9623
 9624    pub fn duplicate_line_down(
 9625        &mut self,
 9626        _: &DuplicateLineDown,
 9627        window: &mut Window,
 9628        cx: &mut Context<Self>,
 9629    ) {
 9630        self.duplicate(false, true, window, cx);
 9631    }
 9632
 9633    pub fn duplicate_selection(
 9634        &mut self,
 9635        _: &DuplicateSelection,
 9636        window: &mut Window,
 9637        cx: &mut Context<Self>,
 9638    ) {
 9639        self.duplicate(false, false, window, cx);
 9640    }
 9641
 9642    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9643        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9644
 9645        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9646        let buffer = self.buffer.read(cx).snapshot(cx);
 9647
 9648        let mut edits = Vec::new();
 9649        let mut unfold_ranges = Vec::new();
 9650        let mut refold_creases = Vec::new();
 9651
 9652        let selections = self.selections.all::<Point>(cx);
 9653        let mut selections = selections.iter().peekable();
 9654        let mut contiguous_row_selections = Vec::new();
 9655        let mut new_selections = Vec::new();
 9656
 9657        while let Some(selection) = selections.next() {
 9658            // Find all the selections that span a contiguous row range
 9659            let (start_row, end_row) = consume_contiguous_rows(
 9660                &mut contiguous_row_selections,
 9661                selection,
 9662                &display_map,
 9663                &mut selections,
 9664            );
 9665
 9666            // Move the text spanned by the row range to be before the line preceding the row range
 9667            if start_row.0 > 0 {
 9668                let range_to_move = Point::new(
 9669                    start_row.previous_row().0,
 9670                    buffer.line_len(start_row.previous_row()),
 9671                )
 9672                    ..Point::new(
 9673                        end_row.previous_row().0,
 9674                        buffer.line_len(end_row.previous_row()),
 9675                    );
 9676                let insertion_point = display_map
 9677                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9678                    .0;
 9679
 9680                // Don't move lines across excerpts
 9681                if buffer
 9682                    .excerpt_containing(insertion_point..range_to_move.end)
 9683                    .is_some()
 9684                {
 9685                    let text = buffer
 9686                        .text_for_range(range_to_move.clone())
 9687                        .flat_map(|s| s.chars())
 9688                        .skip(1)
 9689                        .chain(['\n'])
 9690                        .collect::<String>();
 9691
 9692                    edits.push((
 9693                        buffer.anchor_after(range_to_move.start)
 9694                            ..buffer.anchor_before(range_to_move.end),
 9695                        String::new(),
 9696                    ));
 9697                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9698                    edits.push((insertion_anchor..insertion_anchor, text));
 9699
 9700                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9701
 9702                    // Move selections up
 9703                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9704                        |mut selection| {
 9705                            selection.start.row -= row_delta;
 9706                            selection.end.row -= row_delta;
 9707                            selection
 9708                        },
 9709                    ));
 9710
 9711                    // Move folds up
 9712                    unfold_ranges.push(range_to_move.clone());
 9713                    for fold in display_map.folds_in_range(
 9714                        buffer.anchor_before(range_to_move.start)
 9715                            ..buffer.anchor_after(range_to_move.end),
 9716                    ) {
 9717                        let mut start = fold.range.start.to_point(&buffer);
 9718                        let mut end = fold.range.end.to_point(&buffer);
 9719                        start.row -= row_delta;
 9720                        end.row -= row_delta;
 9721                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9722                    }
 9723                }
 9724            }
 9725
 9726            // If we didn't move line(s), preserve the existing selections
 9727            new_selections.append(&mut contiguous_row_selections);
 9728        }
 9729
 9730        self.transact(window, cx, |this, window, cx| {
 9731            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9732            this.buffer.update(cx, |buffer, cx| {
 9733                for (range, text) in edits {
 9734                    buffer.edit([(range, text)], None, cx);
 9735                }
 9736            });
 9737            this.fold_creases(refold_creases, true, window, cx);
 9738            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9739                s.select(new_selections);
 9740            })
 9741        });
 9742    }
 9743
 9744    pub fn move_line_down(
 9745        &mut self,
 9746        _: &MoveLineDown,
 9747        window: &mut Window,
 9748        cx: &mut Context<Self>,
 9749    ) {
 9750        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9751
 9752        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9753        let buffer = self.buffer.read(cx).snapshot(cx);
 9754
 9755        let mut edits = Vec::new();
 9756        let mut unfold_ranges = Vec::new();
 9757        let mut refold_creases = Vec::new();
 9758
 9759        let selections = self.selections.all::<Point>(cx);
 9760        let mut selections = selections.iter().peekable();
 9761        let mut contiguous_row_selections = Vec::new();
 9762        let mut new_selections = Vec::new();
 9763
 9764        while let Some(selection) = selections.next() {
 9765            // Find all the selections that span a contiguous row range
 9766            let (start_row, end_row) = consume_contiguous_rows(
 9767                &mut contiguous_row_selections,
 9768                selection,
 9769                &display_map,
 9770                &mut selections,
 9771            );
 9772
 9773            // Move the text spanned by the row range to be after the last line of the row range
 9774            if end_row.0 <= buffer.max_point().row {
 9775                let range_to_move =
 9776                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9777                let insertion_point = display_map
 9778                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9779                    .0;
 9780
 9781                // Don't move lines across excerpt boundaries
 9782                if buffer
 9783                    .excerpt_containing(range_to_move.start..insertion_point)
 9784                    .is_some()
 9785                {
 9786                    let mut text = String::from("\n");
 9787                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9788                    text.pop(); // Drop trailing newline
 9789                    edits.push((
 9790                        buffer.anchor_after(range_to_move.start)
 9791                            ..buffer.anchor_before(range_to_move.end),
 9792                        String::new(),
 9793                    ));
 9794                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9795                    edits.push((insertion_anchor..insertion_anchor, text));
 9796
 9797                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9798
 9799                    // Move selections down
 9800                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9801                        |mut selection| {
 9802                            selection.start.row += row_delta;
 9803                            selection.end.row += row_delta;
 9804                            selection
 9805                        },
 9806                    ));
 9807
 9808                    // Move folds down
 9809                    unfold_ranges.push(range_to_move.clone());
 9810                    for fold in display_map.folds_in_range(
 9811                        buffer.anchor_before(range_to_move.start)
 9812                            ..buffer.anchor_after(range_to_move.end),
 9813                    ) {
 9814                        let mut start = fold.range.start.to_point(&buffer);
 9815                        let mut end = fold.range.end.to_point(&buffer);
 9816                        start.row += row_delta;
 9817                        end.row += row_delta;
 9818                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9819                    }
 9820                }
 9821            }
 9822
 9823            // If we didn't move line(s), preserve the existing selections
 9824            new_selections.append(&mut contiguous_row_selections);
 9825        }
 9826
 9827        self.transact(window, cx, |this, window, cx| {
 9828            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9829            this.buffer.update(cx, |buffer, cx| {
 9830                for (range, text) in edits {
 9831                    buffer.edit([(range, text)], None, cx);
 9832                }
 9833            });
 9834            this.fold_creases(refold_creases, true, window, cx);
 9835            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9836                s.select(new_selections)
 9837            });
 9838        });
 9839    }
 9840
 9841    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9842        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9843        let text_layout_details = &self.text_layout_details(window);
 9844        self.transact(window, cx, |this, window, cx| {
 9845            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9846                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9847                s.move_with(|display_map, selection| {
 9848                    if !selection.is_empty() {
 9849                        return;
 9850                    }
 9851
 9852                    let mut head = selection.head();
 9853                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9854                    if head.column() == display_map.line_len(head.row()) {
 9855                        transpose_offset = display_map
 9856                            .buffer_snapshot
 9857                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9858                    }
 9859
 9860                    if transpose_offset == 0 {
 9861                        return;
 9862                    }
 9863
 9864                    *head.column_mut() += 1;
 9865                    head = display_map.clip_point(head, Bias::Right);
 9866                    let goal = SelectionGoal::HorizontalPosition(
 9867                        display_map
 9868                            .x_for_display_point(head, text_layout_details)
 9869                            .into(),
 9870                    );
 9871                    selection.collapse_to(head, goal);
 9872
 9873                    let transpose_start = display_map
 9874                        .buffer_snapshot
 9875                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9876                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9877                        let transpose_end = display_map
 9878                            .buffer_snapshot
 9879                            .clip_offset(transpose_offset + 1, Bias::Right);
 9880                        if let Some(ch) =
 9881                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9882                        {
 9883                            edits.push((transpose_start..transpose_offset, String::new()));
 9884                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9885                        }
 9886                    }
 9887                });
 9888                edits
 9889            });
 9890            this.buffer
 9891                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9892            let selections = this.selections.all::<usize>(cx);
 9893            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9894                s.select(selections);
 9895            });
 9896        });
 9897    }
 9898
 9899    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9900        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9901        self.rewrap_impl(RewrapOptions::default(), cx)
 9902    }
 9903
 9904    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9905        let buffer = self.buffer.read(cx).snapshot(cx);
 9906        let selections = self.selections.all::<Point>(cx);
 9907        let mut selections = selections.iter().peekable();
 9908
 9909        let mut edits = Vec::new();
 9910        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9911
 9912        while let Some(selection) = selections.next() {
 9913            let mut start_row = selection.start.row;
 9914            let mut end_row = selection.end.row;
 9915
 9916            // Skip selections that overlap with a range that has already been rewrapped.
 9917            let selection_range = start_row..end_row;
 9918            if rewrapped_row_ranges
 9919                .iter()
 9920                .any(|range| range.overlaps(&selection_range))
 9921            {
 9922                continue;
 9923            }
 9924
 9925            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9926
 9927            // Since not all lines in the selection may be at the same indent
 9928            // level, choose the indent size that is the most common between all
 9929            // of the lines.
 9930            //
 9931            // If there is a tie, we use the deepest indent.
 9932            let (indent_size, indent_end) = {
 9933                let mut indent_size_occurrences = HashMap::default();
 9934                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9935
 9936                for row in start_row..=end_row {
 9937                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9938                    rows_by_indent_size.entry(indent).or_default().push(row);
 9939                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9940                }
 9941
 9942                let indent_size = indent_size_occurrences
 9943                    .into_iter()
 9944                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9945                    .map(|(indent, _)| indent)
 9946                    .unwrap_or_default();
 9947                let row = rows_by_indent_size[&indent_size][0];
 9948                let indent_end = Point::new(row, indent_size.len);
 9949
 9950                (indent_size, indent_end)
 9951            };
 9952
 9953            let mut line_prefix = indent_size.chars().collect::<String>();
 9954
 9955            let mut inside_comment = false;
 9956            if let Some(comment_prefix) =
 9957                buffer
 9958                    .language_scope_at(selection.head())
 9959                    .and_then(|language| {
 9960                        language
 9961                            .line_comment_prefixes()
 9962                            .iter()
 9963                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9964                            .cloned()
 9965                    })
 9966            {
 9967                line_prefix.push_str(&comment_prefix);
 9968                inside_comment = true;
 9969            }
 9970
 9971            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9972            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9973                RewrapBehavior::InComments => inside_comment,
 9974                RewrapBehavior::InSelections => !selection.is_empty(),
 9975                RewrapBehavior::Anywhere => true,
 9976            };
 9977
 9978            let should_rewrap = options.override_language_settings
 9979                || allow_rewrap_based_on_language
 9980                || self.hard_wrap.is_some();
 9981            if !should_rewrap {
 9982                continue;
 9983            }
 9984
 9985            if selection.is_empty() {
 9986                'expand_upwards: while start_row > 0 {
 9987                    let prev_row = start_row - 1;
 9988                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9989                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9990                    {
 9991                        start_row = prev_row;
 9992                    } else {
 9993                        break 'expand_upwards;
 9994                    }
 9995                }
 9996
 9997                'expand_downwards: while end_row < buffer.max_point().row {
 9998                    let next_row = end_row + 1;
 9999                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10000                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10001                    {
10002                        end_row = next_row;
10003                    } else {
10004                        break 'expand_downwards;
10005                    }
10006                }
10007            }
10008
10009            let start = Point::new(start_row, 0);
10010            let start_offset = start.to_offset(&buffer);
10011            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10012            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10013            let Some(lines_without_prefixes) = selection_text
10014                .lines()
10015                .map(|line| {
10016                    line.strip_prefix(&line_prefix)
10017                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10018                        .ok_or_else(|| {
10019                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10020                        })
10021                })
10022                .collect::<Result<Vec<_>, _>>()
10023                .log_err()
10024            else {
10025                continue;
10026            };
10027
10028            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10029                buffer
10030                    .language_settings_at(Point::new(start_row, 0), cx)
10031                    .preferred_line_length as usize
10032            });
10033            let wrapped_text = wrap_with_prefix(
10034                line_prefix,
10035                lines_without_prefixes.join("\n"),
10036                wrap_column,
10037                tab_size,
10038                options.preserve_existing_whitespace,
10039            );
10040
10041            // TODO: should always use char-based diff while still supporting cursor behavior that
10042            // matches vim.
10043            let mut diff_options = DiffOptions::default();
10044            if options.override_language_settings {
10045                diff_options.max_word_diff_len = 0;
10046                diff_options.max_word_diff_line_count = 0;
10047            } else {
10048                diff_options.max_word_diff_len = usize::MAX;
10049                diff_options.max_word_diff_line_count = usize::MAX;
10050            }
10051
10052            for (old_range, new_text) in
10053                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10054            {
10055                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10056                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10057                edits.push((edit_start..edit_end, new_text));
10058            }
10059
10060            rewrapped_row_ranges.push(start_row..=end_row);
10061        }
10062
10063        self.buffer
10064            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10065    }
10066
10067    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10068        let mut text = String::new();
10069        let buffer = self.buffer.read(cx).snapshot(cx);
10070        let mut selections = self.selections.all::<Point>(cx);
10071        let mut clipboard_selections = Vec::with_capacity(selections.len());
10072        {
10073            let max_point = buffer.max_point();
10074            let mut is_first = true;
10075            for selection in &mut selections {
10076                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10077                if is_entire_line {
10078                    selection.start = Point::new(selection.start.row, 0);
10079                    if !selection.is_empty() && selection.end.column == 0 {
10080                        selection.end = cmp::min(max_point, selection.end);
10081                    } else {
10082                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10083                    }
10084                    selection.goal = SelectionGoal::None;
10085                }
10086                if is_first {
10087                    is_first = false;
10088                } else {
10089                    text += "\n";
10090                }
10091                let mut len = 0;
10092                for chunk in buffer.text_for_range(selection.start..selection.end) {
10093                    text.push_str(chunk);
10094                    len += chunk.len();
10095                }
10096                clipboard_selections.push(ClipboardSelection {
10097                    len,
10098                    is_entire_line,
10099                    first_line_indent: buffer
10100                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10101                        .len,
10102                });
10103            }
10104        }
10105
10106        self.transact(window, cx, |this, window, cx| {
10107            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10108                s.select(selections);
10109            });
10110            this.insert("", window, cx);
10111        });
10112        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10113    }
10114
10115    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10116        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10117        let item = self.cut_common(window, cx);
10118        cx.write_to_clipboard(item);
10119    }
10120
10121    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10122        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10123        self.change_selections(None, window, cx, |s| {
10124            s.move_with(|snapshot, sel| {
10125                if sel.is_empty() {
10126                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10127                }
10128            });
10129        });
10130        let item = self.cut_common(window, cx);
10131        cx.set_global(KillRing(item))
10132    }
10133
10134    pub fn kill_ring_yank(
10135        &mut self,
10136        _: &KillRingYank,
10137        window: &mut Window,
10138        cx: &mut Context<Self>,
10139    ) {
10140        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10141        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10142            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10143                (kill_ring.text().to_string(), kill_ring.metadata_json())
10144            } else {
10145                return;
10146            }
10147        } else {
10148            return;
10149        };
10150        self.do_paste(&text, metadata, false, window, cx);
10151    }
10152
10153    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10154        self.do_copy(true, cx);
10155    }
10156
10157    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10158        self.do_copy(false, cx);
10159    }
10160
10161    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10162        let selections = self.selections.all::<Point>(cx);
10163        let buffer = self.buffer.read(cx).read(cx);
10164        let mut text = String::new();
10165
10166        let mut clipboard_selections = Vec::with_capacity(selections.len());
10167        {
10168            let max_point = buffer.max_point();
10169            let mut is_first = true;
10170            for selection in &selections {
10171                let mut start = selection.start;
10172                let mut end = selection.end;
10173                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10174                if is_entire_line {
10175                    start = Point::new(start.row, 0);
10176                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10177                }
10178
10179                let mut trimmed_selections = Vec::new();
10180                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10181                    let row = MultiBufferRow(start.row);
10182                    let first_indent = buffer.indent_size_for_line(row);
10183                    if first_indent.len == 0 || start.column > first_indent.len {
10184                        trimmed_selections.push(start..end);
10185                    } else {
10186                        trimmed_selections.push(
10187                            Point::new(row.0, first_indent.len)
10188                                ..Point::new(row.0, buffer.line_len(row)),
10189                        );
10190                        for row in start.row + 1..=end.row {
10191                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10192                            if row == end.row {
10193                                line_len = end.column;
10194                            }
10195                            if line_len == 0 {
10196                                trimmed_selections
10197                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10198                                continue;
10199                            }
10200                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10201                            if row_indent_size.len >= first_indent.len {
10202                                trimmed_selections.push(
10203                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10204                                );
10205                            } else {
10206                                trimmed_selections.clear();
10207                                trimmed_selections.push(start..end);
10208                                break;
10209                            }
10210                        }
10211                    }
10212                } else {
10213                    trimmed_selections.push(start..end);
10214                }
10215
10216                for trimmed_range in trimmed_selections {
10217                    if is_first {
10218                        is_first = false;
10219                    } else {
10220                        text += "\n";
10221                    }
10222                    let mut len = 0;
10223                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10224                        text.push_str(chunk);
10225                        len += chunk.len();
10226                    }
10227                    clipboard_selections.push(ClipboardSelection {
10228                        len,
10229                        is_entire_line,
10230                        first_line_indent: buffer
10231                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10232                            .len,
10233                    });
10234                }
10235            }
10236        }
10237
10238        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10239            text,
10240            clipboard_selections,
10241        ));
10242    }
10243
10244    pub fn do_paste(
10245        &mut self,
10246        text: &String,
10247        clipboard_selections: Option<Vec<ClipboardSelection>>,
10248        handle_entire_lines: bool,
10249        window: &mut Window,
10250        cx: &mut Context<Self>,
10251    ) {
10252        if self.read_only(cx) {
10253            return;
10254        }
10255
10256        let clipboard_text = Cow::Borrowed(text);
10257
10258        self.transact(window, cx, |this, window, cx| {
10259            if let Some(mut clipboard_selections) = clipboard_selections {
10260                let old_selections = this.selections.all::<usize>(cx);
10261                let all_selections_were_entire_line =
10262                    clipboard_selections.iter().all(|s| s.is_entire_line);
10263                let first_selection_indent_column =
10264                    clipboard_selections.first().map(|s| s.first_line_indent);
10265                if clipboard_selections.len() != old_selections.len() {
10266                    clipboard_selections.drain(..);
10267                }
10268                let cursor_offset = this.selections.last::<usize>(cx).head();
10269                let mut auto_indent_on_paste = true;
10270
10271                this.buffer.update(cx, |buffer, cx| {
10272                    let snapshot = buffer.read(cx);
10273                    auto_indent_on_paste = snapshot
10274                        .language_settings_at(cursor_offset, cx)
10275                        .auto_indent_on_paste;
10276
10277                    let mut start_offset = 0;
10278                    let mut edits = Vec::new();
10279                    let mut original_indent_columns = Vec::new();
10280                    for (ix, selection) in old_selections.iter().enumerate() {
10281                        let to_insert;
10282                        let entire_line;
10283                        let original_indent_column;
10284                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10285                            let end_offset = start_offset + clipboard_selection.len;
10286                            to_insert = &clipboard_text[start_offset..end_offset];
10287                            entire_line = clipboard_selection.is_entire_line;
10288                            start_offset = end_offset + 1;
10289                            original_indent_column = Some(clipboard_selection.first_line_indent);
10290                        } else {
10291                            to_insert = clipboard_text.as_str();
10292                            entire_line = all_selections_were_entire_line;
10293                            original_indent_column = first_selection_indent_column
10294                        }
10295
10296                        // If the corresponding selection was empty when this slice of the
10297                        // clipboard text was written, then the entire line containing the
10298                        // selection was copied. If this selection is also currently empty,
10299                        // then paste the line before the current line of the buffer.
10300                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10301                            let column = selection.start.to_point(&snapshot).column as usize;
10302                            let line_start = selection.start - column;
10303                            line_start..line_start
10304                        } else {
10305                            selection.range()
10306                        };
10307
10308                        edits.push((range, to_insert));
10309                        original_indent_columns.push(original_indent_column);
10310                    }
10311                    drop(snapshot);
10312
10313                    buffer.edit(
10314                        edits,
10315                        if auto_indent_on_paste {
10316                            Some(AutoindentMode::Block {
10317                                original_indent_columns,
10318                            })
10319                        } else {
10320                            None
10321                        },
10322                        cx,
10323                    );
10324                });
10325
10326                let selections = this.selections.all::<usize>(cx);
10327                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10328                    s.select(selections)
10329                });
10330            } else {
10331                this.insert(&clipboard_text, window, cx);
10332            }
10333        });
10334    }
10335
10336    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10337        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10338        if let Some(item) = cx.read_from_clipboard() {
10339            let entries = item.entries();
10340
10341            match entries.first() {
10342                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10343                // of all the pasted entries.
10344                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10345                    .do_paste(
10346                        clipboard_string.text(),
10347                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10348                        true,
10349                        window,
10350                        cx,
10351                    ),
10352                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10353            }
10354        }
10355    }
10356
10357    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10358        if self.read_only(cx) {
10359            return;
10360        }
10361
10362        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10363
10364        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10365            if let Some((selections, _)) =
10366                self.selection_history.transaction(transaction_id).cloned()
10367            {
10368                self.change_selections(None, window, cx, |s| {
10369                    s.select_anchors(selections.to_vec());
10370                });
10371            } else {
10372                log::error!(
10373                    "No entry in selection_history found for undo. \
10374                     This may correspond to a bug where undo does not update the selection. \
10375                     If this is occurring, please add details to \
10376                     https://github.com/zed-industries/zed/issues/22692"
10377                );
10378            }
10379            self.request_autoscroll(Autoscroll::fit(), cx);
10380            self.unmark_text(window, cx);
10381            self.refresh_inline_completion(true, false, window, cx);
10382            cx.emit(EditorEvent::Edited { transaction_id });
10383            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10384        }
10385    }
10386
10387    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10388        if self.read_only(cx) {
10389            return;
10390        }
10391
10392        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10393
10394        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10395            if let Some((_, Some(selections))) =
10396                self.selection_history.transaction(transaction_id).cloned()
10397            {
10398                self.change_selections(None, window, cx, |s| {
10399                    s.select_anchors(selections.to_vec());
10400                });
10401            } else {
10402                log::error!(
10403                    "No entry in selection_history found for redo. \
10404                     This may correspond to a bug where undo does not update the selection. \
10405                     If this is occurring, please add details to \
10406                     https://github.com/zed-industries/zed/issues/22692"
10407                );
10408            }
10409            self.request_autoscroll(Autoscroll::fit(), cx);
10410            self.unmark_text(window, cx);
10411            self.refresh_inline_completion(true, false, window, cx);
10412            cx.emit(EditorEvent::Edited { transaction_id });
10413        }
10414    }
10415
10416    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10417        self.buffer
10418            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10419    }
10420
10421    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10422        self.buffer
10423            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10424    }
10425
10426    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10427        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10428        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10429            s.move_with(|map, selection| {
10430                let cursor = if selection.is_empty() {
10431                    movement::left(map, selection.start)
10432                } else {
10433                    selection.start
10434                };
10435                selection.collapse_to(cursor, SelectionGoal::None);
10436            });
10437        })
10438    }
10439
10440    pub fn select_left(&mut self, _: &SelectLeft, 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_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10444        })
10445    }
10446
10447    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10448        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10449        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10450            s.move_with(|map, selection| {
10451                let cursor = if selection.is_empty() {
10452                    movement::right(map, selection.end)
10453                } else {
10454                    selection.end
10455                };
10456                selection.collapse_to(cursor, SelectionGoal::None)
10457            });
10458        })
10459    }
10460
10461    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10462        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10463        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10464            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10465        })
10466    }
10467
10468    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10469        if self.take_rename(true, window, cx).is_some() {
10470            return;
10471        }
10472
10473        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10474            cx.propagate();
10475            return;
10476        }
10477
10478        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10479
10480        let text_layout_details = &self.text_layout_details(window);
10481        let selection_count = self.selections.count();
10482        let first_selection = self.selections.first_anchor();
10483
10484        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10485            s.move_with(|map, selection| {
10486                if !selection.is_empty() {
10487                    selection.goal = SelectionGoal::None;
10488                }
10489                let (cursor, goal) = movement::up(
10490                    map,
10491                    selection.start,
10492                    selection.goal,
10493                    false,
10494                    text_layout_details,
10495                );
10496                selection.collapse_to(cursor, goal);
10497            });
10498        });
10499
10500        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10501        {
10502            cx.propagate();
10503        }
10504    }
10505
10506    pub fn move_up_by_lines(
10507        &mut self,
10508        action: &MoveUpByLines,
10509        window: &mut Window,
10510        cx: &mut Context<Self>,
10511    ) {
10512        if self.take_rename(true, window, cx).is_some() {
10513            return;
10514        }
10515
10516        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10517            cx.propagate();
10518            return;
10519        }
10520
10521        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10522
10523        let text_layout_details = &self.text_layout_details(window);
10524
10525        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10526            s.move_with(|map, selection| {
10527                if !selection.is_empty() {
10528                    selection.goal = SelectionGoal::None;
10529                }
10530                let (cursor, goal) = movement::up_by_rows(
10531                    map,
10532                    selection.start,
10533                    action.lines,
10534                    selection.goal,
10535                    false,
10536                    text_layout_details,
10537                );
10538                selection.collapse_to(cursor, goal);
10539            });
10540        })
10541    }
10542
10543    pub fn move_down_by_lines(
10544        &mut self,
10545        action: &MoveDownByLines,
10546        window: &mut Window,
10547        cx: &mut Context<Self>,
10548    ) {
10549        if self.take_rename(true, window, cx).is_some() {
10550            return;
10551        }
10552
10553        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10554            cx.propagate();
10555            return;
10556        }
10557
10558        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10559
10560        let text_layout_details = &self.text_layout_details(window);
10561
10562        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10563            s.move_with(|map, selection| {
10564                if !selection.is_empty() {
10565                    selection.goal = SelectionGoal::None;
10566                }
10567                let (cursor, goal) = movement::down_by_rows(
10568                    map,
10569                    selection.start,
10570                    action.lines,
10571                    selection.goal,
10572                    false,
10573                    text_layout_details,
10574                );
10575                selection.collapse_to(cursor, goal);
10576            });
10577        })
10578    }
10579
10580    pub fn select_down_by_lines(
10581        &mut self,
10582        action: &SelectDownByLines,
10583        window: &mut Window,
10584        cx: &mut Context<Self>,
10585    ) {
10586        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10587        let text_layout_details = &self.text_layout_details(window);
10588        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10589            s.move_heads_with(|map, head, goal| {
10590                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10591            })
10592        })
10593    }
10594
10595    pub fn select_up_by_lines(
10596        &mut self,
10597        action: &SelectUpByLines,
10598        window: &mut Window,
10599        cx: &mut Context<Self>,
10600    ) {
10601        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10602        let text_layout_details = &self.text_layout_details(window);
10603        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10604            s.move_heads_with(|map, head, goal| {
10605                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10606            })
10607        })
10608    }
10609
10610    pub fn select_page_up(
10611        &mut self,
10612        _: &SelectPageUp,
10613        window: &mut Window,
10614        cx: &mut Context<Self>,
10615    ) {
10616        let Some(row_count) = self.visible_row_count() else {
10617            return;
10618        };
10619
10620        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10621
10622        let text_layout_details = &self.text_layout_details(window);
10623
10624        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10625            s.move_heads_with(|map, head, goal| {
10626                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10627            })
10628        })
10629    }
10630
10631    pub fn move_page_up(
10632        &mut self,
10633        action: &MovePageUp,
10634        window: &mut Window,
10635        cx: &mut Context<Self>,
10636    ) {
10637        if self.take_rename(true, window, cx).is_some() {
10638            return;
10639        }
10640
10641        if self
10642            .context_menu
10643            .borrow_mut()
10644            .as_mut()
10645            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10646            .unwrap_or(false)
10647        {
10648            return;
10649        }
10650
10651        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10652            cx.propagate();
10653            return;
10654        }
10655
10656        let Some(row_count) = self.visible_row_count() else {
10657            return;
10658        };
10659
10660        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10661
10662        let autoscroll = if action.center_cursor {
10663            Autoscroll::center()
10664        } else {
10665            Autoscroll::fit()
10666        };
10667
10668        let text_layout_details = &self.text_layout_details(window);
10669
10670        self.change_selections(Some(autoscroll), window, cx, |s| {
10671            s.move_with(|map, selection| {
10672                if !selection.is_empty() {
10673                    selection.goal = SelectionGoal::None;
10674                }
10675                let (cursor, goal) = movement::up_by_rows(
10676                    map,
10677                    selection.end,
10678                    row_count,
10679                    selection.goal,
10680                    false,
10681                    text_layout_details,
10682                );
10683                selection.collapse_to(cursor, goal);
10684            });
10685        });
10686    }
10687
10688    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10689        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10690        let text_layout_details = &self.text_layout_details(window);
10691        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10692            s.move_heads_with(|map, head, goal| {
10693                movement::up(map, head, goal, false, text_layout_details)
10694            })
10695        })
10696    }
10697
10698    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10699        self.take_rename(true, window, cx);
10700
10701        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10702            cx.propagate();
10703            return;
10704        }
10705
10706        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10707
10708        let text_layout_details = &self.text_layout_details(window);
10709        let selection_count = self.selections.count();
10710        let first_selection = self.selections.first_anchor();
10711
10712        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10713            s.move_with(|map, selection| {
10714                if !selection.is_empty() {
10715                    selection.goal = SelectionGoal::None;
10716                }
10717                let (cursor, goal) = movement::down(
10718                    map,
10719                    selection.end,
10720                    selection.goal,
10721                    false,
10722                    text_layout_details,
10723                );
10724                selection.collapse_to(cursor, goal);
10725            });
10726        });
10727
10728        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10729        {
10730            cx.propagate();
10731        }
10732    }
10733
10734    pub fn select_page_down(
10735        &mut self,
10736        _: &SelectPageDown,
10737        window: &mut Window,
10738        cx: &mut Context<Self>,
10739    ) {
10740        let Some(row_count) = self.visible_row_count() else {
10741            return;
10742        };
10743
10744        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10745
10746        let text_layout_details = &self.text_layout_details(window);
10747
10748        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10749            s.move_heads_with(|map, head, goal| {
10750                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10751            })
10752        })
10753    }
10754
10755    pub fn move_page_down(
10756        &mut self,
10757        action: &MovePageDown,
10758        window: &mut Window,
10759        cx: &mut Context<Self>,
10760    ) {
10761        if self.take_rename(true, window, cx).is_some() {
10762            return;
10763        }
10764
10765        if self
10766            .context_menu
10767            .borrow_mut()
10768            .as_mut()
10769            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10770            .unwrap_or(false)
10771        {
10772            return;
10773        }
10774
10775        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10776            cx.propagate();
10777            return;
10778        }
10779
10780        let Some(row_count) = self.visible_row_count() else {
10781            return;
10782        };
10783
10784        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10785
10786        let autoscroll = if action.center_cursor {
10787            Autoscroll::center()
10788        } else {
10789            Autoscroll::fit()
10790        };
10791
10792        let text_layout_details = &self.text_layout_details(window);
10793        self.change_selections(Some(autoscroll), window, cx, |s| {
10794            s.move_with(|map, selection| {
10795                if !selection.is_empty() {
10796                    selection.goal = SelectionGoal::None;
10797                }
10798                let (cursor, goal) = movement::down_by_rows(
10799                    map,
10800                    selection.end,
10801                    row_count,
10802                    selection.goal,
10803                    false,
10804                    text_layout_details,
10805                );
10806                selection.collapse_to(cursor, goal);
10807            });
10808        });
10809    }
10810
10811    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10812        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10813        let text_layout_details = &self.text_layout_details(window);
10814        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10815            s.move_heads_with(|map, head, goal| {
10816                movement::down(map, head, goal, false, text_layout_details)
10817            })
10818        });
10819    }
10820
10821    pub fn context_menu_first(
10822        &mut self,
10823        _: &ContextMenuFirst,
10824        _window: &mut Window,
10825        cx: &mut Context<Self>,
10826    ) {
10827        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10828            context_menu.select_first(self.completion_provider.as_deref(), cx);
10829        }
10830    }
10831
10832    pub fn context_menu_prev(
10833        &mut self,
10834        _: &ContextMenuPrevious,
10835        _window: &mut Window,
10836        cx: &mut Context<Self>,
10837    ) {
10838        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10839            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10840        }
10841    }
10842
10843    pub fn context_menu_next(
10844        &mut self,
10845        _: &ContextMenuNext,
10846        _window: &mut Window,
10847        cx: &mut Context<Self>,
10848    ) {
10849        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10850            context_menu.select_next(self.completion_provider.as_deref(), cx);
10851        }
10852    }
10853
10854    pub fn context_menu_last(
10855        &mut self,
10856        _: &ContextMenuLast,
10857        _window: &mut Window,
10858        cx: &mut Context<Self>,
10859    ) {
10860        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10861            context_menu.select_last(self.completion_provider.as_deref(), cx);
10862        }
10863    }
10864
10865    pub fn move_to_previous_word_start(
10866        &mut self,
10867        _: &MoveToPreviousWordStart,
10868        window: &mut Window,
10869        cx: &mut Context<Self>,
10870    ) {
10871        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10872        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10873            s.move_cursors_with(|map, head, _| {
10874                (
10875                    movement::previous_word_start(map, head),
10876                    SelectionGoal::None,
10877                )
10878            });
10879        })
10880    }
10881
10882    pub fn move_to_previous_subword_start(
10883        &mut self,
10884        _: &MoveToPreviousSubwordStart,
10885        window: &mut Window,
10886        cx: &mut Context<Self>,
10887    ) {
10888        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10889        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10890            s.move_cursors_with(|map, head, _| {
10891                (
10892                    movement::previous_subword_start(map, head),
10893                    SelectionGoal::None,
10894                )
10895            });
10896        })
10897    }
10898
10899    pub fn select_to_previous_word_start(
10900        &mut self,
10901        _: &SelectToPreviousWordStart,
10902        window: &mut Window,
10903        cx: &mut Context<Self>,
10904    ) {
10905        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10906        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10907            s.move_heads_with(|map, head, _| {
10908                (
10909                    movement::previous_word_start(map, head),
10910                    SelectionGoal::None,
10911                )
10912            });
10913        })
10914    }
10915
10916    pub fn select_to_previous_subword_start(
10917        &mut self,
10918        _: &SelectToPreviousSubwordStart,
10919        window: &mut Window,
10920        cx: &mut Context<Self>,
10921    ) {
10922        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10923        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10924            s.move_heads_with(|map, head, _| {
10925                (
10926                    movement::previous_subword_start(map, head),
10927                    SelectionGoal::None,
10928                )
10929            });
10930        })
10931    }
10932
10933    pub fn delete_to_previous_word_start(
10934        &mut self,
10935        action: &DeleteToPreviousWordStart,
10936        window: &mut Window,
10937        cx: &mut Context<Self>,
10938    ) {
10939        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10940        self.transact(window, cx, |this, window, cx| {
10941            this.select_autoclose_pair(window, cx);
10942            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10943                s.move_with(|map, selection| {
10944                    if selection.is_empty() {
10945                        let cursor = if action.ignore_newlines {
10946                            movement::previous_word_start(map, selection.head())
10947                        } else {
10948                            movement::previous_word_start_or_newline(map, selection.head())
10949                        };
10950                        selection.set_head(cursor, SelectionGoal::None);
10951                    }
10952                });
10953            });
10954            this.insert("", window, cx);
10955        });
10956    }
10957
10958    pub fn delete_to_previous_subword_start(
10959        &mut self,
10960        _: &DeleteToPreviousSubwordStart,
10961        window: &mut Window,
10962        cx: &mut Context<Self>,
10963    ) {
10964        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10965        self.transact(window, cx, |this, window, cx| {
10966            this.select_autoclose_pair(window, cx);
10967            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10968                s.move_with(|map, selection| {
10969                    if selection.is_empty() {
10970                        let cursor = movement::previous_subword_start(map, selection.head());
10971                        selection.set_head(cursor, SelectionGoal::None);
10972                    }
10973                });
10974            });
10975            this.insert("", window, cx);
10976        });
10977    }
10978
10979    pub fn move_to_next_word_end(
10980        &mut self,
10981        _: &MoveToNextWordEnd,
10982        window: &mut Window,
10983        cx: &mut Context<Self>,
10984    ) {
10985        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10986        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10987            s.move_cursors_with(|map, head, _| {
10988                (movement::next_word_end(map, head), SelectionGoal::None)
10989            });
10990        })
10991    }
10992
10993    pub fn move_to_next_subword_end(
10994        &mut self,
10995        _: &MoveToNextSubwordEnd,
10996        window: &mut Window,
10997        cx: &mut Context<Self>,
10998    ) {
10999        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11000        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11001            s.move_cursors_with(|map, head, _| {
11002                (movement::next_subword_end(map, head), SelectionGoal::None)
11003            });
11004        })
11005    }
11006
11007    pub fn select_to_next_word_end(
11008        &mut self,
11009        _: &SelectToNextWordEnd,
11010        window: &mut Window,
11011        cx: &mut Context<Self>,
11012    ) {
11013        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11014        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11015            s.move_heads_with(|map, head, _| {
11016                (movement::next_word_end(map, head), SelectionGoal::None)
11017            });
11018        })
11019    }
11020
11021    pub fn select_to_next_subword_end(
11022        &mut self,
11023        _: &SelectToNextSubwordEnd,
11024        window: &mut Window,
11025        cx: &mut Context<Self>,
11026    ) {
11027        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11028        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11029            s.move_heads_with(|map, head, _| {
11030                (movement::next_subword_end(map, head), SelectionGoal::None)
11031            });
11032        })
11033    }
11034
11035    pub fn delete_to_next_word_end(
11036        &mut self,
11037        action: &DeleteToNextWordEnd,
11038        window: &mut Window,
11039        cx: &mut Context<Self>,
11040    ) {
11041        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11042        self.transact(window, cx, |this, window, cx| {
11043            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11044                s.move_with(|map, selection| {
11045                    if selection.is_empty() {
11046                        let cursor = if action.ignore_newlines {
11047                            movement::next_word_end(map, selection.head())
11048                        } else {
11049                            movement::next_word_end_or_newline(map, selection.head())
11050                        };
11051                        selection.set_head(cursor, SelectionGoal::None);
11052                    }
11053                });
11054            });
11055            this.insert("", window, cx);
11056        });
11057    }
11058
11059    pub fn delete_to_next_subword_end(
11060        &mut self,
11061        _: &DeleteToNextSubwordEnd,
11062        window: &mut Window,
11063        cx: &mut Context<Self>,
11064    ) {
11065        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11066        self.transact(window, cx, |this, window, cx| {
11067            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11068                s.move_with(|map, selection| {
11069                    if selection.is_empty() {
11070                        let cursor = movement::next_subword_end(map, selection.head());
11071                        selection.set_head(cursor, SelectionGoal::None);
11072                    }
11073                });
11074            });
11075            this.insert("", window, cx);
11076        });
11077    }
11078
11079    pub fn move_to_beginning_of_line(
11080        &mut self,
11081        action: &MoveToBeginningOfLine,
11082        window: &mut Window,
11083        cx: &mut Context<Self>,
11084    ) {
11085        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11086        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11087            s.move_cursors_with(|map, head, _| {
11088                (
11089                    movement::indented_line_beginning(
11090                        map,
11091                        head,
11092                        action.stop_at_soft_wraps,
11093                        action.stop_at_indent,
11094                    ),
11095                    SelectionGoal::None,
11096                )
11097            });
11098        })
11099    }
11100
11101    pub fn select_to_beginning_of_line(
11102        &mut self,
11103        action: &SelectToBeginningOfLine,
11104        window: &mut Window,
11105        cx: &mut Context<Self>,
11106    ) {
11107        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11108        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11109            s.move_heads_with(|map, head, _| {
11110                (
11111                    movement::indented_line_beginning(
11112                        map,
11113                        head,
11114                        action.stop_at_soft_wraps,
11115                        action.stop_at_indent,
11116                    ),
11117                    SelectionGoal::None,
11118                )
11119            });
11120        });
11121    }
11122
11123    pub fn delete_to_beginning_of_line(
11124        &mut self,
11125        action: &DeleteToBeginningOfLine,
11126        window: &mut Window,
11127        cx: &mut Context<Self>,
11128    ) {
11129        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11130        self.transact(window, cx, |this, window, cx| {
11131            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11132                s.move_with(|_, selection| {
11133                    selection.reversed = true;
11134                });
11135            });
11136
11137            this.select_to_beginning_of_line(
11138                &SelectToBeginningOfLine {
11139                    stop_at_soft_wraps: false,
11140                    stop_at_indent: action.stop_at_indent,
11141                },
11142                window,
11143                cx,
11144            );
11145            this.backspace(&Backspace, window, cx);
11146        });
11147    }
11148
11149    pub fn move_to_end_of_line(
11150        &mut self,
11151        action: &MoveToEndOfLine,
11152        window: &mut Window,
11153        cx: &mut Context<Self>,
11154    ) {
11155        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11156        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11157            s.move_cursors_with(|map, head, _| {
11158                (
11159                    movement::line_end(map, head, action.stop_at_soft_wraps),
11160                    SelectionGoal::None,
11161                )
11162            });
11163        })
11164    }
11165
11166    pub fn select_to_end_of_line(
11167        &mut self,
11168        action: &SelectToEndOfLine,
11169        window: &mut Window,
11170        cx: &mut Context<Self>,
11171    ) {
11172        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11173        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11174            s.move_heads_with(|map, head, _| {
11175                (
11176                    movement::line_end(map, head, action.stop_at_soft_wraps),
11177                    SelectionGoal::None,
11178                )
11179            });
11180        })
11181    }
11182
11183    pub fn delete_to_end_of_line(
11184        &mut self,
11185        _: &DeleteToEndOfLine,
11186        window: &mut Window,
11187        cx: &mut Context<Self>,
11188    ) {
11189        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11190        self.transact(window, cx, |this, window, cx| {
11191            this.select_to_end_of_line(
11192                &SelectToEndOfLine {
11193                    stop_at_soft_wraps: false,
11194                },
11195                window,
11196                cx,
11197            );
11198            this.delete(&Delete, window, cx);
11199        });
11200    }
11201
11202    pub fn cut_to_end_of_line(
11203        &mut self,
11204        _: &CutToEndOfLine,
11205        window: &mut Window,
11206        cx: &mut Context<Self>,
11207    ) {
11208        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11209        self.transact(window, cx, |this, window, cx| {
11210            this.select_to_end_of_line(
11211                &SelectToEndOfLine {
11212                    stop_at_soft_wraps: false,
11213                },
11214                window,
11215                cx,
11216            );
11217            this.cut(&Cut, window, cx);
11218        });
11219    }
11220
11221    pub fn move_to_start_of_paragraph(
11222        &mut self,
11223        _: &MoveToStartOfParagraph,
11224        window: &mut Window,
11225        cx: &mut Context<Self>,
11226    ) {
11227        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11228            cx.propagate();
11229            return;
11230        }
11231        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11232        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11233            s.move_with(|map, selection| {
11234                selection.collapse_to(
11235                    movement::start_of_paragraph(map, selection.head(), 1),
11236                    SelectionGoal::None,
11237                )
11238            });
11239        })
11240    }
11241
11242    pub fn move_to_end_of_paragraph(
11243        &mut self,
11244        _: &MoveToEndOfParagraph,
11245        window: &mut Window,
11246        cx: &mut Context<Self>,
11247    ) {
11248        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11249            cx.propagate();
11250            return;
11251        }
11252        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11253        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11254            s.move_with(|map, selection| {
11255                selection.collapse_to(
11256                    movement::end_of_paragraph(map, selection.head(), 1),
11257                    SelectionGoal::None,
11258                )
11259            });
11260        })
11261    }
11262
11263    pub fn select_to_start_of_paragraph(
11264        &mut self,
11265        _: &SelectToStartOfParagraph,
11266        window: &mut Window,
11267        cx: &mut Context<Self>,
11268    ) {
11269        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11270            cx.propagate();
11271            return;
11272        }
11273        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11274        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11275            s.move_heads_with(|map, head, _| {
11276                (
11277                    movement::start_of_paragraph(map, head, 1),
11278                    SelectionGoal::None,
11279                )
11280            });
11281        })
11282    }
11283
11284    pub fn select_to_end_of_paragraph(
11285        &mut self,
11286        _: &SelectToEndOfParagraph,
11287        window: &mut Window,
11288        cx: &mut Context<Self>,
11289    ) {
11290        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11291            cx.propagate();
11292            return;
11293        }
11294        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11295        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11296            s.move_heads_with(|map, head, _| {
11297                (
11298                    movement::end_of_paragraph(map, head, 1),
11299                    SelectionGoal::None,
11300                )
11301            });
11302        })
11303    }
11304
11305    pub fn move_to_start_of_excerpt(
11306        &mut self,
11307        _: &MoveToStartOfExcerpt,
11308        window: &mut Window,
11309        cx: &mut Context<Self>,
11310    ) {
11311        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11312            cx.propagate();
11313            return;
11314        }
11315        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11316        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11317            s.move_with(|map, selection| {
11318                selection.collapse_to(
11319                    movement::start_of_excerpt(
11320                        map,
11321                        selection.head(),
11322                        workspace::searchable::Direction::Prev,
11323                    ),
11324                    SelectionGoal::None,
11325                )
11326            });
11327        })
11328    }
11329
11330    pub fn move_to_start_of_next_excerpt(
11331        &mut self,
11332        _: &MoveToStartOfNextExcerpt,
11333        window: &mut Window,
11334        cx: &mut Context<Self>,
11335    ) {
11336        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11337            cx.propagate();
11338            return;
11339        }
11340
11341        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11342            s.move_with(|map, selection| {
11343                selection.collapse_to(
11344                    movement::start_of_excerpt(
11345                        map,
11346                        selection.head(),
11347                        workspace::searchable::Direction::Next,
11348                    ),
11349                    SelectionGoal::None,
11350                )
11351            });
11352        })
11353    }
11354
11355    pub fn move_to_end_of_excerpt(
11356        &mut self,
11357        _: &MoveToEndOfExcerpt,
11358        window: &mut Window,
11359        cx: &mut Context<Self>,
11360    ) {
11361        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11362            cx.propagate();
11363            return;
11364        }
11365        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11366        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11367            s.move_with(|map, selection| {
11368                selection.collapse_to(
11369                    movement::end_of_excerpt(
11370                        map,
11371                        selection.head(),
11372                        workspace::searchable::Direction::Next,
11373                    ),
11374                    SelectionGoal::None,
11375                )
11376            });
11377        })
11378    }
11379
11380    pub fn move_to_end_of_previous_excerpt(
11381        &mut self,
11382        _: &MoveToEndOfPreviousExcerpt,
11383        window: &mut Window,
11384        cx: &mut Context<Self>,
11385    ) {
11386        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11387            cx.propagate();
11388            return;
11389        }
11390        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11391        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11392            s.move_with(|map, selection| {
11393                selection.collapse_to(
11394                    movement::end_of_excerpt(
11395                        map,
11396                        selection.head(),
11397                        workspace::searchable::Direction::Prev,
11398                    ),
11399                    SelectionGoal::None,
11400                )
11401            });
11402        })
11403    }
11404
11405    pub fn select_to_start_of_excerpt(
11406        &mut self,
11407        _: &SelectToStartOfExcerpt,
11408        window: &mut Window,
11409        cx: &mut Context<Self>,
11410    ) {
11411        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11412            cx.propagate();
11413            return;
11414        }
11415        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11416        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11417            s.move_heads_with(|map, head, _| {
11418                (
11419                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11420                    SelectionGoal::None,
11421                )
11422            });
11423        })
11424    }
11425
11426    pub fn select_to_start_of_next_excerpt(
11427        &mut self,
11428        _: &SelectToStartOfNextExcerpt,
11429        window: &mut Window,
11430        cx: &mut Context<Self>,
11431    ) {
11432        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11433            cx.propagate();
11434            return;
11435        }
11436        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11437        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11438            s.move_heads_with(|map, head, _| {
11439                (
11440                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11441                    SelectionGoal::None,
11442                )
11443            });
11444        })
11445    }
11446
11447    pub fn select_to_end_of_excerpt(
11448        &mut self,
11449        _: &SelectToEndOfExcerpt,
11450        window: &mut Window,
11451        cx: &mut Context<Self>,
11452    ) {
11453        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11454            cx.propagate();
11455            return;
11456        }
11457        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11458        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11459            s.move_heads_with(|map, head, _| {
11460                (
11461                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11462                    SelectionGoal::None,
11463                )
11464            });
11465        })
11466    }
11467
11468    pub fn select_to_end_of_previous_excerpt(
11469        &mut self,
11470        _: &SelectToEndOfPreviousExcerpt,
11471        window: &mut Window,
11472        cx: &mut Context<Self>,
11473    ) {
11474        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11475            cx.propagate();
11476            return;
11477        }
11478        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11479        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11480            s.move_heads_with(|map, head, _| {
11481                (
11482                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11483                    SelectionGoal::None,
11484                )
11485            });
11486        })
11487    }
11488
11489    pub fn move_to_beginning(
11490        &mut self,
11491        _: &MoveToBeginning,
11492        window: &mut Window,
11493        cx: &mut Context<Self>,
11494    ) {
11495        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11496            cx.propagate();
11497            return;
11498        }
11499        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11500        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11501            s.select_ranges(vec![0..0]);
11502        });
11503    }
11504
11505    pub fn select_to_beginning(
11506        &mut self,
11507        _: &SelectToBeginning,
11508        window: &mut Window,
11509        cx: &mut Context<Self>,
11510    ) {
11511        let mut selection = self.selections.last::<Point>(cx);
11512        selection.set_head(Point::zero(), SelectionGoal::None);
11513        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11514        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11515            s.select(vec![selection]);
11516        });
11517    }
11518
11519    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11520        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11521            cx.propagate();
11522            return;
11523        }
11524        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11525        let cursor = self.buffer.read(cx).read(cx).len();
11526        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11527            s.select_ranges(vec![cursor..cursor])
11528        });
11529    }
11530
11531    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11532        self.nav_history = nav_history;
11533    }
11534
11535    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11536        self.nav_history.as_ref()
11537    }
11538
11539    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11540        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11541    }
11542
11543    fn push_to_nav_history(
11544        &mut self,
11545        cursor_anchor: Anchor,
11546        new_position: Option<Point>,
11547        is_deactivate: bool,
11548        cx: &mut Context<Self>,
11549    ) {
11550        if let Some(nav_history) = self.nav_history.as_mut() {
11551            let buffer = self.buffer.read(cx).read(cx);
11552            let cursor_position = cursor_anchor.to_point(&buffer);
11553            let scroll_state = self.scroll_manager.anchor();
11554            let scroll_top_row = scroll_state.top_row(&buffer);
11555            drop(buffer);
11556
11557            if let Some(new_position) = new_position {
11558                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11559                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11560                    return;
11561                }
11562            }
11563
11564            nav_history.push(
11565                Some(NavigationData {
11566                    cursor_anchor,
11567                    cursor_position,
11568                    scroll_anchor: scroll_state,
11569                    scroll_top_row,
11570                }),
11571                cx,
11572            );
11573            cx.emit(EditorEvent::PushedToNavHistory {
11574                anchor: cursor_anchor,
11575                is_deactivate,
11576            })
11577        }
11578    }
11579
11580    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11581        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11582        let buffer = self.buffer.read(cx).snapshot(cx);
11583        let mut selection = self.selections.first::<usize>(cx);
11584        selection.set_head(buffer.len(), SelectionGoal::None);
11585        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11586            s.select(vec![selection]);
11587        });
11588    }
11589
11590    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11591        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11592        let end = self.buffer.read(cx).read(cx).len();
11593        self.change_selections(None, window, cx, |s| {
11594            s.select_ranges(vec![0..end]);
11595        });
11596    }
11597
11598    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11599        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11600        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11601        let mut selections = self.selections.all::<Point>(cx);
11602        let max_point = display_map.buffer_snapshot.max_point();
11603        for selection in &mut selections {
11604            let rows = selection.spanned_rows(true, &display_map);
11605            selection.start = Point::new(rows.start.0, 0);
11606            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11607            selection.reversed = false;
11608        }
11609        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11610            s.select(selections);
11611        });
11612    }
11613
11614    pub fn split_selection_into_lines(
11615        &mut self,
11616        _: &SplitSelectionIntoLines,
11617        window: &mut Window,
11618        cx: &mut Context<Self>,
11619    ) {
11620        let selections = self
11621            .selections
11622            .all::<Point>(cx)
11623            .into_iter()
11624            .map(|selection| selection.start..selection.end)
11625            .collect::<Vec<_>>();
11626        self.unfold_ranges(&selections, true, true, cx);
11627
11628        let mut new_selection_ranges = Vec::new();
11629        {
11630            let buffer = self.buffer.read(cx).read(cx);
11631            for selection in selections {
11632                for row in selection.start.row..selection.end.row {
11633                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11634                    new_selection_ranges.push(cursor..cursor);
11635                }
11636
11637                let is_multiline_selection = selection.start.row != selection.end.row;
11638                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11639                // so this action feels more ergonomic when paired with other selection operations
11640                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11641                if !should_skip_last {
11642                    new_selection_ranges.push(selection.end..selection.end);
11643                }
11644            }
11645        }
11646        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11647            s.select_ranges(new_selection_ranges);
11648        });
11649    }
11650
11651    pub fn add_selection_above(
11652        &mut self,
11653        _: &AddSelectionAbove,
11654        window: &mut Window,
11655        cx: &mut Context<Self>,
11656    ) {
11657        self.add_selection(true, window, cx);
11658    }
11659
11660    pub fn add_selection_below(
11661        &mut self,
11662        _: &AddSelectionBelow,
11663        window: &mut Window,
11664        cx: &mut Context<Self>,
11665    ) {
11666        self.add_selection(false, window, cx);
11667    }
11668
11669    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11670        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11671
11672        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11673        let mut selections = self.selections.all::<Point>(cx);
11674        let text_layout_details = self.text_layout_details(window);
11675        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11676            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11677            let range = oldest_selection.display_range(&display_map).sorted();
11678
11679            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11680            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11681            let positions = start_x.min(end_x)..start_x.max(end_x);
11682
11683            selections.clear();
11684            let mut stack = Vec::new();
11685            for row in range.start.row().0..=range.end.row().0 {
11686                if let Some(selection) = self.selections.build_columnar_selection(
11687                    &display_map,
11688                    DisplayRow(row),
11689                    &positions,
11690                    oldest_selection.reversed,
11691                    &text_layout_details,
11692                ) {
11693                    stack.push(selection.id);
11694                    selections.push(selection);
11695                }
11696            }
11697
11698            if above {
11699                stack.reverse();
11700            }
11701
11702            AddSelectionsState { above, stack }
11703        });
11704
11705        let last_added_selection = *state.stack.last().unwrap();
11706        let mut new_selections = Vec::new();
11707        if above == state.above {
11708            let end_row = if above {
11709                DisplayRow(0)
11710            } else {
11711                display_map.max_point().row()
11712            };
11713
11714            'outer: for selection in selections {
11715                if selection.id == last_added_selection {
11716                    let range = selection.display_range(&display_map).sorted();
11717                    debug_assert_eq!(range.start.row(), range.end.row());
11718                    let mut row = range.start.row();
11719                    let positions =
11720                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11721                            px(start)..px(end)
11722                        } else {
11723                            let start_x =
11724                                display_map.x_for_display_point(range.start, &text_layout_details);
11725                            let end_x =
11726                                display_map.x_for_display_point(range.end, &text_layout_details);
11727                            start_x.min(end_x)..start_x.max(end_x)
11728                        };
11729
11730                    while row != end_row {
11731                        if above {
11732                            row.0 -= 1;
11733                        } else {
11734                            row.0 += 1;
11735                        }
11736
11737                        if let Some(new_selection) = self.selections.build_columnar_selection(
11738                            &display_map,
11739                            row,
11740                            &positions,
11741                            selection.reversed,
11742                            &text_layout_details,
11743                        ) {
11744                            state.stack.push(new_selection.id);
11745                            if above {
11746                                new_selections.push(new_selection);
11747                                new_selections.push(selection);
11748                            } else {
11749                                new_selections.push(selection);
11750                                new_selections.push(new_selection);
11751                            }
11752
11753                            continue 'outer;
11754                        }
11755                    }
11756                }
11757
11758                new_selections.push(selection);
11759            }
11760        } else {
11761            new_selections = selections;
11762            new_selections.retain(|s| s.id != last_added_selection);
11763            state.stack.pop();
11764        }
11765
11766        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11767            s.select(new_selections);
11768        });
11769        if state.stack.len() > 1 {
11770            self.add_selections_state = Some(state);
11771        }
11772    }
11773
11774    pub fn select_next_match_internal(
11775        &mut self,
11776        display_map: &DisplaySnapshot,
11777        replace_newest: bool,
11778        autoscroll: Option<Autoscroll>,
11779        window: &mut Window,
11780        cx: &mut Context<Self>,
11781    ) -> Result<()> {
11782        fn select_next_match_ranges(
11783            this: &mut Editor,
11784            range: Range<usize>,
11785            replace_newest: bool,
11786            auto_scroll: Option<Autoscroll>,
11787            window: &mut Window,
11788            cx: &mut Context<Editor>,
11789        ) {
11790            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11791            this.change_selections(auto_scroll, window, cx, |s| {
11792                if replace_newest {
11793                    s.delete(s.newest_anchor().id);
11794                }
11795                s.insert_range(range.clone());
11796            });
11797        }
11798
11799        let buffer = &display_map.buffer_snapshot;
11800        let mut selections = self.selections.all::<usize>(cx);
11801        if let Some(mut select_next_state) = self.select_next_state.take() {
11802            let query = &select_next_state.query;
11803            if !select_next_state.done {
11804                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11805                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11806                let mut next_selected_range = None;
11807
11808                let bytes_after_last_selection =
11809                    buffer.bytes_in_range(last_selection.end..buffer.len());
11810                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11811                let query_matches = query
11812                    .stream_find_iter(bytes_after_last_selection)
11813                    .map(|result| (last_selection.end, result))
11814                    .chain(
11815                        query
11816                            .stream_find_iter(bytes_before_first_selection)
11817                            .map(|result| (0, result)),
11818                    );
11819
11820                for (start_offset, query_match) in query_matches {
11821                    let query_match = query_match.unwrap(); // can only fail due to I/O
11822                    let offset_range =
11823                        start_offset + query_match.start()..start_offset + query_match.end();
11824                    let display_range = offset_range.start.to_display_point(display_map)
11825                        ..offset_range.end.to_display_point(display_map);
11826
11827                    if !select_next_state.wordwise
11828                        || (!movement::is_inside_word(display_map, display_range.start)
11829                            && !movement::is_inside_word(display_map, display_range.end))
11830                    {
11831                        // TODO: This is n^2, because we might check all the selections
11832                        if !selections
11833                            .iter()
11834                            .any(|selection| selection.range().overlaps(&offset_range))
11835                        {
11836                            next_selected_range = Some(offset_range);
11837                            break;
11838                        }
11839                    }
11840                }
11841
11842                if let Some(next_selected_range) = next_selected_range {
11843                    select_next_match_ranges(
11844                        self,
11845                        next_selected_range,
11846                        replace_newest,
11847                        autoscroll,
11848                        window,
11849                        cx,
11850                    );
11851                } else {
11852                    select_next_state.done = true;
11853                }
11854            }
11855
11856            self.select_next_state = Some(select_next_state);
11857        } else {
11858            let mut only_carets = true;
11859            let mut same_text_selected = true;
11860            let mut selected_text = None;
11861
11862            let mut selections_iter = selections.iter().peekable();
11863            while let Some(selection) = selections_iter.next() {
11864                if selection.start != selection.end {
11865                    only_carets = false;
11866                }
11867
11868                if same_text_selected {
11869                    if selected_text.is_none() {
11870                        selected_text =
11871                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11872                    }
11873
11874                    if let Some(next_selection) = selections_iter.peek() {
11875                        if next_selection.range().len() == selection.range().len() {
11876                            let next_selected_text = buffer
11877                                .text_for_range(next_selection.range())
11878                                .collect::<String>();
11879                            if Some(next_selected_text) != selected_text {
11880                                same_text_selected = false;
11881                                selected_text = None;
11882                            }
11883                        } else {
11884                            same_text_selected = false;
11885                            selected_text = None;
11886                        }
11887                    }
11888                }
11889            }
11890
11891            if only_carets {
11892                for selection in &mut selections {
11893                    let word_range = movement::surrounding_word(
11894                        display_map,
11895                        selection.start.to_display_point(display_map),
11896                    );
11897                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11898                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11899                    selection.goal = SelectionGoal::None;
11900                    selection.reversed = false;
11901                    select_next_match_ranges(
11902                        self,
11903                        selection.start..selection.end,
11904                        replace_newest,
11905                        autoscroll,
11906                        window,
11907                        cx,
11908                    );
11909                }
11910
11911                if selections.len() == 1 {
11912                    let selection = selections
11913                        .last()
11914                        .expect("ensured that there's only one selection");
11915                    let query = buffer
11916                        .text_for_range(selection.start..selection.end)
11917                        .collect::<String>();
11918                    let is_empty = query.is_empty();
11919                    let select_state = SelectNextState {
11920                        query: AhoCorasick::new(&[query])?,
11921                        wordwise: true,
11922                        done: is_empty,
11923                    };
11924                    self.select_next_state = Some(select_state);
11925                } else {
11926                    self.select_next_state = None;
11927                }
11928            } else if let Some(selected_text) = selected_text {
11929                self.select_next_state = Some(SelectNextState {
11930                    query: AhoCorasick::new(&[selected_text])?,
11931                    wordwise: false,
11932                    done: false,
11933                });
11934                self.select_next_match_internal(
11935                    display_map,
11936                    replace_newest,
11937                    autoscroll,
11938                    window,
11939                    cx,
11940                )?;
11941            }
11942        }
11943        Ok(())
11944    }
11945
11946    pub fn select_all_matches(
11947        &mut self,
11948        _action: &SelectAllMatches,
11949        window: &mut Window,
11950        cx: &mut Context<Self>,
11951    ) -> Result<()> {
11952        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11953
11954        self.push_to_selection_history();
11955        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11956
11957        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11958        let Some(select_next_state) = self.select_next_state.as_mut() else {
11959            return Ok(());
11960        };
11961        if select_next_state.done {
11962            return Ok(());
11963        }
11964
11965        let mut new_selections = Vec::new();
11966
11967        let reversed = self.selections.oldest::<usize>(cx).reversed;
11968        let buffer = &display_map.buffer_snapshot;
11969        let query_matches = select_next_state
11970            .query
11971            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11972
11973        for query_match in query_matches.into_iter() {
11974            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11975            let offset_range = if reversed {
11976                query_match.end()..query_match.start()
11977            } else {
11978                query_match.start()..query_match.end()
11979            };
11980            let display_range = offset_range.start.to_display_point(&display_map)
11981                ..offset_range.end.to_display_point(&display_map);
11982
11983            if !select_next_state.wordwise
11984                || (!movement::is_inside_word(&display_map, display_range.start)
11985                    && !movement::is_inside_word(&display_map, display_range.end))
11986            {
11987                new_selections.push(offset_range.start..offset_range.end);
11988            }
11989        }
11990
11991        select_next_state.done = true;
11992        self.unfold_ranges(&new_selections.clone(), false, false, cx);
11993        self.change_selections(None, window, cx, |selections| {
11994            selections.select_ranges(new_selections)
11995        });
11996
11997        Ok(())
11998    }
11999
12000    pub fn select_next(
12001        &mut self,
12002        action: &SelectNext,
12003        window: &mut Window,
12004        cx: &mut Context<Self>,
12005    ) -> Result<()> {
12006        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12007        self.push_to_selection_history();
12008        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12009        self.select_next_match_internal(
12010            &display_map,
12011            action.replace_newest,
12012            Some(Autoscroll::newest()),
12013            window,
12014            cx,
12015        )?;
12016        Ok(())
12017    }
12018
12019    pub fn select_previous(
12020        &mut self,
12021        action: &SelectPrevious,
12022        window: &mut Window,
12023        cx: &mut Context<Self>,
12024    ) -> Result<()> {
12025        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12026        self.push_to_selection_history();
12027        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12028        let buffer = &display_map.buffer_snapshot;
12029        let mut selections = self.selections.all::<usize>(cx);
12030        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12031            let query = &select_prev_state.query;
12032            if !select_prev_state.done {
12033                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12034                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12035                let mut next_selected_range = None;
12036                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12037                let bytes_before_last_selection =
12038                    buffer.reversed_bytes_in_range(0..last_selection.start);
12039                let bytes_after_first_selection =
12040                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12041                let query_matches = query
12042                    .stream_find_iter(bytes_before_last_selection)
12043                    .map(|result| (last_selection.start, result))
12044                    .chain(
12045                        query
12046                            .stream_find_iter(bytes_after_first_selection)
12047                            .map(|result| (buffer.len(), result)),
12048                    );
12049                for (end_offset, query_match) in query_matches {
12050                    let query_match = query_match.unwrap(); // can only fail due to I/O
12051                    let offset_range =
12052                        end_offset - query_match.end()..end_offset - query_match.start();
12053                    let display_range = offset_range.start.to_display_point(&display_map)
12054                        ..offset_range.end.to_display_point(&display_map);
12055
12056                    if !select_prev_state.wordwise
12057                        || (!movement::is_inside_word(&display_map, display_range.start)
12058                            && !movement::is_inside_word(&display_map, display_range.end))
12059                    {
12060                        next_selected_range = Some(offset_range);
12061                        break;
12062                    }
12063                }
12064
12065                if let Some(next_selected_range) = next_selected_range {
12066                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12067                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12068                        if action.replace_newest {
12069                            s.delete(s.newest_anchor().id);
12070                        }
12071                        s.insert_range(next_selected_range);
12072                    });
12073                } else {
12074                    select_prev_state.done = true;
12075                }
12076            }
12077
12078            self.select_prev_state = Some(select_prev_state);
12079        } else {
12080            let mut only_carets = true;
12081            let mut same_text_selected = true;
12082            let mut selected_text = None;
12083
12084            let mut selections_iter = selections.iter().peekable();
12085            while let Some(selection) = selections_iter.next() {
12086                if selection.start != selection.end {
12087                    only_carets = false;
12088                }
12089
12090                if same_text_selected {
12091                    if selected_text.is_none() {
12092                        selected_text =
12093                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12094                    }
12095
12096                    if let Some(next_selection) = selections_iter.peek() {
12097                        if next_selection.range().len() == selection.range().len() {
12098                            let next_selected_text = buffer
12099                                .text_for_range(next_selection.range())
12100                                .collect::<String>();
12101                            if Some(next_selected_text) != selected_text {
12102                                same_text_selected = false;
12103                                selected_text = None;
12104                            }
12105                        } else {
12106                            same_text_selected = false;
12107                            selected_text = None;
12108                        }
12109                    }
12110                }
12111            }
12112
12113            if only_carets {
12114                for selection in &mut selections {
12115                    let word_range = movement::surrounding_word(
12116                        &display_map,
12117                        selection.start.to_display_point(&display_map),
12118                    );
12119                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12120                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12121                    selection.goal = SelectionGoal::None;
12122                    selection.reversed = false;
12123                }
12124                if selections.len() == 1 {
12125                    let selection = selections
12126                        .last()
12127                        .expect("ensured that there's only one selection");
12128                    let query = buffer
12129                        .text_for_range(selection.start..selection.end)
12130                        .collect::<String>();
12131                    let is_empty = query.is_empty();
12132                    let select_state = SelectNextState {
12133                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12134                        wordwise: true,
12135                        done: is_empty,
12136                    };
12137                    self.select_prev_state = Some(select_state);
12138                } else {
12139                    self.select_prev_state = None;
12140                }
12141
12142                self.unfold_ranges(
12143                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12144                    false,
12145                    true,
12146                    cx,
12147                );
12148                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12149                    s.select(selections);
12150                });
12151            } else if let Some(selected_text) = selected_text {
12152                self.select_prev_state = Some(SelectNextState {
12153                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12154                    wordwise: false,
12155                    done: false,
12156                });
12157                self.select_previous(action, window, cx)?;
12158            }
12159        }
12160        Ok(())
12161    }
12162
12163    pub fn find_next_match(
12164        &mut self,
12165        _: &FindNextMatch,
12166        window: &mut Window,
12167        cx: &mut Context<Self>,
12168    ) -> Result<()> {
12169        let selections = self.selections.disjoint_anchors();
12170        match selections.first() {
12171            Some(first) if selections.len() >= 2 => {
12172                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12173                    s.select_ranges([first.range()]);
12174                });
12175            }
12176            _ => self.select_next(
12177                &SelectNext {
12178                    replace_newest: true,
12179                },
12180                window,
12181                cx,
12182            )?,
12183        }
12184        Ok(())
12185    }
12186
12187    pub fn find_previous_match(
12188        &mut self,
12189        _: &FindPreviousMatch,
12190        window: &mut Window,
12191        cx: &mut Context<Self>,
12192    ) -> Result<()> {
12193        let selections = self.selections.disjoint_anchors();
12194        match selections.last() {
12195            Some(last) if selections.len() >= 2 => {
12196                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12197                    s.select_ranges([last.range()]);
12198                });
12199            }
12200            _ => self.select_previous(
12201                &SelectPrevious {
12202                    replace_newest: true,
12203                },
12204                window,
12205                cx,
12206            )?,
12207        }
12208        Ok(())
12209    }
12210
12211    pub fn toggle_comments(
12212        &mut self,
12213        action: &ToggleComments,
12214        window: &mut Window,
12215        cx: &mut Context<Self>,
12216    ) {
12217        if self.read_only(cx) {
12218            return;
12219        }
12220        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12221        let text_layout_details = &self.text_layout_details(window);
12222        self.transact(window, cx, |this, window, cx| {
12223            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12224            let mut edits = Vec::new();
12225            let mut selection_edit_ranges = Vec::new();
12226            let mut last_toggled_row = None;
12227            let snapshot = this.buffer.read(cx).read(cx);
12228            let empty_str: Arc<str> = Arc::default();
12229            let mut suffixes_inserted = Vec::new();
12230            let ignore_indent = action.ignore_indent;
12231
12232            fn comment_prefix_range(
12233                snapshot: &MultiBufferSnapshot,
12234                row: MultiBufferRow,
12235                comment_prefix: &str,
12236                comment_prefix_whitespace: &str,
12237                ignore_indent: bool,
12238            ) -> Range<Point> {
12239                let indent_size = if ignore_indent {
12240                    0
12241                } else {
12242                    snapshot.indent_size_for_line(row).len
12243                };
12244
12245                let start = Point::new(row.0, indent_size);
12246
12247                let mut line_bytes = snapshot
12248                    .bytes_in_range(start..snapshot.max_point())
12249                    .flatten()
12250                    .copied();
12251
12252                // If this line currently begins with the line comment prefix, then record
12253                // the range containing the prefix.
12254                if line_bytes
12255                    .by_ref()
12256                    .take(comment_prefix.len())
12257                    .eq(comment_prefix.bytes())
12258                {
12259                    // Include any whitespace that matches the comment prefix.
12260                    let matching_whitespace_len = line_bytes
12261                        .zip(comment_prefix_whitespace.bytes())
12262                        .take_while(|(a, b)| a == b)
12263                        .count() as u32;
12264                    let end = Point::new(
12265                        start.row,
12266                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12267                    );
12268                    start..end
12269                } else {
12270                    start..start
12271                }
12272            }
12273
12274            fn comment_suffix_range(
12275                snapshot: &MultiBufferSnapshot,
12276                row: MultiBufferRow,
12277                comment_suffix: &str,
12278                comment_suffix_has_leading_space: bool,
12279            ) -> Range<Point> {
12280                let end = Point::new(row.0, snapshot.line_len(row));
12281                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12282
12283                let mut line_end_bytes = snapshot
12284                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12285                    .flatten()
12286                    .copied();
12287
12288                let leading_space_len = if suffix_start_column > 0
12289                    && line_end_bytes.next() == Some(b' ')
12290                    && comment_suffix_has_leading_space
12291                {
12292                    1
12293                } else {
12294                    0
12295                };
12296
12297                // If this line currently begins with the line comment prefix, then record
12298                // the range containing the prefix.
12299                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12300                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12301                    start..end
12302                } else {
12303                    end..end
12304                }
12305            }
12306
12307            // TODO: Handle selections that cross excerpts
12308            for selection in &mut selections {
12309                let start_column = snapshot
12310                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12311                    .len;
12312                let language = if let Some(language) =
12313                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12314                {
12315                    language
12316                } else {
12317                    continue;
12318                };
12319
12320                selection_edit_ranges.clear();
12321
12322                // If multiple selections contain a given row, avoid processing that
12323                // row more than once.
12324                let mut start_row = MultiBufferRow(selection.start.row);
12325                if last_toggled_row == Some(start_row) {
12326                    start_row = start_row.next_row();
12327                }
12328                let end_row =
12329                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12330                        MultiBufferRow(selection.end.row - 1)
12331                    } else {
12332                        MultiBufferRow(selection.end.row)
12333                    };
12334                last_toggled_row = Some(end_row);
12335
12336                if start_row > end_row {
12337                    continue;
12338                }
12339
12340                // If the language has line comments, toggle those.
12341                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12342
12343                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12344                if ignore_indent {
12345                    full_comment_prefixes = full_comment_prefixes
12346                        .into_iter()
12347                        .map(|s| Arc::from(s.trim_end()))
12348                        .collect();
12349                }
12350
12351                if !full_comment_prefixes.is_empty() {
12352                    let first_prefix = full_comment_prefixes
12353                        .first()
12354                        .expect("prefixes is non-empty");
12355                    let prefix_trimmed_lengths = full_comment_prefixes
12356                        .iter()
12357                        .map(|p| p.trim_end_matches(' ').len())
12358                        .collect::<SmallVec<[usize; 4]>>();
12359
12360                    let mut all_selection_lines_are_comments = true;
12361
12362                    for row in start_row.0..=end_row.0 {
12363                        let row = MultiBufferRow(row);
12364                        if start_row < end_row && snapshot.is_line_blank(row) {
12365                            continue;
12366                        }
12367
12368                        let prefix_range = full_comment_prefixes
12369                            .iter()
12370                            .zip(prefix_trimmed_lengths.iter().copied())
12371                            .map(|(prefix, trimmed_prefix_len)| {
12372                                comment_prefix_range(
12373                                    snapshot.deref(),
12374                                    row,
12375                                    &prefix[..trimmed_prefix_len],
12376                                    &prefix[trimmed_prefix_len..],
12377                                    ignore_indent,
12378                                )
12379                            })
12380                            .max_by_key(|range| range.end.column - range.start.column)
12381                            .expect("prefixes is non-empty");
12382
12383                        if prefix_range.is_empty() {
12384                            all_selection_lines_are_comments = false;
12385                        }
12386
12387                        selection_edit_ranges.push(prefix_range);
12388                    }
12389
12390                    if all_selection_lines_are_comments {
12391                        edits.extend(
12392                            selection_edit_ranges
12393                                .iter()
12394                                .cloned()
12395                                .map(|range| (range, empty_str.clone())),
12396                        );
12397                    } else {
12398                        let min_column = selection_edit_ranges
12399                            .iter()
12400                            .map(|range| range.start.column)
12401                            .min()
12402                            .unwrap_or(0);
12403                        edits.extend(selection_edit_ranges.iter().map(|range| {
12404                            let position = Point::new(range.start.row, min_column);
12405                            (position..position, first_prefix.clone())
12406                        }));
12407                    }
12408                } else if let Some((full_comment_prefix, comment_suffix)) =
12409                    language.block_comment_delimiters()
12410                {
12411                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12412                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12413                    let prefix_range = comment_prefix_range(
12414                        snapshot.deref(),
12415                        start_row,
12416                        comment_prefix,
12417                        comment_prefix_whitespace,
12418                        ignore_indent,
12419                    );
12420                    let suffix_range = comment_suffix_range(
12421                        snapshot.deref(),
12422                        end_row,
12423                        comment_suffix.trim_start_matches(' '),
12424                        comment_suffix.starts_with(' '),
12425                    );
12426
12427                    if prefix_range.is_empty() || suffix_range.is_empty() {
12428                        edits.push((
12429                            prefix_range.start..prefix_range.start,
12430                            full_comment_prefix.clone(),
12431                        ));
12432                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12433                        suffixes_inserted.push((end_row, comment_suffix.len()));
12434                    } else {
12435                        edits.push((prefix_range, empty_str.clone()));
12436                        edits.push((suffix_range, empty_str.clone()));
12437                    }
12438                } else {
12439                    continue;
12440                }
12441            }
12442
12443            drop(snapshot);
12444            this.buffer.update(cx, |buffer, cx| {
12445                buffer.edit(edits, None, cx);
12446            });
12447
12448            // Adjust selections so that they end before any comment suffixes that
12449            // were inserted.
12450            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12451            let mut selections = this.selections.all::<Point>(cx);
12452            let snapshot = this.buffer.read(cx).read(cx);
12453            for selection in &mut selections {
12454                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12455                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12456                        Ordering::Less => {
12457                            suffixes_inserted.next();
12458                            continue;
12459                        }
12460                        Ordering::Greater => break,
12461                        Ordering::Equal => {
12462                            if selection.end.column == snapshot.line_len(row) {
12463                                if selection.is_empty() {
12464                                    selection.start.column -= suffix_len as u32;
12465                                }
12466                                selection.end.column -= suffix_len as u32;
12467                            }
12468                            break;
12469                        }
12470                    }
12471                }
12472            }
12473
12474            drop(snapshot);
12475            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12476                s.select(selections)
12477            });
12478
12479            let selections = this.selections.all::<Point>(cx);
12480            let selections_on_single_row = selections.windows(2).all(|selections| {
12481                selections[0].start.row == selections[1].start.row
12482                    && selections[0].end.row == selections[1].end.row
12483                    && selections[0].start.row == selections[0].end.row
12484            });
12485            let selections_selecting = selections
12486                .iter()
12487                .any(|selection| selection.start != selection.end);
12488            let advance_downwards = action.advance_downwards
12489                && selections_on_single_row
12490                && !selections_selecting
12491                && !matches!(this.mode, EditorMode::SingleLine { .. });
12492
12493            if advance_downwards {
12494                let snapshot = this.buffer.read(cx).snapshot(cx);
12495
12496                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12497                    s.move_cursors_with(|display_snapshot, display_point, _| {
12498                        let mut point = display_point.to_point(display_snapshot);
12499                        point.row += 1;
12500                        point = snapshot.clip_point(point, Bias::Left);
12501                        let display_point = point.to_display_point(display_snapshot);
12502                        let goal = SelectionGoal::HorizontalPosition(
12503                            display_snapshot
12504                                .x_for_display_point(display_point, text_layout_details)
12505                                .into(),
12506                        );
12507                        (display_point, goal)
12508                    })
12509                });
12510            }
12511        });
12512    }
12513
12514    pub fn select_enclosing_symbol(
12515        &mut self,
12516        _: &SelectEnclosingSymbol,
12517        window: &mut Window,
12518        cx: &mut Context<Self>,
12519    ) {
12520        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12521
12522        let buffer = self.buffer.read(cx).snapshot(cx);
12523        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12524
12525        fn update_selection(
12526            selection: &Selection<usize>,
12527            buffer_snap: &MultiBufferSnapshot,
12528        ) -> Option<Selection<usize>> {
12529            let cursor = selection.head();
12530            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12531            for symbol in symbols.iter().rev() {
12532                let start = symbol.range.start.to_offset(buffer_snap);
12533                let end = symbol.range.end.to_offset(buffer_snap);
12534                let new_range = start..end;
12535                if start < selection.start || end > selection.end {
12536                    return Some(Selection {
12537                        id: selection.id,
12538                        start: new_range.start,
12539                        end: new_range.end,
12540                        goal: SelectionGoal::None,
12541                        reversed: selection.reversed,
12542                    });
12543                }
12544            }
12545            None
12546        }
12547
12548        let mut selected_larger_symbol = false;
12549        let new_selections = old_selections
12550            .iter()
12551            .map(|selection| match update_selection(selection, &buffer) {
12552                Some(new_selection) => {
12553                    if new_selection.range() != selection.range() {
12554                        selected_larger_symbol = true;
12555                    }
12556                    new_selection
12557                }
12558                None => selection.clone(),
12559            })
12560            .collect::<Vec<_>>();
12561
12562        if selected_larger_symbol {
12563            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12564                s.select(new_selections);
12565            });
12566        }
12567    }
12568
12569    pub fn select_larger_syntax_node(
12570        &mut self,
12571        _: &SelectLargerSyntaxNode,
12572        window: &mut Window,
12573        cx: &mut Context<Self>,
12574    ) {
12575        let Some(visible_row_count) = self.visible_row_count() else {
12576            return;
12577        };
12578        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12579        if old_selections.is_empty() {
12580            return;
12581        }
12582
12583        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12584
12585        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12586        let buffer = self.buffer.read(cx).snapshot(cx);
12587
12588        let mut selected_larger_node = false;
12589        let mut new_selections = old_selections
12590            .iter()
12591            .map(|selection| {
12592                let old_range = selection.start..selection.end;
12593
12594                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12595                    // manually select word at selection
12596                    if ["string_content", "inline"].contains(&node.kind()) {
12597                        let word_range = {
12598                            let display_point = buffer
12599                                .offset_to_point(old_range.start)
12600                                .to_display_point(&display_map);
12601                            let Range { start, end } =
12602                                movement::surrounding_word(&display_map, display_point);
12603                            start.to_point(&display_map).to_offset(&buffer)
12604                                ..end.to_point(&display_map).to_offset(&buffer)
12605                        };
12606                        // ignore if word is already selected
12607                        if !word_range.is_empty() && old_range != word_range {
12608                            let last_word_range = {
12609                                let display_point = buffer
12610                                    .offset_to_point(old_range.end)
12611                                    .to_display_point(&display_map);
12612                                let Range { start, end } =
12613                                    movement::surrounding_word(&display_map, display_point);
12614                                start.to_point(&display_map).to_offset(&buffer)
12615                                    ..end.to_point(&display_map).to_offset(&buffer)
12616                            };
12617                            // only select word if start and end point belongs to same word
12618                            if word_range == last_word_range {
12619                                selected_larger_node = true;
12620                                return Selection {
12621                                    id: selection.id,
12622                                    start: word_range.start,
12623                                    end: word_range.end,
12624                                    goal: SelectionGoal::None,
12625                                    reversed: selection.reversed,
12626                                };
12627                            }
12628                        }
12629                    }
12630                }
12631
12632                let mut new_range = old_range.clone();
12633                let mut new_node = None;
12634                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12635                {
12636                    new_node = Some(node);
12637                    new_range = match containing_range {
12638                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12639                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12640                    };
12641                    if !display_map.intersects_fold(new_range.start)
12642                        && !display_map.intersects_fold(new_range.end)
12643                    {
12644                        break;
12645                    }
12646                }
12647
12648                if let Some(node) = new_node {
12649                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12650                    // nodes. Parent and grandparent are also logged because this operation will not
12651                    // visit nodes that have the same range as their parent.
12652                    log::info!("Node: {node:?}");
12653                    let parent = node.parent();
12654                    log::info!("Parent: {parent:?}");
12655                    let grandparent = parent.and_then(|x| x.parent());
12656                    log::info!("Grandparent: {grandparent:?}");
12657                }
12658
12659                selected_larger_node |= new_range != old_range;
12660                Selection {
12661                    id: selection.id,
12662                    start: new_range.start,
12663                    end: new_range.end,
12664                    goal: SelectionGoal::None,
12665                    reversed: selection.reversed,
12666                }
12667            })
12668            .collect::<Vec<_>>();
12669
12670        if !selected_larger_node {
12671            return; // don't put this call in the history
12672        }
12673
12674        // scroll based on transformation done to the last selection created by the user
12675        let (last_old, last_new) = old_selections
12676            .last()
12677            .zip(new_selections.last().cloned())
12678            .expect("old_selections isn't empty");
12679
12680        // revert selection
12681        let is_selection_reversed = {
12682            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12683            new_selections.last_mut().expect("checked above").reversed =
12684                should_newest_selection_be_reversed;
12685            should_newest_selection_be_reversed
12686        };
12687
12688        if selected_larger_node {
12689            self.select_syntax_node_history.disable_clearing = true;
12690            self.change_selections(None, window, cx, |s| {
12691                s.select(new_selections.clone());
12692            });
12693            self.select_syntax_node_history.disable_clearing = false;
12694        }
12695
12696        let start_row = last_new.start.to_display_point(&display_map).row().0;
12697        let end_row = last_new.end.to_display_point(&display_map).row().0;
12698        let selection_height = end_row - start_row + 1;
12699        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12700
12701        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12702        let scroll_behavior = if fits_on_the_screen {
12703            self.request_autoscroll(Autoscroll::fit(), cx);
12704            SelectSyntaxNodeScrollBehavior::FitSelection
12705        } else if is_selection_reversed {
12706            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12707            SelectSyntaxNodeScrollBehavior::CursorTop
12708        } else {
12709            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12710            SelectSyntaxNodeScrollBehavior::CursorBottom
12711        };
12712
12713        self.select_syntax_node_history.push((
12714            old_selections,
12715            scroll_behavior,
12716            is_selection_reversed,
12717        ));
12718    }
12719
12720    pub fn select_smaller_syntax_node(
12721        &mut self,
12722        _: &SelectSmallerSyntaxNode,
12723        window: &mut Window,
12724        cx: &mut Context<Self>,
12725    ) {
12726        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12727
12728        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12729            self.select_syntax_node_history.pop()
12730        {
12731            if let Some(selection) = selections.last_mut() {
12732                selection.reversed = is_selection_reversed;
12733            }
12734
12735            self.select_syntax_node_history.disable_clearing = true;
12736            self.change_selections(None, window, cx, |s| {
12737                s.select(selections.to_vec());
12738            });
12739            self.select_syntax_node_history.disable_clearing = false;
12740
12741            match scroll_behavior {
12742                SelectSyntaxNodeScrollBehavior::CursorTop => {
12743                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12744                }
12745                SelectSyntaxNodeScrollBehavior::FitSelection => {
12746                    self.request_autoscroll(Autoscroll::fit(), cx);
12747                }
12748                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12749                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12750                }
12751            }
12752        }
12753    }
12754
12755    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12756        if !EditorSettings::get_global(cx).gutter.runnables {
12757            self.clear_tasks();
12758            return Task::ready(());
12759        }
12760        let project = self.project.as_ref().map(Entity::downgrade);
12761        let task_sources = self.lsp_task_sources(cx);
12762        cx.spawn_in(window, async move |editor, cx| {
12763            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12764            let Some(project) = project.and_then(|p| p.upgrade()) else {
12765                return;
12766            };
12767            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12768                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12769            }) else {
12770                return;
12771            };
12772
12773            let hide_runnables = project
12774                .update(cx, |project, cx| {
12775                    // Do not display any test indicators in non-dev server remote projects.
12776                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12777                })
12778                .unwrap_or(true);
12779            if hide_runnables {
12780                return;
12781            }
12782            let new_rows =
12783                cx.background_spawn({
12784                    let snapshot = display_snapshot.clone();
12785                    async move {
12786                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12787                    }
12788                })
12789                    .await;
12790            let Ok(lsp_tasks) =
12791                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12792            else {
12793                return;
12794            };
12795            let lsp_tasks = lsp_tasks.await;
12796
12797            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12798                lsp_tasks
12799                    .into_iter()
12800                    .flat_map(|(kind, tasks)| {
12801                        tasks.into_iter().filter_map(move |(location, task)| {
12802                            Some((kind.clone(), location?, task))
12803                        })
12804                    })
12805                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12806                        let buffer = location.target.buffer;
12807                        let buffer_snapshot = buffer.read(cx).snapshot();
12808                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12809                            |(excerpt_id, snapshot, _)| {
12810                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
12811                                    display_snapshot
12812                                        .buffer_snapshot
12813                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
12814                                } else {
12815                                    None
12816                                }
12817                            },
12818                        );
12819                        if let Some(offset) = offset {
12820                            let task_buffer_range =
12821                                location.target.range.to_point(&buffer_snapshot);
12822                            let context_buffer_range =
12823                                task_buffer_range.to_offset(&buffer_snapshot);
12824                            let context_range = BufferOffset(context_buffer_range.start)
12825                                ..BufferOffset(context_buffer_range.end);
12826
12827                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12828                                .or_insert_with(|| RunnableTasks {
12829                                    templates: Vec::new(),
12830                                    offset,
12831                                    column: task_buffer_range.start.column,
12832                                    extra_variables: HashMap::default(),
12833                                    context_range,
12834                                })
12835                                .templates
12836                                .push((kind, task.original_task().clone()));
12837                        }
12838
12839                        acc
12840                    })
12841            }) else {
12842                return;
12843            };
12844
12845            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12846            editor
12847                .update(cx, |editor, _| {
12848                    editor.clear_tasks();
12849                    for (key, mut value) in rows {
12850                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12851                            value.templates.extend(lsp_tasks.templates);
12852                        }
12853
12854                        editor.insert_tasks(key, value);
12855                    }
12856                    for (key, value) in lsp_tasks_by_rows {
12857                        editor.insert_tasks(key, value);
12858                    }
12859                })
12860                .ok();
12861        })
12862    }
12863    fn fetch_runnable_ranges(
12864        snapshot: &DisplaySnapshot,
12865        range: Range<Anchor>,
12866    ) -> Vec<language::RunnableRange> {
12867        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12868    }
12869
12870    fn runnable_rows(
12871        project: Entity<Project>,
12872        snapshot: DisplaySnapshot,
12873        runnable_ranges: Vec<RunnableRange>,
12874        mut cx: AsyncWindowContext,
12875    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12876        runnable_ranges
12877            .into_iter()
12878            .filter_map(|mut runnable| {
12879                let tasks = cx
12880                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12881                    .ok()?;
12882                if tasks.is_empty() {
12883                    return None;
12884                }
12885
12886                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12887
12888                let row = snapshot
12889                    .buffer_snapshot
12890                    .buffer_line_for_row(MultiBufferRow(point.row))?
12891                    .1
12892                    .start
12893                    .row;
12894
12895                let context_range =
12896                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12897                Some((
12898                    (runnable.buffer_id, row),
12899                    RunnableTasks {
12900                        templates: tasks,
12901                        offset: snapshot
12902                            .buffer_snapshot
12903                            .anchor_before(runnable.run_range.start),
12904                        context_range,
12905                        column: point.column,
12906                        extra_variables: runnable.extra_captures,
12907                    },
12908                ))
12909            })
12910            .collect()
12911    }
12912
12913    fn templates_with_tags(
12914        project: &Entity<Project>,
12915        runnable: &mut Runnable,
12916        cx: &mut App,
12917    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12918        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12919            let (worktree_id, file) = project
12920                .buffer_for_id(runnable.buffer, cx)
12921                .and_then(|buffer| buffer.read(cx).file())
12922                .map(|file| (file.worktree_id(cx), file.clone()))
12923                .unzip();
12924
12925            (
12926                project.task_store().read(cx).task_inventory().cloned(),
12927                worktree_id,
12928                file,
12929            )
12930        });
12931
12932        let mut templates_with_tags = mem::take(&mut runnable.tags)
12933            .into_iter()
12934            .flat_map(|RunnableTag(tag)| {
12935                inventory
12936                    .as_ref()
12937                    .into_iter()
12938                    .flat_map(|inventory| {
12939                        inventory.read(cx).list_tasks(
12940                            file.clone(),
12941                            Some(runnable.language.clone()),
12942                            worktree_id,
12943                            cx,
12944                        )
12945                    })
12946                    .filter(move |(_, template)| {
12947                        template.tags.iter().any(|source_tag| source_tag == &tag)
12948                    })
12949            })
12950            .sorted_by_key(|(kind, _)| kind.to_owned())
12951            .collect::<Vec<_>>();
12952        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12953            // Strongest source wins; if we have worktree tag binding, prefer that to
12954            // global and language bindings;
12955            // if we have a global binding, prefer that to language binding.
12956            let first_mismatch = templates_with_tags
12957                .iter()
12958                .position(|(tag_source, _)| tag_source != leading_tag_source);
12959            if let Some(index) = first_mismatch {
12960                templates_with_tags.truncate(index);
12961            }
12962        }
12963
12964        templates_with_tags
12965    }
12966
12967    pub fn move_to_enclosing_bracket(
12968        &mut self,
12969        _: &MoveToEnclosingBracket,
12970        window: &mut Window,
12971        cx: &mut Context<Self>,
12972    ) {
12973        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12974        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12975            s.move_offsets_with(|snapshot, selection| {
12976                let Some(enclosing_bracket_ranges) =
12977                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12978                else {
12979                    return;
12980                };
12981
12982                let mut best_length = usize::MAX;
12983                let mut best_inside = false;
12984                let mut best_in_bracket_range = false;
12985                let mut best_destination = None;
12986                for (open, close) in enclosing_bracket_ranges {
12987                    let close = close.to_inclusive();
12988                    let length = close.end() - open.start;
12989                    let inside = selection.start >= open.end && selection.end <= *close.start();
12990                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12991                        || close.contains(&selection.head());
12992
12993                    // If best is next to a bracket and current isn't, skip
12994                    if !in_bracket_range && best_in_bracket_range {
12995                        continue;
12996                    }
12997
12998                    // Prefer smaller lengths unless best is inside and current isn't
12999                    if length > best_length && (best_inside || !inside) {
13000                        continue;
13001                    }
13002
13003                    best_length = length;
13004                    best_inside = inside;
13005                    best_in_bracket_range = in_bracket_range;
13006                    best_destination = Some(
13007                        if close.contains(&selection.start) && close.contains(&selection.end) {
13008                            if inside { open.end } else { open.start }
13009                        } else if inside {
13010                            *close.start()
13011                        } else {
13012                            *close.end()
13013                        },
13014                    );
13015                }
13016
13017                if let Some(destination) = best_destination {
13018                    selection.collapse_to(destination, SelectionGoal::None);
13019                }
13020            })
13021        });
13022    }
13023
13024    pub fn undo_selection(
13025        &mut self,
13026        _: &UndoSelection,
13027        window: &mut Window,
13028        cx: &mut Context<Self>,
13029    ) {
13030        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13031        self.end_selection(window, cx);
13032        self.selection_history.mode = SelectionHistoryMode::Undoing;
13033        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13034            self.change_selections(None, window, cx, |s| {
13035                s.select_anchors(entry.selections.to_vec())
13036            });
13037            self.select_next_state = entry.select_next_state;
13038            self.select_prev_state = entry.select_prev_state;
13039            self.add_selections_state = entry.add_selections_state;
13040            self.request_autoscroll(Autoscroll::newest(), cx);
13041        }
13042        self.selection_history.mode = SelectionHistoryMode::Normal;
13043    }
13044
13045    pub fn redo_selection(
13046        &mut self,
13047        _: &RedoSelection,
13048        window: &mut Window,
13049        cx: &mut Context<Self>,
13050    ) {
13051        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13052        self.end_selection(window, cx);
13053        self.selection_history.mode = SelectionHistoryMode::Redoing;
13054        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13055            self.change_selections(None, window, cx, |s| {
13056                s.select_anchors(entry.selections.to_vec())
13057            });
13058            self.select_next_state = entry.select_next_state;
13059            self.select_prev_state = entry.select_prev_state;
13060            self.add_selections_state = entry.add_selections_state;
13061            self.request_autoscroll(Autoscroll::newest(), cx);
13062        }
13063        self.selection_history.mode = SelectionHistoryMode::Normal;
13064    }
13065
13066    pub fn expand_excerpts(
13067        &mut self,
13068        action: &ExpandExcerpts,
13069        _: &mut Window,
13070        cx: &mut Context<Self>,
13071    ) {
13072        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13073    }
13074
13075    pub fn expand_excerpts_down(
13076        &mut self,
13077        action: &ExpandExcerptsDown,
13078        _: &mut Window,
13079        cx: &mut Context<Self>,
13080    ) {
13081        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13082    }
13083
13084    pub fn expand_excerpts_up(
13085        &mut self,
13086        action: &ExpandExcerptsUp,
13087        _: &mut Window,
13088        cx: &mut Context<Self>,
13089    ) {
13090        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13091    }
13092
13093    pub fn expand_excerpts_for_direction(
13094        &mut self,
13095        lines: u32,
13096        direction: ExpandExcerptDirection,
13097
13098        cx: &mut Context<Self>,
13099    ) {
13100        let selections = self.selections.disjoint_anchors();
13101
13102        let lines = if lines == 0 {
13103            EditorSettings::get_global(cx).expand_excerpt_lines
13104        } else {
13105            lines
13106        };
13107
13108        self.buffer.update(cx, |buffer, cx| {
13109            let snapshot = buffer.snapshot(cx);
13110            let mut excerpt_ids = selections
13111                .iter()
13112                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13113                .collect::<Vec<_>>();
13114            excerpt_ids.sort();
13115            excerpt_ids.dedup();
13116            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13117        })
13118    }
13119
13120    pub fn expand_excerpt(
13121        &mut self,
13122        excerpt: ExcerptId,
13123        direction: ExpandExcerptDirection,
13124        window: &mut Window,
13125        cx: &mut Context<Self>,
13126    ) {
13127        let current_scroll_position = self.scroll_position(cx);
13128        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13129        let mut should_scroll_up = false;
13130
13131        if direction == ExpandExcerptDirection::Down {
13132            let multi_buffer = self.buffer.read(cx);
13133            let snapshot = multi_buffer.snapshot(cx);
13134            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13135                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13136                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13137                        let buffer_snapshot = buffer.read(cx).snapshot();
13138                        let excerpt_end_row =
13139                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13140                        let last_row = buffer_snapshot.max_point().row;
13141                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13142                        should_scroll_up = lines_below >= lines_to_expand;
13143                    }
13144                }
13145            }
13146        }
13147
13148        self.buffer.update(cx, |buffer, cx| {
13149            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13150        });
13151
13152        if should_scroll_up {
13153            let new_scroll_position =
13154                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13155            self.set_scroll_position(new_scroll_position, window, cx);
13156        }
13157    }
13158
13159    pub fn go_to_singleton_buffer_point(
13160        &mut self,
13161        point: Point,
13162        window: &mut Window,
13163        cx: &mut Context<Self>,
13164    ) {
13165        self.go_to_singleton_buffer_range(point..point, window, cx);
13166    }
13167
13168    pub fn go_to_singleton_buffer_range(
13169        &mut self,
13170        range: Range<Point>,
13171        window: &mut Window,
13172        cx: &mut Context<Self>,
13173    ) {
13174        let multibuffer = self.buffer().read(cx);
13175        let Some(buffer) = multibuffer.as_singleton() else {
13176            return;
13177        };
13178        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13179            return;
13180        };
13181        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13182            return;
13183        };
13184        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13185            s.select_anchor_ranges([start..end])
13186        });
13187    }
13188
13189    pub fn go_to_diagnostic(
13190        &mut self,
13191        _: &GoToDiagnostic,
13192        window: &mut Window,
13193        cx: &mut Context<Self>,
13194    ) {
13195        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13196        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13197    }
13198
13199    pub fn go_to_prev_diagnostic(
13200        &mut self,
13201        _: &GoToPreviousDiagnostic,
13202        window: &mut Window,
13203        cx: &mut Context<Self>,
13204    ) {
13205        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13206        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13207    }
13208
13209    pub fn go_to_diagnostic_impl(
13210        &mut self,
13211        direction: Direction,
13212        window: &mut Window,
13213        cx: &mut Context<Self>,
13214    ) {
13215        let buffer = self.buffer.read(cx).snapshot(cx);
13216        let selection = self.selections.newest::<usize>(cx);
13217
13218        let mut active_group_id = None;
13219        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13220            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13221                active_group_id = Some(active_group.group_id);
13222            }
13223        }
13224
13225        fn filtered(
13226            snapshot: EditorSnapshot,
13227            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13228        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13229            diagnostics
13230                .filter(|entry| entry.range.start != entry.range.end)
13231                .filter(|entry| !entry.diagnostic.is_unnecessary)
13232                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13233        }
13234
13235        let snapshot = self.snapshot(window, cx);
13236        let before = filtered(
13237            snapshot.clone(),
13238            buffer
13239                .diagnostics_in_range(0..selection.start)
13240                .filter(|entry| entry.range.start <= selection.start),
13241        );
13242        let after = filtered(
13243            snapshot,
13244            buffer
13245                .diagnostics_in_range(selection.start..buffer.len())
13246                .filter(|entry| entry.range.start >= selection.start),
13247        );
13248
13249        let mut found: Option<DiagnosticEntry<usize>> = None;
13250        if direction == Direction::Prev {
13251            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13252            {
13253                for diagnostic in prev_diagnostics.into_iter().rev() {
13254                    if diagnostic.range.start != selection.start
13255                        || active_group_id
13256                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13257                    {
13258                        found = Some(diagnostic);
13259                        break 'outer;
13260                    }
13261                }
13262            }
13263        } else {
13264            for diagnostic in after.chain(before) {
13265                if diagnostic.range.start != selection.start
13266                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13267                {
13268                    found = Some(diagnostic);
13269                    break;
13270                }
13271            }
13272        }
13273        let Some(next_diagnostic) = found else {
13274            return;
13275        };
13276
13277        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13278            return;
13279        };
13280        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13281            s.select_ranges(vec![
13282                next_diagnostic.range.start..next_diagnostic.range.start,
13283            ])
13284        });
13285        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13286        self.refresh_inline_completion(false, true, window, cx);
13287    }
13288
13289    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13290        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13291        let snapshot = self.snapshot(window, cx);
13292        let selection = self.selections.newest::<Point>(cx);
13293        self.go_to_hunk_before_or_after_position(
13294            &snapshot,
13295            selection.head(),
13296            Direction::Next,
13297            window,
13298            cx,
13299        );
13300    }
13301
13302    pub fn go_to_hunk_before_or_after_position(
13303        &mut self,
13304        snapshot: &EditorSnapshot,
13305        position: Point,
13306        direction: Direction,
13307        window: &mut Window,
13308        cx: &mut Context<Editor>,
13309    ) {
13310        let row = if direction == Direction::Next {
13311            self.hunk_after_position(snapshot, position)
13312                .map(|hunk| hunk.row_range.start)
13313        } else {
13314            self.hunk_before_position(snapshot, position)
13315        };
13316
13317        if let Some(row) = row {
13318            let destination = Point::new(row.0, 0);
13319            let autoscroll = Autoscroll::center();
13320
13321            self.unfold_ranges(&[destination..destination], false, false, cx);
13322            self.change_selections(Some(autoscroll), window, cx, |s| {
13323                s.select_ranges([destination..destination]);
13324            });
13325        }
13326    }
13327
13328    fn hunk_after_position(
13329        &mut self,
13330        snapshot: &EditorSnapshot,
13331        position: Point,
13332    ) -> Option<MultiBufferDiffHunk> {
13333        snapshot
13334            .buffer_snapshot
13335            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13336            .find(|hunk| hunk.row_range.start.0 > position.row)
13337            .or_else(|| {
13338                snapshot
13339                    .buffer_snapshot
13340                    .diff_hunks_in_range(Point::zero()..position)
13341                    .find(|hunk| hunk.row_range.end.0 < position.row)
13342            })
13343    }
13344
13345    fn go_to_prev_hunk(
13346        &mut self,
13347        _: &GoToPreviousHunk,
13348        window: &mut Window,
13349        cx: &mut Context<Self>,
13350    ) {
13351        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13352        let snapshot = self.snapshot(window, cx);
13353        let selection = self.selections.newest::<Point>(cx);
13354        self.go_to_hunk_before_or_after_position(
13355            &snapshot,
13356            selection.head(),
13357            Direction::Prev,
13358            window,
13359            cx,
13360        );
13361    }
13362
13363    fn hunk_before_position(
13364        &mut self,
13365        snapshot: &EditorSnapshot,
13366        position: Point,
13367    ) -> Option<MultiBufferRow> {
13368        snapshot
13369            .buffer_snapshot
13370            .diff_hunk_before(position)
13371            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13372    }
13373
13374    fn go_to_line<T: 'static>(
13375        &mut self,
13376        position: Anchor,
13377        highlight_color: Option<Hsla>,
13378        window: &mut Window,
13379        cx: &mut Context<Self>,
13380    ) {
13381        let snapshot = self.snapshot(window, cx).display_snapshot;
13382        let position = position.to_point(&snapshot.buffer_snapshot);
13383        let start = snapshot
13384            .buffer_snapshot
13385            .clip_point(Point::new(position.row, 0), Bias::Left);
13386        let end = start + Point::new(1, 0);
13387        let start = snapshot.buffer_snapshot.anchor_before(start);
13388        let end = snapshot.buffer_snapshot.anchor_before(end);
13389
13390        self.highlight_rows::<T>(
13391            start..end,
13392            highlight_color
13393                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13394            false,
13395            cx,
13396        );
13397        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13398    }
13399
13400    pub fn go_to_definition(
13401        &mut self,
13402        _: &GoToDefinition,
13403        window: &mut Window,
13404        cx: &mut Context<Self>,
13405    ) -> Task<Result<Navigated>> {
13406        let definition =
13407            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13408        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13409        cx.spawn_in(window, async move |editor, cx| {
13410            if definition.await? == Navigated::Yes {
13411                return Ok(Navigated::Yes);
13412            }
13413            match fallback_strategy {
13414                GoToDefinitionFallback::None => Ok(Navigated::No),
13415                GoToDefinitionFallback::FindAllReferences => {
13416                    match editor.update_in(cx, |editor, window, cx| {
13417                        editor.find_all_references(&FindAllReferences, window, cx)
13418                    })? {
13419                        Some(references) => references.await,
13420                        None => Ok(Navigated::No),
13421                    }
13422                }
13423            }
13424        })
13425    }
13426
13427    pub fn go_to_declaration(
13428        &mut self,
13429        _: &GoToDeclaration,
13430        window: &mut Window,
13431        cx: &mut Context<Self>,
13432    ) -> Task<Result<Navigated>> {
13433        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13434    }
13435
13436    pub fn go_to_declaration_split(
13437        &mut self,
13438        _: &GoToDeclaration,
13439        window: &mut Window,
13440        cx: &mut Context<Self>,
13441    ) -> Task<Result<Navigated>> {
13442        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13443    }
13444
13445    pub fn go_to_implementation(
13446        &mut self,
13447        _: &GoToImplementation,
13448        window: &mut Window,
13449        cx: &mut Context<Self>,
13450    ) -> Task<Result<Navigated>> {
13451        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13452    }
13453
13454    pub fn go_to_implementation_split(
13455        &mut self,
13456        _: &GoToImplementationSplit,
13457        window: &mut Window,
13458        cx: &mut Context<Self>,
13459    ) -> Task<Result<Navigated>> {
13460        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13461    }
13462
13463    pub fn go_to_type_definition(
13464        &mut self,
13465        _: &GoToTypeDefinition,
13466        window: &mut Window,
13467        cx: &mut Context<Self>,
13468    ) -> Task<Result<Navigated>> {
13469        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13470    }
13471
13472    pub fn go_to_definition_split(
13473        &mut self,
13474        _: &GoToDefinitionSplit,
13475        window: &mut Window,
13476        cx: &mut Context<Self>,
13477    ) -> Task<Result<Navigated>> {
13478        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13479    }
13480
13481    pub fn go_to_type_definition_split(
13482        &mut self,
13483        _: &GoToTypeDefinitionSplit,
13484        window: &mut Window,
13485        cx: &mut Context<Self>,
13486    ) -> Task<Result<Navigated>> {
13487        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13488    }
13489
13490    fn go_to_definition_of_kind(
13491        &mut self,
13492        kind: GotoDefinitionKind,
13493        split: bool,
13494        window: &mut Window,
13495        cx: &mut Context<Self>,
13496    ) -> Task<Result<Navigated>> {
13497        let Some(provider) = self.semantics_provider.clone() else {
13498            return Task::ready(Ok(Navigated::No));
13499        };
13500        let head = self.selections.newest::<usize>(cx).head();
13501        let buffer = self.buffer.read(cx);
13502        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13503            text_anchor
13504        } else {
13505            return Task::ready(Ok(Navigated::No));
13506        };
13507
13508        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13509            return Task::ready(Ok(Navigated::No));
13510        };
13511
13512        cx.spawn_in(window, async move |editor, cx| {
13513            let definitions = definitions.await?;
13514            let navigated = editor
13515                .update_in(cx, |editor, window, cx| {
13516                    editor.navigate_to_hover_links(
13517                        Some(kind),
13518                        definitions
13519                            .into_iter()
13520                            .filter(|location| {
13521                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13522                            })
13523                            .map(HoverLink::Text)
13524                            .collect::<Vec<_>>(),
13525                        split,
13526                        window,
13527                        cx,
13528                    )
13529                })?
13530                .await?;
13531            anyhow::Ok(navigated)
13532        })
13533    }
13534
13535    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13536        let selection = self.selections.newest_anchor();
13537        let head = selection.head();
13538        let tail = selection.tail();
13539
13540        let Some((buffer, start_position)) =
13541            self.buffer.read(cx).text_anchor_for_position(head, cx)
13542        else {
13543            return;
13544        };
13545
13546        let end_position = if head != tail {
13547            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13548                return;
13549            };
13550            Some(pos)
13551        } else {
13552            None
13553        };
13554
13555        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13556            let url = if let Some(end_pos) = end_position {
13557                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13558            } else {
13559                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13560            };
13561
13562            if let Some(url) = url {
13563                editor.update(cx, |_, cx| {
13564                    cx.open_url(&url);
13565                })
13566            } else {
13567                Ok(())
13568            }
13569        });
13570
13571        url_finder.detach();
13572    }
13573
13574    pub fn open_selected_filename(
13575        &mut self,
13576        _: &OpenSelectedFilename,
13577        window: &mut Window,
13578        cx: &mut Context<Self>,
13579    ) {
13580        let Some(workspace) = self.workspace() else {
13581            return;
13582        };
13583
13584        let position = self.selections.newest_anchor().head();
13585
13586        let Some((buffer, buffer_position)) =
13587            self.buffer.read(cx).text_anchor_for_position(position, cx)
13588        else {
13589            return;
13590        };
13591
13592        let project = self.project.clone();
13593
13594        cx.spawn_in(window, async move |_, cx| {
13595            let result = find_file(&buffer, project, buffer_position, cx).await;
13596
13597            if let Some((_, path)) = result {
13598                workspace
13599                    .update_in(cx, |workspace, window, cx| {
13600                        workspace.open_resolved_path(path, window, cx)
13601                    })?
13602                    .await?;
13603            }
13604            anyhow::Ok(())
13605        })
13606        .detach();
13607    }
13608
13609    pub(crate) fn navigate_to_hover_links(
13610        &mut self,
13611        kind: Option<GotoDefinitionKind>,
13612        mut definitions: Vec<HoverLink>,
13613        split: bool,
13614        window: &mut Window,
13615        cx: &mut Context<Editor>,
13616    ) -> Task<Result<Navigated>> {
13617        // If there is one definition, just open it directly
13618        if definitions.len() == 1 {
13619            let definition = definitions.pop().unwrap();
13620
13621            enum TargetTaskResult {
13622                Location(Option<Location>),
13623                AlreadyNavigated,
13624            }
13625
13626            let target_task = match definition {
13627                HoverLink::Text(link) => {
13628                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13629                }
13630                HoverLink::InlayHint(lsp_location, server_id) => {
13631                    let computation =
13632                        self.compute_target_location(lsp_location, server_id, window, cx);
13633                    cx.background_spawn(async move {
13634                        let location = computation.await?;
13635                        Ok(TargetTaskResult::Location(location))
13636                    })
13637                }
13638                HoverLink::Url(url) => {
13639                    cx.open_url(&url);
13640                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13641                }
13642                HoverLink::File(path) => {
13643                    if let Some(workspace) = self.workspace() {
13644                        cx.spawn_in(window, async move |_, cx| {
13645                            workspace
13646                                .update_in(cx, |workspace, window, cx| {
13647                                    workspace.open_resolved_path(path, window, cx)
13648                                })?
13649                                .await
13650                                .map(|_| TargetTaskResult::AlreadyNavigated)
13651                        })
13652                    } else {
13653                        Task::ready(Ok(TargetTaskResult::Location(None)))
13654                    }
13655                }
13656            };
13657            cx.spawn_in(window, async move |editor, cx| {
13658                let target = match target_task.await.context("target resolution task")? {
13659                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13660                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13661                    TargetTaskResult::Location(Some(target)) => target,
13662                };
13663
13664                editor.update_in(cx, |editor, window, cx| {
13665                    let Some(workspace) = editor.workspace() else {
13666                        return Navigated::No;
13667                    };
13668                    let pane = workspace.read(cx).active_pane().clone();
13669
13670                    let range = target.range.to_point(target.buffer.read(cx));
13671                    let range = editor.range_for_match(&range);
13672                    let range = collapse_multiline_range(range);
13673
13674                    if !split
13675                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13676                    {
13677                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13678                    } else {
13679                        window.defer(cx, move |window, cx| {
13680                            let target_editor: Entity<Self> =
13681                                workspace.update(cx, |workspace, cx| {
13682                                    let pane = if split {
13683                                        workspace.adjacent_pane(window, cx)
13684                                    } else {
13685                                        workspace.active_pane().clone()
13686                                    };
13687
13688                                    workspace.open_project_item(
13689                                        pane,
13690                                        target.buffer.clone(),
13691                                        true,
13692                                        true,
13693                                        window,
13694                                        cx,
13695                                    )
13696                                });
13697                            target_editor.update(cx, |target_editor, cx| {
13698                                // When selecting a definition in a different buffer, disable the nav history
13699                                // to avoid creating a history entry at the previous cursor location.
13700                                pane.update(cx, |pane, _| pane.disable_history());
13701                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13702                                pane.update(cx, |pane, _| pane.enable_history());
13703                            });
13704                        });
13705                    }
13706                    Navigated::Yes
13707                })
13708            })
13709        } else if !definitions.is_empty() {
13710            cx.spawn_in(window, async move |editor, cx| {
13711                let (title, location_tasks, workspace) = editor
13712                    .update_in(cx, |editor, window, cx| {
13713                        let tab_kind = match kind {
13714                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13715                            _ => "Definitions",
13716                        };
13717                        let title = definitions
13718                            .iter()
13719                            .find_map(|definition| match definition {
13720                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13721                                    let buffer = origin.buffer.read(cx);
13722                                    format!(
13723                                        "{} for {}",
13724                                        tab_kind,
13725                                        buffer
13726                                            .text_for_range(origin.range.clone())
13727                                            .collect::<String>()
13728                                    )
13729                                }),
13730                                HoverLink::InlayHint(_, _) => None,
13731                                HoverLink::Url(_) => None,
13732                                HoverLink::File(_) => None,
13733                            })
13734                            .unwrap_or(tab_kind.to_string());
13735                        let location_tasks = definitions
13736                            .into_iter()
13737                            .map(|definition| match definition {
13738                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13739                                HoverLink::InlayHint(lsp_location, server_id) => editor
13740                                    .compute_target_location(lsp_location, server_id, window, cx),
13741                                HoverLink::Url(_) => Task::ready(Ok(None)),
13742                                HoverLink::File(_) => Task::ready(Ok(None)),
13743                            })
13744                            .collect::<Vec<_>>();
13745                        (title, location_tasks, editor.workspace().clone())
13746                    })
13747                    .context("location tasks preparation")?;
13748
13749                let locations = future::join_all(location_tasks)
13750                    .await
13751                    .into_iter()
13752                    .filter_map(|location| location.transpose())
13753                    .collect::<Result<_>>()
13754                    .context("location tasks")?;
13755
13756                let Some(workspace) = workspace else {
13757                    return Ok(Navigated::No);
13758                };
13759                let opened = workspace
13760                    .update_in(cx, |workspace, window, cx| {
13761                        Self::open_locations_in_multibuffer(
13762                            workspace,
13763                            locations,
13764                            title,
13765                            split,
13766                            MultibufferSelectionMode::First,
13767                            window,
13768                            cx,
13769                        )
13770                    })
13771                    .ok();
13772
13773                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13774            })
13775        } else {
13776            Task::ready(Ok(Navigated::No))
13777        }
13778    }
13779
13780    fn compute_target_location(
13781        &self,
13782        lsp_location: lsp::Location,
13783        server_id: LanguageServerId,
13784        window: &mut Window,
13785        cx: &mut Context<Self>,
13786    ) -> Task<anyhow::Result<Option<Location>>> {
13787        let Some(project) = self.project.clone() else {
13788            return Task::ready(Ok(None));
13789        };
13790
13791        cx.spawn_in(window, async move |editor, cx| {
13792            let location_task = editor.update(cx, |_, cx| {
13793                project.update(cx, |project, cx| {
13794                    let language_server_name = project
13795                        .language_server_statuses(cx)
13796                        .find(|(id, _)| server_id == *id)
13797                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13798                    language_server_name.map(|language_server_name| {
13799                        project.open_local_buffer_via_lsp(
13800                            lsp_location.uri.clone(),
13801                            server_id,
13802                            language_server_name,
13803                            cx,
13804                        )
13805                    })
13806                })
13807            })?;
13808            let location = match location_task {
13809                Some(task) => Some({
13810                    let target_buffer_handle = task.await.context("open local buffer")?;
13811                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13812                        let target_start = target_buffer
13813                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13814                        let target_end = target_buffer
13815                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13816                        target_buffer.anchor_after(target_start)
13817                            ..target_buffer.anchor_before(target_end)
13818                    })?;
13819                    Location {
13820                        buffer: target_buffer_handle,
13821                        range,
13822                    }
13823                }),
13824                None => None,
13825            };
13826            Ok(location)
13827        })
13828    }
13829
13830    pub fn find_all_references(
13831        &mut self,
13832        _: &FindAllReferences,
13833        window: &mut Window,
13834        cx: &mut Context<Self>,
13835    ) -> Option<Task<Result<Navigated>>> {
13836        let selection = self.selections.newest::<usize>(cx);
13837        let multi_buffer = self.buffer.read(cx);
13838        let head = selection.head();
13839
13840        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13841        let head_anchor = multi_buffer_snapshot.anchor_at(
13842            head,
13843            if head < selection.tail() {
13844                Bias::Right
13845            } else {
13846                Bias::Left
13847            },
13848        );
13849
13850        match self
13851            .find_all_references_task_sources
13852            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13853        {
13854            Ok(_) => {
13855                log::info!(
13856                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13857                );
13858                return None;
13859            }
13860            Err(i) => {
13861                self.find_all_references_task_sources.insert(i, head_anchor);
13862            }
13863        }
13864
13865        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13866        let workspace = self.workspace()?;
13867        let project = workspace.read(cx).project().clone();
13868        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13869        Some(cx.spawn_in(window, async move |editor, cx| {
13870            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13871                if let Ok(i) = editor
13872                    .find_all_references_task_sources
13873                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13874                {
13875                    editor.find_all_references_task_sources.remove(i);
13876                }
13877            });
13878
13879            let locations = references.await?;
13880            if locations.is_empty() {
13881                return anyhow::Ok(Navigated::No);
13882            }
13883
13884            workspace.update_in(cx, |workspace, window, cx| {
13885                let title = locations
13886                    .first()
13887                    .as_ref()
13888                    .map(|location| {
13889                        let buffer = location.buffer.read(cx);
13890                        format!(
13891                            "References to `{}`",
13892                            buffer
13893                                .text_for_range(location.range.clone())
13894                                .collect::<String>()
13895                        )
13896                    })
13897                    .unwrap();
13898                Self::open_locations_in_multibuffer(
13899                    workspace,
13900                    locations,
13901                    title,
13902                    false,
13903                    MultibufferSelectionMode::First,
13904                    window,
13905                    cx,
13906                );
13907                Navigated::Yes
13908            })
13909        }))
13910    }
13911
13912    /// Opens a multibuffer with the given project locations in it
13913    pub fn open_locations_in_multibuffer(
13914        workspace: &mut Workspace,
13915        mut locations: Vec<Location>,
13916        title: String,
13917        split: bool,
13918        multibuffer_selection_mode: MultibufferSelectionMode,
13919        window: &mut Window,
13920        cx: &mut Context<Workspace>,
13921    ) {
13922        // If there are multiple definitions, open them in a multibuffer
13923        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13924        let mut locations = locations.into_iter().peekable();
13925        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13926        let capability = workspace.project().read(cx).capability();
13927
13928        let excerpt_buffer = cx.new(|cx| {
13929            let mut multibuffer = MultiBuffer::new(capability);
13930            while let Some(location) = locations.next() {
13931                let buffer = location.buffer.read(cx);
13932                let mut ranges_for_buffer = Vec::new();
13933                let range = location.range.to_point(buffer);
13934                ranges_for_buffer.push(range.clone());
13935
13936                while let Some(next_location) = locations.peek() {
13937                    if next_location.buffer == location.buffer {
13938                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13939                        locations.next();
13940                    } else {
13941                        break;
13942                    }
13943                }
13944
13945                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13946                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13947                    PathKey::for_buffer(&location.buffer, cx),
13948                    location.buffer.clone(),
13949                    ranges_for_buffer,
13950                    DEFAULT_MULTIBUFFER_CONTEXT,
13951                    cx,
13952                );
13953                ranges.extend(new_ranges)
13954            }
13955
13956            multibuffer.with_title(title)
13957        });
13958
13959        let editor = cx.new(|cx| {
13960            Editor::for_multibuffer(
13961                excerpt_buffer,
13962                Some(workspace.project().clone()),
13963                window,
13964                cx,
13965            )
13966        });
13967        editor.update(cx, |editor, cx| {
13968            match multibuffer_selection_mode {
13969                MultibufferSelectionMode::First => {
13970                    if let Some(first_range) = ranges.first() {
13971                        editor.change_selections(None, window, cx, |selections| {
13972                            selections.clear_disjoint();
13973                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13974                        });
13975                    }
13976                    editor.highlight_background::<Self>(
13977                        &ranges,
13978                        |theme| theme.editor_highlighted_line_background,
13979                        cx,
13980                    );
13981                }
13982                MultibufferSelectionMode::All => {
13983                    editor.change_selections(None, window, cx, |selections| {
13984                        selections.clear_disjoint();
13985                        selections.select_anchor_ranges(ranges);
13986                    });
13987                }
13988            }
13989            editor.register_buffers_with_language_servers(cx);
13990        });
13991
13992        let item = Box::new(editor);
13993        let item_id = item.item_id();
13994
13995        if split {
13996            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13997        } else {
13998            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13999                let (preview_item_id, preview_item_idx) =
14000                    workspace.active_pane().update(cx, |pane, _| {
14001                        (pane.preview_item_id(), pane.preview_item_idx())
14002                    });
14003
14004                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14005
14006                if let Some(preview_item_id) = preview_item_id {
14007                    workspace.active_pane().update(cx, |pane, cx| {
14008                        pane.remove_item(preview_item_id, false, false, window, cx);
14009                    });
14010                }
14011            } else {
14012                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14013            }
14014        }
14015        workspace.active_pane().update(cx, |pane, cx| {
14016            pane.set_preview_item_id(Some(item_id), cx);
14017        });
14018    }
14019
14020    pub fn rename(
14021        &mut self,
14022        _: &Rename,
14023        window: &mut Window,
14024        cx: &mut Context<Self>,
14025    ) -> Option<Task<Result<()>>> {
14026        use language::ToOffset as _;
14027
14028        let provider = self.semantics_provider.clone()?;
14029        let selection = self.selections.newest_anchor().clone();
14030        let (cursor_buffer, cursor_buffer_position) = self
14031            .buffer
14032            .read(cx)
14033            .text_anchor_for_position(selection.head(), cx)?;
14034        let (tail_buffer, cursor_buffer_position_end) = self
14035            .buffer
14036            .read(cx)
14037            .text_anchor_for_position(selection.tail(), cx)?;
14038        if tail_buffer != cursor_buffer {
14039            return None;
14040        }
14041
14042        let snapshot = cursor_buffer.read(cx).snapshot();
14043        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14044        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14045        let prepare_rename = provider
14046            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14047            .unwrap_or_else(|| Task::ready(Ok(None)));
14048        drop(snapshot);
14049
14050        Some(cx.spawn_in(window, async move |this, cx| {
14051            let rename_range = if let Some(range) = prepare_rename.await? {
14052                Some(range)
14053            } else {
14054                this.update(cx, |this, cx| {
14055                    let buffer = this.buffer.read(cx).snapshot(cx);
14056                    let mut buffer_highlights = this
14057                        .document_highlights_for_position(selection.head(), &buffer)
14058                        .filter(|highlight| {
14059                            highlight.start.excerpt_id == selection.head().excerpt_id
14060                                && highlight.end.excerpt_id == selection.head().excerpt_id
14061                        });
14062                    buffer_highlights
14063                        .next()
14064                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14065                })?
14066            };
14067            if let Some(rename_range) = rename_range {
14068                this.update_in(cx, |this, window, cx| {
14069                    let snapshot = cursor_buffer.read(cx).snapshot();
14070                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14071                    let cursor_offset_in_rename_range =
14072                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14073                    let cursor_offset_in_rename_range_end =
14074                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14075
14076                    this.take_rename(false, window, cx);
14077                    let buffer = this.buffer.read(cx).read(cx);
14078                    let cursor_offset = selection.head().to_offset(&buffer);
14079                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14080                    let rename_end = rename_start + rename_buffer_range.len();
14081                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14082                    let mut old_highlight_id = None;
14083                    let old_name: Arc<str> = buffer
14084                        .chunks(rename_start..rename_end, true)
14085                        .map(|chunk| {
14086                            if old_highlight_id.is_none() {
14087                                old_highlight_id = chunk.syntax_highlight_id;
14088                            }
14089                            chunk.text
14090                        })
14091                        .collect::<String>()
14092                        .into();
14093
14094                    drop(buffer);
14095
14096                    // Position the selection in the rename editor so that it matches the current selection.
14097                    this.show_local_selections = false;
14098                    let rename_editor = cx.new(|cx| {
14099                        let mut editor = Editor::single_line(window, cx);
14100                        editor.buffer.update(cx, |buffer, cx| {
14101                            buffer.edit([(0..0, old_name.clone())], None, cx)
14102                        });
14103                        let rename_selection_range = match cursor_offset_in_rename_range
14104                            .cmp(&cursor_offset_in_rename_range_end)
14105                        {
14106                            Ordering::Equal => {
14107                                editor.select_all(&SelectAll, window, cx);
14108                                return editor;
14109                            }
14110                            Ordering::Less => {
14111                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14112                            }
14113                            Ordering::Greater => {
14114                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14115                            }
14116                        };
14117                        if rename_selection_range.end > old_name.len() {
14118                            editor.select_all(&SelectAll, window, cx);
14119                        } else {
14120                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14121                                s.select_ranges([rename_selection_range]);
14122                            });
14123                        }
14124                        editor
14125                    });
14126                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14127                        if e == &EditorEvent::Focused {
14128                            cx.emit(EditorEvent::FocusedIn)
14129                        }
14130                    })
14131                    .detach();
14132
14133                    let write_highlights =
14134                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14135                    let read_highlights =
14136                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14137                    let ranges = write_highlights
14138                        .iter()
14139                        .flat_map(|(_, ranges)| ranges.iter())
14140                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14141                        .cloned()
14142                        .collect();
14143
14144                    this.highlight_text::<Rename>(
14145                        ranges,
14146                        HighlightStyle {
14147                            fade_out: Some(0.6),
14148                            ..Default::default()
14149                        },
14150                        cx,
14151                    );
14152                    let rename_focus_handle = rename_editor.focus_handle(cx);
14153                    window.focus(&rename_focus_handle);
14154                    let block_id = this.insert_blocks(
14155                        [BlockProperties {
14156                            style: BlockStyle::Flex,
14157                            placement: BlockPlacement::Below(range.start),
14158                            height: Some(1),
14159                            render: Arc::new({
14160                                let rename_editor = rename_editor.clone();
14161                                move |cx: &mut BlockContext| {
14162                                    let mut text_style = cx.editor_style.text.clone();
14163                                    if let Some(highlight_style) = old_highlight_id
14164                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14165                                    {
14166                                        text_style = text_style.highlight(highlight_style);
14167                                    }
14168                                    div()
14169                                        .block_mouse_down()
14170                                        .pl(cx.anchor_x)
14171                                        .child(EditorElement::new(
14172                                            &rename_editor,
14173                                            EditorStyle {
14174                                                background: cx.theme().system().transparent,
14175                                                local_player: cx.editor_style.local_player,
14176                                                text: text_style,
14177                                                scrollbar_width: cx.editor_style.scrollbar_width,
14178                                                syntax: cx.editor_style.syntax.clone(),
14179                                                status: cx.editor_style.status.clone(),
14180                                                inlay_hints_style: HighlightStyle {
14181                                                    font_weight: Some(FontWeight::BOLD),
14182                                                    ..make_inlay_hints_style(cx.app)
14183                                                },
14184                                                inline_completion_styles: make_suggestion_styles(
14185                                                    cx.app,
14186                                                ),
14187                                                ..EditorStyle::default()
14188                                            },
14189                                        ))
14190                                        .into_any_element()
14191                                }
14192                            }),
14193                            priority: 0,
14194                        }],
14195                        Some(Autoscroll::fit()),
14196                        cx,
14197                    )[0];
14198                    this.pending_rename = Some(RenameState {
14199                        range,
14200                        old_name,
14201                        editor: rename_editor,
14202                        block_id,
14203                    });
14204                })?;
14205            }
14206
14207            Ok(())
14208        }))
14209    }
14210
14211    pub fn confirm_rename(
14212        &mut self,
14213        _: &ConfirmRename,
14214        window: &mut Window,
14215        cx: &mut Context<Self>,
14216    ) -> Option<Task<Result<()>>> {
14217        let rename = self.take_rename(false, window, cx)?;
14218        let workspace = self.workspace()?.downgrade();
14219        let (buffer, start) = self
14220            .buffer
14221            .read(cx)
14222            .text_anchor_for_position(rename.range.start, cx)?;
14223        let (end_buffer, _) = self
14224            .buffer
14225            .read(cx)
14226            .text_anchor_for_position(rename.range.end, cx)?;
14227        if buffer != end_buffer {
14228            return None;
14229        }
14230
14231        let old_name = rename.old_name;
14232        let new_name = rename.editor.read(cx).text(cx);
14233
14234        let rename = self.semantics_provider.as_ref()?.perform_rename(
14235            &buffer,
14236            start,
14237            new_name.clone(),
14238            cx,
14239        )?;
14240
14241        Some(cx.spawn_in(window, async move |editor, cx| {
14242            let project_transaction = rename.await?;
14243            Self::open_project_transaction(
14244                &editor,
14245                workspace,
14246                project_transaction,
14247                format!("Rename: {}{}", old_name, new_name),
14248                cx,
14249            )
14250            .await?;
14251
14252            editor.update(cx, |editor, cx| {
14253                editor.refresh_document_highlights(cx);
14254            })?;
14255            Ok(())
14256        }))
14257    }
14258
14259    fn take_rename(
14260        &mut self,
14261        moving_cursor: bool,
14262        window: &mut Window,
14263        cx: &mut Context<Self>,
14264    ) -> Option<RenameState> {
14265        let rename = self.pending_rename.take()?;
14266        if rename.editor.focus_handle(cx).is_focused(window) {
14267            window.focus(&self.focus_handle);
14268        }
14269
14270        self.remove_blocks(
14271            [rename.block_id].into_iter().collect(),
14272            Some(Autoscroll::fit()),
14273            cx,
14274        );
14275        self.clear_highlights::<Rename>(cx);
14276        self.show_local_selections = true;
14277
14278        if moving_cursor {
14279            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14280                editor.selections.newest::<usize>(cx).head()
14281            });
14282
14283            // Update the selection to match the position of the selection inside
14284            // the rename editor.
14285            let snapshot = self.buffer.read(cx).read(cx);
14286            let rename_range = rename.range.to_offset(&snapshot);
14287            let cursor_in_editor = snapshot
14288                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14289                .min(rename_range.end);
14290            drop(snapshot);
14291
14292            self.change_selections(None, window, cx, |s| {
14293                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14294            });
14295        } else {
14296            self.refresh_document_highlights(cx);
14297        }
14298
14299        Some(rename)
14300    }
14301
14302    pub fn pending_rename(&self) -> Option<&RenameState> {
14303        self.pending_rename.as_ref()
14304    }
14305
14306    fn format(
14307        &mut self,
14308        _: &Format,
14309        window: &mut Window,
14310        cx: &mut Context<Self>,
14311    ) -> Option<Task<Result<()>>> {
14312        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14313
14314        let project = match &self.project {
14315            Some(project) => project.clone(),
14316            None => return None,
14317        };
14318
14319        Some(self.perform_format(
14320            project,
14321            FormatTrigger::Manual,
14322            FormatTarget::Buffers,
14323            window,
14324            cx,
14325        ))
14326    }
14327
14328    fn format_selections(
14329        &mut self,
14330        _: &FormatSelections,
14331        window: &mut Window,
14332        cx: &mut Context<Self>,
14333    ) -> Option<Task<Result<()>>> {
14334        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14335
14336        let project = match &self.project {
14337            Some(project) => project.clone(),
14338            None => return None,
14339        };
14340
14341        let ranges = self
14342            .selections
14343            .all_adjusted(cx)
14344            .into_iter()
14345            .map(|selection| selection.range())
14346            .collect_vec();
14347
14348        Some(self.perform_format(
14349            project,
14350            FormatTrigger::Manual,
14351            FormatTarget::Ranges(ranges),
14352            window,
14353            cx,
14354        ))
14355    }
14356
14357    fn perform_format(
14358        &mut self,
14359        project: Entity<Project>,
14360        trigger: FormatTrigger,
14361        target: FormatTarget,
14362        window: &mut Window,
14363        cx: &mut Context<Self>,
14364    ) -> Task<Result<()>> {
14365        let buffer = self.buffer.clone();
14366        let (buffers, target) = match target {
14367            FormatTarget::Buffers => {
14368                let mut buffers = buffer.read(cx).all_buffers();
14369                if trigger == FormatTrigger::Save {
14370                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14371                }
14372                (buffers, LspFormatTarget::Buffers)
14373            }
14374            FormatTarget::Ranges(selection_ranges) => {
14375                let multi_buffer = buffer.read(cx);
14376                let snapshot = multi_buffer.read(cx);
14377                let mut buffers = HashSet::default();
14378                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14379                    BTreeMap::new();
14380                for selection_range in selection_ranges {
14381                    for (buffer, buffer_range, _) in
14382                        snapshot.range_to_buffer_ranges(selection_range)
14383                    {
14384                        let buffer_id = buffer.remote_id();
14385                        let start = buffer.anchor_before(buffer_range.start);
14386                        let end = buffer.anchor_after(buffer_range.end);
14387                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14388                        buffer_id_to_ranges
14389                            .entry(buffer_id)
14390                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14391                            .or_insert_with(|| vec![start..end]);
14392                    }
14393                }
14394                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14395            }
14396        };
14397
14398        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14399        let selections_prev = transaction_id_prev
14400            .and_then(|transaction_id_prev| {
14401                // default to selections as they were after the last edit, if we have them,
14402                // instead of how they are now.
14403                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14404                // will take you back to where you made the last edit, instead of staying where you scrolled
14405                self.selection_history
14406                    .transaction(transaction_id_prev)
14407                    .map(|t| t.0.clone())
14408            })
14409            .unwrap_or_else(|| {
14410                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14411                self.selections.disjoint_anchors()
14412            });
14413
14414        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14415        let format = project.update(cx, |project, cx| {
14416            project.format(buffers, target, true, trigger, cx)
14417        });
14418
14419        cx.spawn_in(window, async move |editor, cx| {
14420            let transaction = futures::select_biased! {
14421                transaction = format.log_err().fuse() => transaction,
14422                () = timeout => {
14423                    log::warn!("timed out waiting for formatting");
14424                    None
14425                }
14426            };
14427
14428            buffer
14429                .update(cx, |buffer, cx| {
14430                    if let Some(transaction) = transaction {
14431                        if !buffer.is_singleton() {
14432                            buffer.push_transaction(&transaction.0, cx);
14433                        }
14434                    }
14435                    cx.notify();
14436                })
14437                .ok();
14438
14439            if let Some(transaction_id_now) =
14440                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14441            {
14442                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14443                if has_new_transaction {
14444                    _ = editor.update(cx, |editor, _| {
14445                        editor
14446                            .selection_history
14447                            .insert_transaction(transaction_id_now, selections_prev);
14448                    });
14449                }
14450            }
14451
14452            Ok(())
14453        })
14454    }
14455
14456    fn organize_imports(
14457        &mut self,
14458        _: &OrganizeImports,
14459        window: &mut Window,
14460        cx: &mut Context<Self>,
14461    ) -> Option<Task<Result<()>>> {
14462        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14463        let project = match &self.project {
14464            Some(project) => project.clone(),
14465            None => return None,
14466        };
14467        Some(self.perform_code_action_kind(
14468            project,
14469            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14470            window,
14471            cx,
14472        ))
14473    }
14474
14475    fn perform_code_action_kind(
14476        &mut self,
14477        project: Entity<Project>,
14478        kind: CodeActionKind,
14479        window: &mut Window,
14480        cx: &mut Context<Self>,
14481    ) -> Task<Result<()>> {
14482        let buffer = self.buffer.clone();
14483        let buffers = buffer.read(cx).all_buffers();
14484        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14485        let apply_action = project.update(cx, |project, cx| {
14486            project.apply_code_action_kind(buffers, kind, true, cx)
14487        });
14488        cx.spawn_in(window, async move |_, cx| {
14489            let transaction = futures::select_biased! {
14490                () = timeout => {
14491                    log::warn!("timed out waiting for executing code action");
14492                    None
14493                }
14494                transaction = apply_action.log_err().fuse() => transaction,
14495            };
14496            buffer
14497                .update(cx, |buffer, cx| {
14498                    // check if we need this
14499                    if let Some(transaction) = transaction {
14500                        if !buffer.is_singleton() {
14501                            buffer.push_transaction(&transaction.0, cx);
14502                        }
14503                    }
14504                    cx.notify();
14505                })
14506                .ok();
14507            Ok(())
14508        })
14509    }
14510
14511    fn restart_language_server(
14512        &mut self,
14513        _: &RestartLanguageServer,
14514        _: &mut Window,
14515        cx: &mut Context<Self>,
14516    ) {
14517        if let Some(project) = self.project.clone() {
14518            self.buffer.update(cx, |multi_buffer, cx| {
14519                project.update(cx, |project, cx| {
14520                    project.restart_language_servers_for_buffers(
14521                        multi_buffer.all_buffers().into_iter().collect(),
14522                        cx,
14523                    );
14524                });
14525            })
14526        }
14527    }
14528
14529    fn stop_language_server(
14530        &mut self,
14531        _: &StopLanguageServer,
14532        _: &mut Window,
14533        cx: &mut Context<Self>,
14534    ) {
14535        if let Some(project) = self.project.clone() {
14536            self.buffer.update(cx, |multi_buffer, cx| {
14537                project.update(cx, |project, cx| {
14538                    project.stop_language_servers_for_buffers(
14539                        multi_buffer.all_buffers().into_iter().collect(),
14540                        cx,
14541                    );
14542                    cx.emit(project::Event::RefreshInlayHints);
14543                });
14544            });
14545        }
14546    }
14547
14548    fn cancel_language_server_work(
14549        workspace: &mut Workspace,
14550        _: &actions::CancelLanguageServerWork,
14551        _: &mut Window,
14552        cx: &mut Context<Workspace>,
14553    ) {
14554        let project = workspace.project();
14555        let buffers = workspace
14556            .active_item(cx)
14557            .and_then(|item| item.act_as::<Editor>(cx))
14558            .map_or(HashSet::default(), |editor| {
14559                editor.read(cx).buffer.read(cx).all_buffers()
14560            });
14561        project.update(cx, |project, cx| {
14562            project.cancel_language_server_work_for_buffers(buffers, cx);
14563        });
14564    }
14565
14566    fn show_character_palette(
14567        &mut self,
14568        _: &ShowCharacterPalette,
14569        window: &mut Window,
14570        _: &mut Context<Self>,
14571    ) {
14572        window.show_character_palette();
14573    }
14574
14575    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14576        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14577            let buffer = self.buffer.read(cx).snapshot(cx);
14578            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14579            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14580            let is_valid = buffer
14581                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14582                .any(|entry| {
14583                    entry.diagnostic.is_primary
14584                        && !entry.range.is_empty()
14585                        && entry.range.start == primary_range_start
14586                        && entry.diagnostic.message == active_diagnostics.active_message
14587                });
14588
14589            if !is_valid {
14590                self.dismiss_diagnostics(cx);
14591            }
14592        }
14593    }
14594
14595    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14596        match &self.active_diagnostics {
14597            ActiveDiagnostic::Group(group) => Some(group),
14598            _ => None,
14599        }
14600    }
14601
14602    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14603        self.dismiss_diagnostics(cx);
14604        self.active_diagnostics = ActiveDiagnostic::All;
14605    }
14606
14607    fn activate_diagnostics(
14608        &mut self,
14609        buffer_id: BufferId,
14610        diagnostic: DiagnosticEntry<usize>,
14611        window: &mut Window,
14612        cx: &mut Context<Self>,
14613    ) {
14614        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14615            return;
14616        }
14617        self.dismiss_diagnostics(cx);
14618        let snapshot = self.snapshot(window, cx);
14619        let Some(diagnostic_renderer) = cx
14620            .try_global::<GlobalDiagnosticRenderer>()
14621            .map(|g| g.0.clone())
14622        else {
14623            return;
14624        };
14625        let buffer = self.buffer.read(cx).snapshot(cx);
14626
14627        let diagnostic_group = buffer
14628            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14629            .collect::<Vec<_>>();
14630
14631        let blocks = diagnostic_renderer.render_group(
14632            diagnostic_group,
14633            buffer_id,
14634            snapshot,
14635            cx.weak_entity(),
14636            cx,
14637        );
14638
14639        let blocks = self.display_map.update(cx, |display_map, cx| {
14640            display_map.insert_blocks(blocks, cx).into_iter().collect()
14641        });
14642        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14643            active_range: buffer.anchor_before(diagnostic.range.start)
14644                ..buffer.anchor_after(diagnostic.range.end),
14645            active_message: diagnostic.diagnostic.message.clone(),
14646            group_id: diagnostic.diagnostic.group_id,
14647            blocks,
14648        });
14649        cx.notify();
14650    }
14651
14652    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14653        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14654            return;
14655        };
14656
14657        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14658        if let ActiveDiagnostic::Group(group) = prev {
14659            self.display_map.update(cx, |display_map, cx| {
14660                display_map.remove_blocks(group.blocks, cx);
14661            });
14662            cx.notify();
14663        }
14664    }
14665
14666    /// Disable inline diagnostics rendering for this editor.
14667    pub fn disable_inline_diagnostics(&mut self) {
14668        self.inline_diagnostics_enabled = false;
14669        self.inline_diagnostics_update = Task::ready(());
14670        self.inline_diagnostics.clear();
14671    }
14672
14673    pub fn inline_diagnostics_enabled(&self) -> bool {
14674        self.inline_diagnostics_enabled
14675    }
14676
14677    pub fn show_inline_diagnostics(&self) -> bool {
14678        self.show_inline_diagnostics
14679    }
14680
14681    pub fn toggle_inline_diagnostics(
14682        &mut self,
14683        _: &ToggleInlineDiagnostics,
14684        window: &mut Window,
14685        cx: &mut Context<Editor>,
14686    ) {
14687        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14688        self.refresh_inline_diagnostics(false, window, cx);
14689    }
14690
14691    fn refresh_inline_diagnostics(
14692        &mut self,
14693        debounce: bool,
14694        window: &mut Window,
14695        cx: &mut Context<Self>,
14696    ) {
14697        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14698            self.inline_diagnostics_update = Task::ready(());
14699            self.inline_diagnostics.clear();
14700            return;
14701        }
14702
14703        let debounce_ms = ProjectSettings::get_global(cx)
14704            .diagnostics
14705            .inline
14706            .update_debounce_ms;
14707        let debounce = if debounce && debounce_ms > 0 {
14708            Some(Duration::from_millis(debounce_ms))
14709        } else {
14710            None
14711        };
14712        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14713            let editor = editor.upgrade().unwrap();
14714
14715            if let Some(debounce) = debounce {
14716                cx.background_executor().timer(debounce).await;
14717            }
14718            let Some(snapshot) = editor
14719                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14720                .ok()
14721            else {
14722                return;
14723            };
14724
14725            let new_inline_diagnostics = cx
14726                .background_spawn(async move {
14727                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14728                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14729                        let message = diagnostic_entry
14730                            .diagnostic
14731                            .message
14732                            .split_once('\n')
14733                            .map(|(line, _)| line)
14734                            .map(SharedString::new)
14735                            .unwrap_or_else(|| {
14736                                SharedString::from(diagnostic_entry.diagnostic.message)
14737                            });
14738                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14739                        let (Ok(i) | Err(i)) = inline_diagnostics
14740                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14741                        inline_diagnostics.insert(
14742                            i,
14743                            (
14744                                start_anchor,
14745                                InlineDiagnostic {
14746                                    message,
14747                                    group_id: diagnostic_entry.diagnostic.group_id,
14748                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14749                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14750                                    severity: diagnostic_entry.diagnostic.severity,
14751                                },
14752                            ),
14753                        );
14754                    }
14755                    inline_diagnostics
14756                })
14757                .await;
14758
14759            editor
14760                .update(cx, |editor, cx| {
14761                    editor.inline_diagnostics = new_inline_diagnostics;
14762                    cx.notify();
14763                })
14764                .ok();
14765        });
14766    }
14767
14768    pub fn set_selections_from_remote(
14769        &mut self,
14770        selections: Vec<Selection<Anchor>>,
14771        pending_selection: Option<Selection<Anchor>>,
14772        window: &mut Window,
14773        cx: &mut Context<Self>,
14774    ) {
14775        let old_cursor_position = self.selections.newest_anchor().head();
14776        self.selections.change_with(cx, |s| {
14777            s.select_anchors(selections);
14778            if let Some(pending_selection) = pending_selection {
14779                s.set_pending(pending_selection, SelectMode::Character);
14780            } else {
14781                s.clear_pending();
14782            }
14783        });
14784        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14785    }
14786
14787    fn push_to_selection_history(&mut self) {
14788        self.selection_history.push(SelectionHistoryEntry {
14789            selections: self.selections.disjoint_anchors(),
14790            select_next_state: self.select_next_state.clone(),
14791            select_prev_state: self.select_prev_state.clone(),
14792            add_selections_state: self.add_selections_state.clone(),
14793        });
14794    }
14795
14796    pub fn transact(
14797        &mut self,
14798        window: &mut Window,
14799        cx: &mut Context<Self>,
14800        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14801    ) -> Option<TransactionId> {
14802        self.start_transaction_at(Instant::now(), window, cx);
14803        update(self, window, cx);
14804        self.end_transaction_at(Instant::now(), cx)
14805    }
14806
14807    pub fn start_transaction_at(
14808        &mut self,
14809        now: Instant,
14810        window: &mut Window,
14811        cx: &mut Context<Self>,
14812    ) {
14813        self.end_selection(window, cx);
14814        if let Some(tx_id) = self
14815            .buffer
14816            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14817        {
14818            self.selection_history
14819                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14820            cx.emit(EditorEvent::TransactionBegun {
14821                transaction_id: tx_id,
14822            })
14823        }
14824    }
14825
14826    pub fn end_transaction_at(
14827        &mut self,
14828        now: Instant,
14829        cx: &mut Context<Self>,
14830    ) -> Option<TransactionId> {
14831        if let Some(transaction_id) = self
14832            .buffer
14833            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14834        {
14835            if let Some((_, end_selections)) =
14836                self.selection_history.transaction_mut(transaction_id)
14837            {
14838                *end_selections = Some(self.selections.disjoint_anchors());
14839            } else {
14840                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14841            }
14842
14843            cx.emit(EditorEvent::Edited { transaction_id });
14844            Some(transaction_id)
14845        } else {
14846            None
14847        }
14848    }
14849
14850    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14851        if self.selection_mark_mode {
14852            self.change_selections(None, window, cx, |s| {
14853                s.move_with(|_, sel| {
14854                    sel.collapse_to(sel.head(), SelectionGoal::None);
14855                });
14856            })
14857        }
14858        self.selection_mark_mode = true;
14859        cx.notify();
14860    }
14861
14862    pub fn swap_selection_ends(
14863        &mut self,
14864        _: &actions::SwapSelectionEnds,
14865        window: &mut Window,
14866        cx: &mut Context<Self>,
14867    ) {
14868        self.change_selections(None, window, cx, |s| {
14869            s.move_with(|_, sel| {
14870                if sel.start != sel.end {
14871                    sel.reversed = !sel.reversed
14872                }
14873            });
14874        });
14875        self.request_autoscroll(Autoscroll::newest(), cx);
14876        cx.notify();
14877    }
14878
14879    pub fn toggle_fold(
14880        &mut self,
14881        _: &actions::ToggleFold,
14882        window: &mut Window,
14883        cx: &mut Context<Self>,
14884    ) {
14885        if self.is_singleton(cx) {
14886            let selection = self.selections.newest::<Point>(cx);
14887
14888            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14889            let range = if selection.is_empty() {
14890                let point = selection.head().to_display_point(&display_map);
14891                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14892                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14893                    .to_point(&display_map);
14894                start..end
14895            } else {
14896                selection.range()
14897            };
14898            if display_map.folds_in_range(range).next().is_some() {
14899                self.unfold_lines(&Default::default(), window, cx)
14900            } else {
14901                self.fold(&Default::default(), window, cx)
14902            }
14903        } else {
14904            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14905            let buffer_ids: HashSet<_> = self
14906                .selections
14907                .disjoint_anchor_ranges()
14908                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14909                .collect();
14910
14911            let should_unfold = buffer_ids
14912                .iter()
14913                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14914
14915            for buffer_id in buffer_ids {
14916                if should_unfold {
14917                    self.unfold_buffer(buffer_id, cx);
14918                } else {
14919                    self.fold_buffer(buffer_id, cx);
14920                }
14921            }
14922        }
14923    }
14924
14925    pub fn toggle_fold_recursive(
14926        &mut self,
14927        _: &actions::ToggleFoldRecursive,
14928        window: &mut Window,
14929        cx: &mut Context<Self>,
14930    ) {
14931        let selection = self.selections.newest::<Point>(cx);
14932
14933        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14934        let range = if selection.is_empty() {
14935            let point = selection.head().to_display_point(&display_map);
14936            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14937            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14938                .to_point(&display_map);
14939            start..end
14940        } else {
14941            selection.range()
14942        };
14943        if display_map.folds_in_range(range).next().is_some() {
14944            self.unfold_recursive(&Default::default(), window, cx)
14945        } else {
14946            self.fold_recursive(&Default::default(), window, cx)
14947        }
14948    }
14949
14950    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14951        if self.is_singleton(cx) {
14952            let mut to_fold = Vec::new();
14953            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14954            let selections = self.selections.all_adjusted(cx);
14955
14956            for selection in selections {
14957                let range = selection.range().sorted();
14958                let buffer_start_row = range.start.row;
14959
14960                if range.start.row != range.end.row {
14961                    let mut found = false;
14962                    let mut row = range.start.row;
14963                    while row <= range.end.row {
14964                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14965                        {
14966                            found = true;
14967                            row = crease.range().end.row + 1;
14968                            to_fold.push(crease);
14969                        } else {
14970                            row += 1
14971                        }
14972                    }
14973                    if found {
14974                        continue;
14975                    }
14976                }
14977
14978                for row in (0..=range.start.row).rev() {
14979                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14980                        if crease.range().end.row >= buffer_start_row {
14981                            to_fold.push(crease);
14982                            if row <= range.start.row {
14983                                break;
14984                            }
14985                        }
14986                    }
14987                }
14988            }
14989
14990            self.fold_creases(to_fold, true, window, cx);
14991        } else {
14992            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14993            let buffer_ids = self
14994                .selections
14995                .disjoint_anchor_ranges()
14996                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14997                .collect::<HashSet<_>>();
14998            for buffer_id in buffer_ids {
14999                self.fold_buffer(buffer_id, cx);
15000            }
15001        }
15002    }
15003
15004    fn fold_at_level(
15005        &mut self,
15006        fold_at: &FoldAtLevel,
15007        window: &mut Window,
15008        cx: &mut Context<Self>,
15009    ) {
15010        if !self.buffer.read(cx).is_singleton() {
15011            return;
15012        }
15013
15014        let fold_at_level = fold_at.0;
15015        let snapshot = self.buffer.read(cx).snapshot(cx);
15016        let mut to_fold = Vec::new();
15017        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15018
15019        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15020            while start_row < end_row {
15021                match self
15022                    .snapshot(window, cx)
15023                    .crease_for_buffer_row(MultiBufferRow(start_row))
15024                {
15025                    Some(crease) => {
15026                        let nested_start_row = crease.range().start.row + 1;
15027                        let nested_end_row = crease.range().end.row;
15028
15029                        if current_level < fold_at_level {
15030                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15031                        } else if current_level == fold_at_level {
15032                            to_fold.push(crease);
15033                        }
15034
15035                        start_row = nested_end_row + 1;
15036                    }
15037                    None => start_row += 1,
15038                }
15039            }
15040        }
15041
15042        self.fold_creases(to_fold, true, window, cx);
15043    }
15044
15045    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15046        if self.buffer.read(cx).is_singleton() {
15047            let mut fold_ranges = Vec::new();
15048            let snapshot = self.buffer.read(cx).snapshot(cx);
15049
15050            for row in 0..snapshot.max_row().0 {
15051                if let Some(foldable_range) = self
15052                    .snapshot(window, cx)
15053                    .crease_for_buffer_row(MultiBufferRow(row))
15054                {
15055                    fold_ranges.push(foldable_range);
15056                }
15057            }
15058
15059            self.fold_creases(fold_ranges, true, window, cx);
15060        } else {
15061            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15062                editor
15063                    .update_in(cx, |editor, _, cx| {
15064                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15065                            editor.fold_buffer(buffer_id, cx);
15066                        }
15067                    })
15068                    .ok();
15069            });
15070        }
15071    }
15072
15073    pub fn fold_function_bodies(
15074        &mut self,
15075        _: &actions::FoldFunctionBodies,
15076        window: &mut Window,
15077        cx: &mut Context<Self>,
15078    ) {
15079        let snapshot = self.buffer.read(cx).snapshot(cx);
15080
15081        let ranges = snapshot
15082            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15083            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15084            .collect::<Vec<_>>();
15085
15086        let creases = ranges
15087            .into_iter()
15088            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15089            .collect();
15090
15091        self.fold_creases(creases, true, window, cx);
15092    }
15093
15094    pub fn fold_recursive(
15095        &mut self,
15096        _: &actions::FoldRecursive,
15097        window: &mut Window,
15098        cx: &mut Context<Self>,
15099    ) {
15100        let mut to_fold = Vec::new();
15101        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15102        let selections = self.selections.all_adjusted(cx);
15103
15104        for selection in selections {
15105            let range = selection.range().sorted();
15106            let buffer_start_row = range.start.row;
15107
15108            if range.start.row != range.end.row {
15109                let mut found = false;
15110                for row in range.start.row..=range.end.row {
15111                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15112                        found = true;
15113                        to_fold.push(crease);
15114                    }
15115                }
15116                if found {
15117                    continue;
15118                }
15119            }
15120
15121            for row in (0..=range.start.row).rev() {
15122                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15123                    if crease.range().end.row >= buffer_start_row {
15124                        to_fold.push(crease);
15125                    } else {
15126                        break;
15127                    }
15128                }
15129            }
15130        }
15131
15132        self.fold_creases(to_fold, true, window, cx);
15133    }
15134
15135    pub fn fold_at(
15136        &mut self,
15137        buffer_row: MultiBufferRow,
15138        window: &mut Window,
15139        cx: &mut Context<Self>,
15140    ) {
15141        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15142
15143        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15144            let autoscroll = self
15145                .selections
15146                .all::<Point>(cx)
15147                .iter()
15148                .any(|selection| crease.range().overlaps(&selection.range()));
15149
15150            self.fold_creases(vec![crease], autoscroll, window, cx);
15151        }
15152    }
15153
15154    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15155        if self.is_singleton(cx) {
15156            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15157            let buffer = &display_map.buffer_snapshot;
15158            let selections = self.selections.all::<Point>(cx);
15159            let ranges = selections
15160                .iter()
15161                .map(|s| {
15162                    let range = s.display_range(&display_map).sorted();
15163                    let mut start = range.start.to_point(&display_map);
15164                    let mut end = range.end.to_point(&display_map);
15165                    start.column = 0;
15166                    end.column = buffer.line_len(MultiBufferRow(end.row));
15167                    start..end
15168                })
15169                .collect::<Vec<_>>();
15170
15171            self.unfold_ranges(&ranges, true, true, cx);
15172        } else {
15173            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15174            let buffer_ids = self
15175                .selections
15176                .disjoint_anchor_ranges()
15177                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15178                .collect::<HashSet<_>>();
15179            for buffer_id in buffer_ids {
15180                self.unfold_buffer(buffer_id, cx);
15181            }
15182        }
15183    }
15184
15185    pub fn unfold_recursive(
15186        &mut self,
15187        _: &UnfoldRecursive,
15188        _window: &mut Window,
15189        cx: &mut Context<Self>,
15190    ) {
15191        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15192        let selections = self.selections.all::<Point>(cx);
15193        let ranges = selections
15194            .iter()
15195            .map(|s| {
15196                let mut range = s.display_range(&display_map).sorted();
15197                *range.start.column_mut() = 0;
15198                *range.end.column_mut() = display_map.line_len(range.end.row());
15199                let start = range.start.to_point(&display_map);
15200                let end = range.end.to_point(&display_map);
15201                start..end
15202            })
15203            .collect::<Vec<_>>();
15204
15205        self.unfold_ranges(&ranges, true, true, cx);
15206    }
15207
15208    pub fn unfold_at(
15209        &mut self,
15210        buffer_row: MultiBufferRow,
15211        _window: &mut Window,
15212        cx: &mut Context<Self>,
15213    ) {
15214        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15215
15216        let intersection_range = Point::new(buffer_row.0, 0)
15217            ..Point::new(
15218                buffer_row.0,
15219                display_map.buffer_snapshot.line_len(buffer_row),
15220            );
15221
15222        let autoscroll = self
15223            .selections
15224            .all::<Point>(cx)
15225            .iter()
15226            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15227
15228        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15229    }
15230
15231    pub fn unfold_all(
15232        &mut self,
15233        _: &actions::UnfoldAll,
15234        _window: &mut Window,
15235        cx: &mut Context<Self>,
15236    ) {
15237        if self.buffer.read(cx).is_singleton() {
15238            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15239            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15240        } else {
15241            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15242                editor
15243                    .update(cx, |editor, cx| {
15244                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15245                            editor.unfold_buffer(buffer_id, cx);
15246                        }
15247                    })
15248                    .ok();
15249            });
15250        }
15251    }
15252
15253    pub fn fold_selected_ranges(
15254        &mut self,
15255        _: &FoldSelectedRanges,
15256        window: &mut Window,
15257        cx: &mut Context<Self>,
15258    ) {
15259        let selections = self.selections.all_adjusted(cx);
15260        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15261        let ranges = selections
15262            .into_iter()
15263            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15264            .collect::<Vec<_>>();
15265        self.fold_creases(ranges, true, window, cx);
15266    }
15267
15268    pub fn fold_ranges<T: ToOffset + Clone>(
15269        &mut self,
15270        ranges: Vec<Range<T>>,
15271        auto_scroll: bool,
15272        window: &mut Window,
15273        cx: &mut Context<Self>,
15274    ) {
15275        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15276        let ranges = ranges
15277            .into_iter()
15278            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15279            .collect::<Vec<_>>();
15280        self.fold_creases(ranges, auto_scroll, window, cx);
15281    }
15282
15283    pub fn fold_creases<T: ToOffset + Clone>(
15284        &mut self,
15285        creases: Vec<Crease<T>>,
15286        auto_scroll: bool,
15287        _window: &mut Window,
15288        cx: &mut Context<Self>,
15289    ) {
15290        if creases.is_empty() {
15291            return;
15292        }
15293
15294        let mut buffers_affected = HashSet::default();
15295        let multi_buffer = self.buffer().read(cx);
15296        for crease in &creases {
15297            if let Some((_, buffer, _)) =
15298                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15299            {
15300                buffers_affected.insert(buffer.read(cx).remote_id());
15301            };
15302        }
15303
15304        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15305
15306        if auto_scroll {
15307            self.request_autoscroll(Autoscroll::fit(), cx);
15308        }
15309
15310        cx.notify();
15311
15312        self.scrollbar_marker_state.dirty = true;
15313        self.folds_did_change(cx);
15314    }
15315
15316    /// Removes any folds whose ranges intersect any of the given ranges.
15317    pub fn unfold_ranges<T: ToOffset + Clone>(
15318        &mut self,
15319        ranges: &[Range<T>],
15320        inclusive: bool,
15321        auto_scroll: bool,
15322        cx: &mut Context<Self>,
15323    ) {
15324        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15325            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15326        });
15327        self.folds_did_change(cx);
15328    }
15329
15330    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15331        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15332            return;
15333        }
15334        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15335        self.display_map.update(cx, |display_map, cx| {
15336            display_map.fold_buffers([buffer_id], cx)
15337        });
15338        cx.emit(EditorEvent::BufferFoldToggled {
15339            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15340            folded: true,
15341        });
15342        cx.notify();
15343    }
15344
15345    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15346        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15347            return;
15348        }
15349        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15350        self.display_map.update(cx, |display_map, cx| {
15351            display_map.unfold_buffers([buffer_id], cx);
15352        });
15353        cx.emit(EditorEvent::BufferFoldToggled {
15354            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15355            folded: false,
15356        });
15357        cx.notify();
15358    }
15359
15360    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15361        self.display_map.read(cx).is_buffer_folded(buffer)
15362    }
15363
15364    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15365        self.display_map.read(cx).folded_buffers()
15366    }
15367
15368    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15369        self.display_map.update(cx, |display_map, cx| {
15370            display_map.disable_header_for_buffer(buffer_id, cx);
15371        });
15372        cx.notify();
15373    }
15374
15375    /// Removes any folds with the given ranges.
15376    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15377        &mut self,
15378        ranges: &[Range<T>],
15379        type_id: TypeId,
15380        auto_scroll: bool,
15381        cx: &mut Context<Self>,
15382    ) {
15383        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15384            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15385        });
15386        self.folds_did_change(cx);
15387    }
15388
15389    fn remove_folds_with<T: ToOffset + Clone>(
15390        &mut self,
15391        ranges: &[Range<T>],
15392        auto_scroll: bool,
15393        cx: &mut Context<Self>,
15394        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15395    ) {
15396        if ranges.is_empty() {
15397            return;
15398        }
15399
15400        let mut buffers_affected = HashSet::default();
15401        let multi_buffer = self.buffer().read(cx);
15402        for range in ranges {
15403            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15404                buffers_affected.insert(buffer.read(cx).remote_id());
15405            };
15406        }
15407
15408        self.display_map.update(cx, update);
15409
15410        if auto_scroll {
15411            self.request_autoscroll(Autoscroll::fit(), cx);
15412        }
15413
15414        cx.notify();
15415        self.scrollbar_marker_state.dirty = true;
15416        self.active_indent_guides_state.dirty = true;
15417    }
15418
15419    pub fn update_fold_widths(
15420        &mut self,
15421        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15422        cx: &mut Context<Self>,
15423    ) -> bool {
15424        self.display_map
15425            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15426    }
15427
15428    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15429        self.display_map.read(cx).fold_placeholder.clone()
15430    }
15431
15432    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15433        self.buffer.update(cx, |buffer, cx| {
15434            buffer.set_all_diff_hunks_expanded(cx);
15435        });
15436    }
15437
15438    pub fn expand_all_diff_hunks(
15439        &mut self,
15440        _: &ExpandAllDiffHunks,
15441        _window: &mut Window,
15442        cx: &mut Context<Self>,
15443    ) {
15444        self.buffer.update(cx, |buffer, cx| {
15445            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15446        });
15447    }
15448
15449    pub fn toggle_selected_diff_hunks(
15450        &mut self,
15451        _: &ToggleSelectedDiffHunks,
15452        _window: &mut Window,
15453        cx: &mut Context<Self>,
15454    ) {
15455        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15456        self.toggle_diff_hunks_in_ranges(ranges, cx);
15457    }
15458
15459    pub fn diff_hunks_in_ranges<'a>(
15460        &'a self,
15461        ranges: &'a [Range<Anchor>],
15462        buffer: &'a MultiBufferSnapshot,
15463    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15464        ranges.iter().flat_map(move |range| {
15465            let end_excerpt_id = range.end.excerpt_id;
15466            let range = range.to_point(buffer);
15467            let mut peek_end = range.end;
15468            if range.end.row < buffer.max_row().0 {
15469                peek_end = Point::new(range.end.row + 1, 0);
15470            }
15471            buffer
15472                .diff_hunks_in_range(range.start..peek_end)
15473                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15474        })
15475    }
15476
15477    pub fn has_stageable_diff_hunks_in_ranges(
15478        &self,
15479        ranges: &[Range<Anchor>],
15480        snapshot: &MultiBufferSnapshot,
15481    ) -> bool {
15482        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15483        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15484    }
15485
15486    pub fn toggle_staged_selected_diff_hunks(
15487        &mut self,
15488        _: &::git::ToggleStaged,
15489        _: &mut Window,
15490        cx: &mut Context<Self>,
15491    ) {
15492        let snapshot = self.buffer.read(cx).snapshot(cx);
15493        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15494        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15495        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15496    }
15497
15498    pub fn set_render_diff_hunk_controls(
15499        &mut self,
15500        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15501        cx: &mut Context<Self>,
15502    ) {
15503        self.render_diff_hunk_controls = render_diff_hunk_controls;
15504        cx.notify();
15505    }
15506
15507    pub fn stage_and_next(
15508        &mut self,
15509        _: &::git::StageAndNext,
15510        window: &mut Window,
15511        cx: &mut Context<Self>,
15512    ) {
15513        self.do_stage_or_unstage_and_next(true, window, cx);
15514    }
15515
15516    pub fn unstage_and_next(
15517        &mut self,
15518        _: &::git::UnstageAndNext,
15519        window: &mut Window,
15520        cx: &mut Context<Self>,
15521    ) {
15522        self.do_stage_or_unstage_and_next(false, window, cx);
15523    }
15524
15525    pub fn stage_or_unstage_diff_hunks(
15526        &mut self,
15527        stage: bool,
15528        ranges: Vec<Range<Anchor>>,
15529        cx: &mut Context<Self>,
15530    ) {
15531        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15532        cx.spawn(async move |this, cx| {
15533            task.await?;
15534            this.update(cx, |this, cx| {
15535                let snapshot = this.buffer.read(cx).snapshot(cx);
15536                let chunk_by = this
15537                    .diff_hunks_in_ranges(&ranges, &snapshot)
15538                    .chunk_by(|hunk| hunk.buffer_id);
15539                for (buffer_id, hunks) in &chunk_by {
15540                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15541                }
15542            })
15543        })
15544        .detach_and_log_err(cx);
15545    }
15546
15547    fn save_buffers_for_ranges_if_needed(
15548        &mut self,
15549        ranges: &[Range<Anchor>],
15550        cx: &mut Context<Editor>,
15551    ) -> Task<Result<()>> {
15552        let multibuffer = self.buffer.read(cx);
15553        let snapshot = multibuffer.read(cx);
15554        let buffer_ids: HashSet<_> = ranges
15555            .iter()
15556            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15557            .collect();
15558        drop(snapshot);
15559
15560        let mut buffers = HashSet::default();
15561        for buffer_id in buffer_ids {
15562            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15563                let buffer = buffer_entity.read(cx);
15564                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15565                {
15566                    buffers.insert(buffer_entity);
15567                }
15568            }
15569        }
15570
15571        if let Some(project) = &self.project {
15572            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15573        } else {
15574            Task::ready(Ok(()))
15575        }
15576    }
15577
15578    fn do_stage_or_unstage_and_next(
15579        &mut self,
15580        stage: bool,
15581        window: &mut Window,
15582        cx: &mut Context<Self>,
15583    ) {
15584        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15585
15586        if ranges.iter().any(|range| range.start != range.end) {
15587            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15588            return;
15589        }
15590
15591        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15592        let snapshot = self.snapshot(window, cx);
15593        let position = self.selections.newest::<Point>(cx).head();
15594        let mut row = snapshot
15595            .buffer_snapshot
15596            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15597            .find(|hunk| hunk.row_range.start.0 > position.row)
15598            .map(|hunk| hunk.row_range.start);
15599
15600        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15601        // Outside of the project diff editor, wrap around to the beginning.
15602        if !all_diff_hunks_expanded {
15603            row = row.or_else(|| {
15604                snapshot
15605                    .buffer_snapshot
15606                    .diff_hunks_in_range(Point::zero()..position)
15607                    .find(|hunk| hunk.row_range.end.0 < position.row)
15608                    .map(|hunk| hunk.row_range.start)
15609            });
15610        }
15611
15612        if let Some(row) = row {
15613            let destination = Point::new(row.0, 0);
15614            let autoscroll = Autoscroll::center();
15615
15616            self.unfold_ranges(&[destination..destination], false, false, cx);
15617            self.change_selections(Some(autoscroll), window, cx, |s| {
15618                s.select_ranges([destination..destination]);
15619            });
15620        }
15621    }
15622
15623    fn do_stage_or_unstage(
15624        &self,
15625        stage: bool,
15626        buffer_id: BufferId,
15627        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15628        cx: &mut App,
15629    ) -> Option<()> {
15630        let project = self.project.as_ref()?;
15631        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15632        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15633        let buffer_snapshot = buffer.read(cx).snapshot();
15634        let file_exists = buffer_snapshot
15635            .file()
15636            .is_some_and(|file| file.disk_state().exists());
15637        diff.update(cx, |diff, cx| {
15638            diff.stage_or_unstage_hunks(
15639                stage,
15640                &hunks
15641                    .map(|hunk| buffer_diff::DiffHunk {
15642                        buffer_range: hunk.buffer_range,
15643                        diff_base_byte_range: hunk.diff_base_byte_range,
15644                        secondary_status: hunk.secondary_status,
15645                        range: Point::zero()..Point::zero(), // unused
15646                    })
15647                    .collect::<Vec<_>>(),
15648                &buffer_snapshot,
15649                file_exists,
15650                cx,
15651            )
15652        });
15653        None
15654    }
15655
15656    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15657        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15658        self.buffer
15659            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15660    }
15661
15662    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15663        self.buffer.update(cx, |buffer, cx| {
15664            let ranges = vec![Anchor::min()..Anchor::max()];
15665            if !buffer.all_diff_hunks_expanded()
15666                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15667            {
15668                buffer.collapse_diff_hunks(ranges, cx);
15669                true
15670            } else {
15671                false
15672            }
15673        })
15674    }
15675
15676    fn toggle_diff_hunks_in_ranges(
15677        &mut self,
15678        ranges: Vec<Range<Anchor>>,
15679        cx: &mut Context<Editor>,
15680    ) {
15681        self.buffer.update(cx, |buffer, cx| {
15682            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15683            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15684        })
15685    }
15686
15687    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15688        self.buffer.update(cx, |buffer, cx| {
15689            let snapshot = buffer.snapshot(cx);
15690            let excerpt_id = range.end.excerpt_id;
15691            let point_range = range.to_point(&snapshot);
15692            let expand = !buffer.single_hunk_is_expanded(range, cx);
15693            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15694        })
15695    }
15696
15697    pub(crate) fn apply_all_diff_hunks(
15698        &mut self,
15699        _: &ApplyAllDiffHunks,
15700        window: &mut Window,
15701        cx: &mut Context<Self>,
15702    ) {
15703        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15704
15705        let buffers = self.buffer.read(cx).all_buffers();
15706        for branch_buffer in buffers {
15707            branch_buffer.update(cx, |branch_buffer, cx| {
15708                branch_buffer.merge_into_base(Vec::new(), cx);
15709            });
15710        }
15711
15712        if let Some(project) = self.project.clone() {
15713            self.save(true, project, window, cx).detach_and_log_err(cx);
15714        }
15715    }
15716
15717    pub(crate) fn apply_selected_diff_hunks(
15718        &mut self,
15719        _: &ApplyDiffHunk,
15720        window: &mut Window,
15721        cx: &mut Context<Self>,
15722    ) {
15723        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15724        let snapshot = self.snapshot(window, cx);
15725        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15726        let mut ranges_by_buffer = HashMap::default();
15727        self.transact(window, cx, |editor, _window, cx| {
15728            for hunk in hunks {
15729                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15730                    ranges_by_buffer
15731                        .entry(buffer.clone())
15732                        .or_insert_with(Vec::new)
15733                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15734                }
15735            }
15736
15737            for (buffer, ranges) in ranges_by_buffer {
15738                buffer.update(cx, |buffer, cx| {
15739                    buffer.merge_into_base(ranges, cx);
15740                });
15741            }
15742        });
15743
15744        if let Some(project) = self.project.clone() {
15745            self.save(true, project, window, cx).detach_and_log_err(cx);
15746        }
15747    }
15748
15749    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15750        if hovered != self.gutter_hovered {
15751            self.gutter_hovered = hovered;
15752            cx.notify();
15753        }
15754    }
15755
15756    pub fn insert_blocks(
15757        &mut self,
15758        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15759        autoscroll: Option<Autoscroll>,
15760        cx: &mut Context<Self>,
15761    ) -> Vec<CustomBlockId> {
15762        let blocks = self
15763            .display_map
15764            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15765        if let Some(autoscroll) = autoscroll {
15766            self.request_autoscroll(autoscroll, cx);
15767        }
15768        cx.notify();
15769        blocks
15770    }
15771
15772    pub fn resize_blocks(
15773        &mut self,
15774        heights: HashMap<CustomBlockId, u32>,
15775        autoscroll: Option<Autoscroll>,
15776        cx: &mut Context<Self>,
15777    ) {
15778        self.display_map
15779            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15780        if let Some(autoscroll) = autoscroll {
15781            self.request_autoscroll(autoscroll, cx);
15782        }
15783        cx.notify();
15784    }
15785
15786    pub fn replace_blocks(
15787        &mut self,
15788        renderers: HashMap<CustomBlockId, RenderBlock>,
15789        autoscroll: Option<Autoscroll>,
15790        cx: &mut Context<Self>,
15791    ) {
15792        self.display_map
15793            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15794        if let Some(autoscroll) = autoscroll {
15795            self.request_autoscroll(autoscroll, cx);
15796        }
15797        cx.notify();
15798    }
15799
15800    pub fn remove_blocks(
15801        &mut self,
15802        block_ids: HashSet<CustomBlockId>,
15803        autoscroll: Option<Autoscroll>,
15804        cx: &mut Context<Self>,
15805    ) {
15806        self.display_map.update(cx, |display_map, cx| {
15807            display_map.remove_blocks(block_ids, cx)
15808        });
15809        if let Some(autoscroll) = autoscroll {
15810            self.request_autoscroll(autoscroll, cx);
15811        }
15812        cx.notify();
15813    }
15814
15815    pub fn row_for_block(
15816        &self,
15817        block_id: CustomBlockId,
15818        cx: &mut Context<Self>,
15819    ) -> Option<DisplayRow> {
15820        self.display_map
15821            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15822    }
15823
15824    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15825        self.focused_block = Some(focused_block);
15826    }
15827
15828    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15829        self.focused_block.take()
15830    }
15831
15832    pub fn insert_creases(
15833        &mut self,
15834        creases: impl IntoIterator<Item = Crease<Anchor>>,
15835        cx: &mut Context<Self>,
15836    ) -> Vec<CreaseId> {
15837        self.display_map
15838            .update(cx, |map, cx| map.insert_creases(creases, cx))
15839    }
15840
15841    pub fn remove_creases(
15842        &mut self,
15843        ids: impl IntoIterator<Item = CreaseId>,
15844        cx: &mut Context<Self>,
15845    ) {
15846        self.display_map
15847            .update(cx, |map, cx| map.remove_creases(ids, cx));
15848    }
15849
15850    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15851        self.display_map
15852            .update(cx, |map, cx| map.snapshot(cx))
15853            .longest_row()
15854    }
15855
15856    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15857        self.display_map
15858            .update(cx, |map, cx| map.snapshot(cx))
15859            .max_point()
15860    }
15861
15862    pub fn text(&self, cx: &App) -> String {
15863        self.buffer.read(cx).read(cx).text()
15864    }
15865
15866    pub fn is_empty(&self, cx: &App) -> bool {
15867        self.buffer.read(cx).read(cx).is_empty()
15868    }
15869
15870    pub fn text_option(&self, cx: &App) -> Option<String> {
15871        let text = self.text(cx);
15872        let text = text.trim();
15873
15874        if text.is_empty() {
15875            return None;
15876        }
15877
15878        Some(text.to_string())
15879    }
15880
15881    pub fn set_text(
15882        &mut self,
15883        text: impl Into<Arc<str>>,
15884        window: &mut Window,
15885        cx: &mut Context<Self>,
15886    ) {
15887        self.transact(window, cx, |this, _, cx| {
15888            this.buffer
15889                .read(cx)
15890                .as_singleton()
15891                .expect("you can only call set_text on editors for singleton buffers")
15892                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15893        });
15894    }
15895
15896    pub fn display_text(&self, cx: &mut App) -> String {
15897        self.display_map
15898            .update(cx, |map, cx| map.snapshot(cx))
15899            .text()
15900    }
15901
15902    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15903        let mut wrap_guides = smallvec::smallvec![];
15904
15905        if self.show_wrap_guides == Some(false) {
15906            return wrap_guides;
15907        }
15908
15909        let settings = self.buffer.read(cx).language_settings(cx);
15910        if settings.show_wrap_guides {
15911            match self.soft_wrap_mode(cx) {
15912                SoftWrap::Column(soft_wrap) => {
15913                    wrap_guides.push((soft_wrap as usize, true));
15914                }
15915                SoftWrap::Bounded(soft_wrap) => {
15916                    wrap_guides.push((soft_wrap as usize, true));
15917                }
15918                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15919            }
15920            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15921        }
15922
15923        wrap_guides
15924    }
15925
15926    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15927        let settings = self.buffer.read(cx).language_settings(cx);
15928        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15929        match mode {
15930            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15931                SoftWrap::None
15932            }
15933            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15934            language_settings::SoftWrap::PreferredLineLength => {
15935                SoftWrap::Column(settings.preferred_line_length)
15936            }
15937            language_settings::SoftWrap::Bounded => {
15938                SoftWrap::Bounded(settings.preferred_line_length)
15939            }
15940        }
15941    }
15942
15943    pub fn set_soft_wrap_mode(
15944        &mut self,
15945        mode: language_settings::SoftWrap,
15946
15947        cx: &mut Context<Self>,
15948    ) {
15949        self.soft_wrap_mode_override = Some(mode);
15950        cx.notify();
15951    }
15952
15953    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15954        self.hard_wrap = hard_wrap;
15955        cx.notify();
15956    }
15957
15958    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15959        self.text_style_refinement = Some(style);
15960    }
15961
15962    /// called by the Element so we know what style we were most recently rendered with.
15963    pub(crate) fn set_style(
15964        &mut self,
15965        style: EditorStyle,
15966        window: &mut Window,
15967        cx: &mut Context<Self>,
15968    ) {
15969        let rem_size = window.rem_size();
15970        self.display_map.update(cx, |map, cx| {
15971            map.set_font(
15972                style.text.font(),
15973                style.text.font_size.to_pixels(rem_size),
15974                cx,
15975            )
15976        });
15977        self.style = Some(style);
15978    }
15979
15980    pub fn style(&self) -> Option<&EditorStyle> {
15981        self.style.as_ref()
15982    }
15983
15984    // Called by the element. This method is not designed to be called outside of the editor
15985    // element's layout code because it does not notify when rewrapping is computed synchronously.
15986    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15987        self.display_map
15988            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15989    }
15990
15991    pub fn set_soft_wrap(&mut self) {
15992        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15993    }
15994
15995    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15996        if self.soft_wrap_mode_override.is_some() {
15997            self.soft_wrap_mode_override.take();
15998        } else {
15999            let soft_wrap = match self.soft_wrap_mode(cx) {
16000                SoftWrap::GitDiff => return,
16001                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16002                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16003                    language_settings::SoftWrap::None
16004                }
16005            };
16006            self.soft_wrap_mode_override = Some(soft_wrap);
16007        }
16008        cx.notify();
16009    }
16010
16011    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16012        let Some(workspace) = self.workspace() else {
16013            return;
16014        };
16015        let fs = workspace.read(cx).app_state().fs.clone();
16016        let current_show = TabBarSettings::get_global(cx).show;
16017        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16018            setting.show = Some(!current_show);
16019        });
16020    }
16021
16022    pub fn toggle_indent_guides(
16023        &mut self,
16024        _: &ToggleIndentGuides,
16025        _: &mut Window,
16026        cx: &mut Context<Self>,
16027    ) {
16028        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16029            self.buffer
16030                .read(cx)
16031                .language_settings(cx)
16032                .indent_guides
16033                .enabled
16034        });
16035        self.show_indent_guides = Some(!currently_enabled);
16036        cx.notify();
16037    }
16038
16039    fn should_show_indent_guides(&self) -> Option<bool> {
16040        self.show_indent_guides
16041    }
16042
16043    pub fn toggle_line_numbers(
16044        &mut self,
16045        _: &ToggleLineNumbers,
16046        _: &mut Window,
16047        cx: &mut Context<Self>,
16048    ) {
16049        let mut editor_settings = EditorSettings::get_global(cx).clone();
16050        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16051        EditorSettings::override_global(editor_settings, cx);
16052    }
16053
16054    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16055        if let Some(show_line_numbers) = self.show_line_numbers {
16056            return show_line_numbers;
16057        }
16058        EditorSettings::get_global(cx).gutter.line_numbers
16059    }
16060
16061    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16062        self.use_relative_line_numbers
16063            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16064    }
16065
16066    pub fn toggle_relative_line_numbers(
16067        &mut self,
16068        _: &ToggleRelativeLineNumbers,
16069        _: &mut Window,
16070        cx: &mut Context<Self>,
16071    ) {
16072        let is_relative = self.should_use_relative_line_numbers(cx);
16073        self.set_relative_line_number(Some(!is_relative), cx)
16074    }
16075
16076    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16077        self.use_relative_line_numbers = is_relative;
16078        cx.notify();
16079    }
16080
16081    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16082        self.show_gutter = show_gutter;
16083        cx.notify();
16084    }
16085
16086    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16087        self.show_scrollbars = show_scrollbars;
16088        cx.notify();
16089    }
16090
16091    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16092        self.show_line_numbers = Some(show_line_numbers);
16093        cx.notify();
16094    }
16095
16096    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16097        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16098        cx.notify();
16099    }
16100
16101    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16102        self.show_code_actions = Some(show_code_actions);
16103        cx.notify();
16104    }
16105
16106    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16107        self.show_runnables = Some(show_runnables);
16108        cx.notify();
16109    }
16110
16111    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16112        self.show_breakpoints = Some(show_breakpoints);
16113        cx.notify();
16114    }
16115
16116    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16117        if self.display_map.read(cx).masked != masked {
16118            self.display_map.update(cx, |map, _| map.masked = masked);
16119        }
16120        cx.notify()
16121    }
16122
16123    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16124        self.show_wrap_guides = Some(show_wrap_guides);
16125        cx.notify();
16126    }
16127
16128    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16129        self.show_indent_guides = Some(show_indent_guides);
16130        cx.notify();
16131    }
16132
16133    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16134        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16135            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16136                if let Some(dir) = file.abs_path(cx).parent() {
16137                    return Some(dir.to_owned());
16138                }
16139            }
16140
16141            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16142                return Some(project_path.path.to_path_buf());
16143            }
16144        }
16145
16146        None
16147    }
16148
16149    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16150        self.active_excerpt(cx)?
16151            .1
16152            .read(cx)
16153            .file()
16154            .and_then(|f| f.as_local())
16155    }
16156
16157    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16158        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16159            let buffer = buffer.read(cx);
16160            if let Some(project_path) = buffer.project_path(cx) {
16161                let project = self.project.as_ref()?.read(cx);
16162                project.absolute_path(&project_path, cx)
16163            } else {
16164                buffer
16165                    .file()
16166                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16167            }
16168        })
16169    }
16170
16171    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16172        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16173            let project_path = buffer.read(cx).project_path(cx)?;
16174            let project = self.project.as_ref()?.read(cx);
16175            let entry = project.entry_for_path(&project_path, cx)?;
16176            let path = entry.path.to_path_buf();
16177            Some(path)
16178        })
16179    }
16180
16181    pub fn reveal_in_finder(
16182        &mut self,
16183        _: &RevealInFileManager,
16184        _window: &mut Window,
16185        cx: &mut Context<Self>,
16186    ) {
16187        if let Some(target) = self.target_file(cx) {
16188            cx.reveal_path(&target.abs_path(cx));
16189        }
16190    }
16191
16192    pub fn copy_path(
16193        &mut self,
16194        _: &zed_actions::workspace::CopyPath,
16195        _window: &mut Window,
16196        cx: &mut Context<Self>,
16197    ) {
16198        if let Some(path) = self.target_file_abs_path(cx) {
16199            if let Some(path) = path.to_str() {
16200                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16201            }
16202        }
16203    }
16204
16205    pub fn copy_relative_path(
16206        &mut self,
16207        _: &zed_actions::workspace::CopyRelativePath,
16208        _window: &mut Window,
16209        cx: &mut Context<Self>,
16210    ) {
16211        if let Some(path) = self.target_file_path(cx) {
16212            if let Some(path) = path.to_str() {
16213                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16214            }
16215        }
16216    }
16217
16218    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16219        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16220            buffer.read(cx).project_path(cx)
16221        } else {
16222            None
16223        }
16224    }
16225
16226    // Returns true if the editor handled a go-to-line request
16227    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16228        maybe!({
16229            let breakpoint_store = self.breakpoint_store.as_ref()?;
16230
16231            let Some((_, _, active_position)) =
16232                breakpoint_store.read(cx).active_position().cloned()
16233            else {
16234                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16235                return None;
16236            };
16237
16238            let snapshot = self
16239                .project
16240                .as_ref()?
16241                .read(cx)
16242                .buffer_for_id(active_position.buffer_id?, cx)?
16243                .read(cx)
16244                .snapshot();
16245
16246            let mut handled = false;
16247            for (id, ExcerptRange { context, .. }) in self
16248                .buffer
16249                .read(cx)
16250                .excerpts_for_buffer(active_position.buffer_id?, cx)
16251            {
16252                if context.start.cmp(&active_position, &snapshot).is_ge()
16253                    || context.end.cmp(&active_position, &snapshot).is_lt()
16254                {
16255                    continue;
16256                }
16257                let snapshot = self.buffer.read(cx).snapshot(cx);
16258                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16259
16260                handled = true;
16261                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16262                self.go_to_line::<DebugCurrentRowHighlight>(
16263                    multibuffer_anchor,
16264                    Some(cx.theme().colors().editor_debugger_active_line_background),
16265                    window,
16266                    cx,
16267                );
16268
16269                cx.notify();
16270            }
16271            handled.then_some(())
16272        })
16273        .is_some()
16274    }
16275
16276    pub fn copy_file_name_without_extension(
16277        &mut self,
16278        _: &CopyFileNameWithoutExtension,
16279        _: &mut Window,
16280        cx: &mut Context<Self>,
16281    ) {
16282        if let Some(file) = self.target_file(cx) {
16283            if let Some(file_stem) = file.path().file_stem() {
16284                if let Some(name) = file_stem.to_str() {
16285                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16286                }
16287            }
16288        }
16289    }
16290
16291    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16292        if let Some(file) = self.target_file(cx) {
16293            if let Some(file_name) = file.path().file_name() {
16294                if let Some(name) = file_name.to_str() {
16295                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16296                }
16297            }
16298        }
16299    }
16300
16301    pub fn toggle_git_blame(
16302        &mut self,
16303        _: &::git::Blame,
16304        window: &mut Window,
16305        cx: &mut Context<Self>,
16306    ) {
16307        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16308
16309        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16310            self.start_git_blame(true, window, cx);
16311        }
16312
16313        cx.notify();
16314    }
16315
16316    pub fn toggle_git_blame_inline(
16317        &mut self,
16318        _: &ToggleGitBlameInline,
16319        window: &mut Window,
16320        cx: &mut Context<Self>,
16321    ) {
16322        self.toggle_git_blame_inline_internal(true, window, cx);
16323        cx.notify();
16324    }
16325
16326    pub fn open_git_blame_commit(
16327        &mut self,
16328        _: &OpenGitBlameCommit,
16329        window: &mut Window,
16330        cx: &mut Context<Self>,
16331    ) {
16332        self.open_git_blame_commit_internal(window, cx);
16333    }
16334
16335    fn open_git_blame_commit_internal(
16336        &mut self,
16337        window: &mut Window,
16338        cx: &mut Context<Self>,
16339    ) -> Option<()> {
16340        let blame = self.blame.as_ref()?;
16341        let snapshot = self.snapshot(window, cx);
16342        let cursor = self.selections.newest::<Point>(cx).head();
16343        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16344        let blame_entry = blame
16345            .update(cx, |blame, cx| {
16346                blame
16347                    .blame_for_rows(
16348                        &[RowInfo {
16349                            buffer_id: Some(buffer.remote_id()),
16350                            buffer_row: Some(point.row),
16351                            ..Default::default()
16352                        }],
16353                        cx,
16354                    )
16355                    .next()
16356            })
16357            .flatten()?;
16358        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16359        let repo = blame.read(cx).repository(cx)?;
16360        let workspace = self.workspace()?.downgrade();
16361        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16362        None
16363    }
16364
16365    pub fn git_blame_inline_enabled(&self) -> bool {
16366        self.git_blame_inline_enabled
16367    }
16368
16369    pub fn toggle_selection_menu(
16370        &mut self,
16371        _: &ToggleSelectionMenu,
16372        _: &mut Window,
16373        cx: &mut Context<Self>,
16374    ) {
16375        self.show_selection_menu = self
16376            .show_selection_menu
16377            .map(|show_selections_menu| !show_selections_menu)
16378            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16379
16380        cx.notify();
16381    }
16382
16383    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16384        self.show_selection_menu
16385            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16386    }
16387
16388    fn start_git_blame(
16389        &mut self,
16390        user_triggered: bool,
16391        window: &mut Window,
16392        cx: &mut Context<Self>,
16393    ) {
16394        if let Some(project) = self.project.as_ref() {
16395            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16396                return;
16397            };
16398
16399            if buffer.read(cx).file().is_none() {
16400                return;
16401            }
16402
16403            let focused = self.focus_handle(cx).contains_focused(window, cx);
16404
16405            let project = project.clone();
16406            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16407            self.blame_subscription =
16408                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16409            self.blame = Some(blame);
16410        }
16411    }
16412
16413    fn toggle_git_blame_inline_internal(
16414        &mut self,
16415        user_triggered: bool,
16416        window: &mut Window,
16417        cx: &mut Context<Self>,
16418    ) {
16419        if self.git_blame_inline_enabled {
16420            self.git_blame_inline_enabled = false;
16421            self.show_git_blame_inline = false;
16422            self.show_git_blame_inline_delay_task.take();
16423        } else {
16424            self.git_blame_inline_enabled = true;
16425            self.start_git_blame_inline(user_triggered, window, cx);
16426        }
16427
16428        cx.notify();
16429    }
16430
16431    fn start_git_blame_inline(
16432        &mut self,
16433        user_triggered: bool,
16434        window: &mut Window,
16435        cx: &mut Context<Self>,
16436    ) {
16437        self.start_git_blame(user_triggered, window, cx);
16438
16439        if ProjectSettings::get_global(cx)
16440            .git
16441            .inline_blame_delay()
16442            .is_some()
16443        {
16444            self.start_inline_blame_timer(window, cx);
16445        } else {
16446            self.show_git_blame_inline = true
16447        }
16448    }
16449
16450    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16451        self.blame.as_ref()
16452    }
16453
16454    pub fn show_git_blame_gutter(&self) -> bool {
16455        self.show_git_blame_gutter
16456    }
16457
16458    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16459        self.show_git_blame_gutter && self.has_blame_entries(cx)
16460    }
16461
16462    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16463        self.show_git_blame_inline
16464            && (self.focus_handle.is_focused(window)
16465                || self
16466                    .git_blame_inline_tooltip
16467                    .as_ref()
16468                    .and_then(|t| t.upgrade())
16469                    .is_some())
16470            && !self.newest_selection_head_on_empty_line(cx)
16471            && self.has_blame_entries(cx)
16472    }
16473
16474    fn has_blame_entries(&self, cx: &App) -> bool {
16475        self.blame()
16476            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16477    }
16478
16479    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16480        let cursor_anchor = self.selections.newest_anchor().head();
16481
16482        let snapshot = self.buffer.read(cx).snapshot(cx);
16483        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16484
16485        snapshot.line_len(buffer_row) == 0
16486    }
16487
16488    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16489        let buffer_and_selection = maybe!({
16490            let selection = self.selections.newest::<Point>(cx);
16491            let selection_range = selection.range();
16492
16493            let multi_buffer = self.buffer().read(cx);
16494            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16495            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16496
16497            let (buffer, range, _) = if selection.reversed {
16498                buffer_ranges.first()
16499            } else {
16500                buffer_ranges.last()
16501            }?;
16502
16503            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16504                ..text::ToPoint::to_point(&range.end, &buffer).row;
16505            Some((
16506                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16507                selection,
16508            ))
16509        });
16510
16511        let Some((buffer, selection)) = buffer_and_selection else {
16512            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16513        };
16514
16515        let Some(project) = self.project.as_ref() else {
16516            return Task::ready(Err(anyhow!("editor does not have project")));
16517        };
16518
16519        project.update(cx, |project, cx| {
16520            project.get_permalink_to_line(&buffer, selection, cx)
16521        })
16522    }
16523
16524    pub fn copy_permalink_to_line(
16525        &mut self,
16526        _: &CopyPermalinkToLine,
16527        window: &mut Window,
16528        cx: &mut Context<Self>,
16529    ) {
16530        let permalink_task = self.get_permalink_to_line(cx);
16531        let workspace = self.workspace();
16532
16533        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16534            Ok(permalink) => {
16535                cx.update(|_, cx| {
16536                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16537                })
16538                .ok();
16539            }
16540            Err(err) => {
16541                let message = format!("Failed to copy permalink: {err}");
16542
16543                Err::<(), anyhow::Error>(err).log_err();
16544
16545                if let Some(workspace) = workspace {
16546                    workspace
16547                        .update_in(cx, |workspace, _, cx| {
16548                            struct CopyPermalinkToLine;
16549
16550                            workspace.show_toast(
16551                                Toast::new(
16552                                    NotificationId::unique::<CopyPermalinkToLine>(),
16553                                    message,
16554                                ),
16555                                cx,
16556                            )
16557                        })
16558                        .ok();
16559                }
16560            }
16561        })
16562        .detach();
16563    }
16564
16565    pub fn copy_file_location(
16566        &mut self,
16567        _: &CopyFileLocation,
16568        _: &mut Window,
16569        cx: &mut Context<Self>,
16570    ) {
16571        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16572        if let Some(file) = self.target_file(cx) {
16573            if let Some(path) = file.path().to_str() {
16574                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16575            }
16576        }
16577    }
16578
16579    pub fn open_permalink_to_line(
16580        &mut self,
16581        _: &OpenPermalinkToLine,
16582        window: &mut Window,
16583        cx: &mut Context<Self>,
16584    ) {
16585        let permalink_task = self.get_permalink_to_line(cx);
16586        let workspace = self.workspace();
16587
16588        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16589            Ok(permalink) => {
16590                cx.update(|_, cx| {
16591                    cx.open_url(permalink.as_ref());
16592                })
16593                .ok();
16594            }
16595            Err(err) => {
16596                let message = format!("Failed to open permalink: {err}");
16597
16598                Err::<(), anyhow::Error>(err).log_err();
16599
16600                if let Some(workspace) = workspace {
16601                    workspace
16602                        .update(cx, |workspace, cx| {
16603                            struct OpenPermalinkToLine;
16604
16605                            workspace.show_toast(
16606                                Toast::new(
16607                                    NotificationId::unique::<OpenPermalinkToLine>(),
16608                                    message,
16609                                ),
16610                                cx,
16611                            )
16612                        })
16613                        .ok();
16614                }
16615            }
16616        })
16617        .detach();
16618    }
16619
16620    pub fn insert_uuid_v4(
16621        &mut self,
16622        _: &InsertUuidV4,
16623        window: &mut Window,
16624        cx: &mut Context<Self>,
16625    ) {
16626        self.insert_uuid(UuidVersion::V4, window, cx);
16627    }
16628
16629    pub fn insert_uuid_v7(
16630        &mut self,
16631        _: &InsertUuidV7,
16632        window: &mut Window,
16633        cx: &mut Context<Self>,
16634    ) {
16635        self.insert_uuid(UuidVersion::V7, window, cx);
16636    }
16637
16638    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16639        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16640        self.transact(window, cx, |this, window, cx| {
16641            let edits = this
16642                .selections
16643                .all::<Point>(cx)
16644                .into_iter()
16645                .map(|selection| {
16646                    let uuid = match version {
16647                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16648                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16649                    };
16650
16651                    (selection.range(), uuid.to_string())
16652                });
16653            this.edit(edits, cx);
16654            this.refresh_inline_completion(true, false, window, cx);
16655        });
16656    }
16657
16658    pub fn open_selections_in_multibuffer(
16659        &mut self,
16660        _: &OpenSelectionsInMultibuffer,
16661        window: &mut Window,
16662        cx: &mut Context<Self>,
16663    ) {
16664        let multibuffer = self.buffer.read(cx);
16665
16666        let Some(buffer) = multibuffer.as_singleton() else {
16667            return;
16668        };
16669
16670        let Some(workspace) = self.workspace() else {
16671            return;
16672        };
16673
16674        let locations = self
16675            .selections
16676            .disjoint_anchors()
16677            .iter()
16678            .map(|range| Location {
16679                buffer: buffer.clone(),
16680                range: range.start.text_anchor..range.end.text_anchor,
16681            })
16682            .collect::<Vec<_>>();
16683
16684        let title = multibuffer.title(cx).to_string();
16685
16686        cx.spawn_in(window, async move |_, cx| {
16687            workspace.update_in(cx, |workspace, window, cx| {
16688                Self::open_locations_in_multibuffer(
16689                    workspace,
16690                    locations,
16691                    format!("Selections for '{title}'"),
16692                    false,
16693                    MultibufferSelectionMode::All,
16694                    window,
16695                    cx,
16696                );
16697            })
16698        })
16699        .detach();
16700    }
16701
16702    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16703    /// last highlight added will be used.
16704    ///
16705    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16706    pub fn highlight_rows<T: 'static>(
16707        &mut self,
16708        range: Range<Anchor>,
16709        color: Hsla,
16710        should_autoscroll: bool,
16711        cx: &mut Context<Self>,
16712    ) {
16713        let snapshot = self.buffer().read(cx).snapshot(cx);
16714        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16715        let ix = row_highlights.binary_search_by(|highlight| {
16716            Ordering::Equal
16717                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16718                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16719        });
16720
16721        if let Err(mut ix) = ix {
16722            let index = post_inc(&mut self.highlight_order);
16723
16724            // If this range intersects with the preceding highlight, then merge it with
16725            // the preceding highlight. Otherwise insert a new highlight.
16726            let mut merged = false;
16727            if ix > 0 {
16728                let prev_highlight = &mut row_highlights[ix - 1];
16729                if prev_highlight
16730                    .range
16731                    .end
16732                    .cmp(&range.start, &snapshot)
16733                    .is_ge()
16734                {
16735                    ix -= 1;
16736                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16737                        prev_highlight.range.end = range.end;
16738                    }
16739                    merged = true;
16740                    prev_highlight.index = index;
16741                    prev_highlight.color = color;
16742                    prev_highlight.should_autoscroll = should_autoscroll;
16743                }
16744            }
16745
16746            if !merged {
16747                row_highlights.insert(
16748                    ix,
16749                    RowHighlight {
16750                        range: range.clone(),
16751                        index,
16752                        color,
16753                        should_autoscroll,
16754                    },
16755                );
16756            }
16757
16758            // If any of the following highlights intersect with this one, merge them.
16759            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16760                let highlight = &row_highlights[ix];
16761                if next_highlight
16762                    .range
16763                    .start
16764                    .cmp(&highlight.range.end, &snapshot)
16765                    .is_le()
16766                {
16767                    if next_highlight
16768                        .range
16769                        .end
16770                        .cmp(&highlight.range.end, &snapshot)
16771                        .is_gt()
16772                    {
16773                        row_highlights[ix].range.end = next_highlight.range.end;
16774                    }
16775                    row_highlights.remove(ix + 1);
16776                } else {
16777                    break;
16778                }
16779            }
16780        }
16781    }
16782
16783    /// Remove any highlighted row ranges of the given type that intersect the
16784    /// given ranges.
16785    pub fn remove_highlighted_rows<T: 'static>(
16786        &mut self,
16787        ranges_to_remove: Vec<Range<Anchor>>,
16788        cx: &mut Context<Self>,
16789    ) {
16790        let snapshot = self.buffer().read(cx).snapshot(cx);
16791        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16792        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16793        row_highlights.retain(|highlight| {
16794            while let Some(range_to_remove) = ranges_to_remove.peek() {
16795                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16796                    Ordering::Less | Ordering::Equal => {
16797                        ranges_to_remove.next();
16798                    }
16799                    Ordering::Greater => {
16800                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16801                            Ordering::Less | Ordering::Equal => {
16802                                return false;
16803                            }
16804                            Ordering::Greater => break,
16805                        }
16806                    }
16807                }
16808            }
16809
16810            true
16811        })
16812    }
16813
16814    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16815    pub fn clear_row_highlights<T: 'static>(&mut self) {
16816        self.highlighted_rows.remove(&TypeId::of::<T>());
16817    }
16818
16819    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16820    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16821        self.highlighted_rows
16822            .get(&TypeId::of::<T>())
16823            .map_or(&[] as &[_], |vec| vec.as_slice())
16824            .iter()
16825            .map(|highlight| (highlight.range.clone(), highlight.color))
16826    }
16827
16828    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16829    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16830    /// Allows to ignore certain kinds of highlights.
16831    pub fn highlighted_display_rows(
16832        &self,
16833        window: &mut Window,
16834        cx: &mut App,
16835    ) -> BTreeMap<DisplayRow, LineHighlight> {
16836        let snapshot = self.snapshot(window, cx);
16837        let mut used_highlight_orders = HashMap::default();
16838        self.highlighted_rows
16839            .iter()
16840            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16841            .fold(
16842                BTreeMap::<DisplayRow, LineHighlight>::new(),
16843                |mut unique_rows, highlight| {
16844                    let start = highlight.range.start.to_display_point(&snapshot);
16845                    let end = highlight.range.end.to_display_point(&snapshot);
16846                    let start_row = start.row().0;
16847                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16848                        && end.column() == 0
16849                    {
16850                        end.row().0.saturating_sub(1)
16851                    } else {
16852                        end.row().0
16853                    };
16854                    for row in start_row..=end_row {
16855                        let used_index =
16856                            used_highlight_orders.entry(row).or_insert(highlight.index);
16857                        if highlight.index >= *used_index {
16858                            *used_index = highlight.index;
16859                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16860                        }
16861                    }
16862                    unique_rows
16863                },
16864            )
16865    }
16866
16867    pub fn highlighted_display_row_for_autoscroll(
16868        &self,
16869        snapshot: &DisplaySnapshot,
16870    ) -> Option<DisplayRow> {
16871        self.highlighted_rows
16872            .values()
16873            .flat_map(|highlighted_rows| highlighted_rows.iter())
16874            .filter_map(|highlight| {
16875                if highlight.should_autoscroll {
16876                    Some(highlight.range.start.to_display_point(snapshot).row())
16877                } else {
16878                    None
16879                }
16880            })
16881            .min()
16882    }
16883
16884    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16885        self.highlight_background::<SearchWithinRange>(
16886            ranges,
16887            |colors| colors.editor_document_highlight_read_background,
16888            cx,
16889        )
16890    }
16891
16892    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16893        self.breadcrumb_header = Some(new_header);
16894    }
16895
16896    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16897        self.clear_background_highlights::<SearchWithinRange>(cx);
16898    }
16899
16900    pub fn highlight_background<T: 'static>(
16901        &mut self,
16902        ranges: &[Range<Anchor>],
16903        color_fetcher: fn(&ThemeColors) -> Hsla,
16904        cx: &mut Context<Self>,
16905    ) {
16906        self.background_highlights
16907            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16908        self.scrollbar_marker_state.dirty = true;
16909        cx.notify();
16910    }
16911
16912    pub fn clear_background_highlights<T: 'static>(
16913        &mut self,
16914        cx: &mut Context<Self>,
16915    ) -> Option<BackgroundHighlight> {
16916        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16917        if !text_highlights.1.is_empty() {
16918            self.scrollbar_marker_state.dirty = true;
16919            cx.notify();
16920        }
16921        Some(text_highlights)
16922    }
16923
16924    pub fn highlight_gutter<T: 'static>(
16925        &mut self,
16926        ranges: &[Range<Anchor>],
16927        color_fetcher: fn(&App) -> Hsla,
16928        cx: &mut Context<Self>,
16929    ) {
16930        self.gutter_highlights
16931            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16932        cx.notify();
16933    }
16934
16935    pub fn clear_gutter_highlights<T: 'static>(
16936        &mut self,
16937        cx: &mut Context<Self>,
16938    ) -> Option<GutterHighlight> {
16939        cx.notify();
16940        self.gutter_highlights.remove(&TypeId::of::<T>())
16941    }
16942
16943    #[cfg(feature = "test-support")]
16944    pub fn all_text_background_highlights(
16945        &self,
16946        window: &mut Window,
16947        cx: &mut Context<Self>,
16948    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16949        let snapshot = self.snapshot(window, cx);
16950        let buffer = &snapshot.buffer_snapshot;
16951        let start = buffer.anchor_before(0);
16952        let end = buffer.anchor_after(buffer.len());
16953        let theme = cx.theme().colors();
16954        self.background_highlights_in_range(start..end, &snapshot, theme)
16955    }
16956
16957    #[cfg(feature = "test-support")]
16958    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16959        let snapshot = self.buffer().read(cx).snapshot(cx);
16960
16961        let highlights = self
16962            .background_highlights
16963            .get(&TypeId::of::<items::BufferSearchHighlights>());
16964
16965        if let Some((_color, ranges)) = highlights {
16966            ranges
16967                .iter()
16968                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16969                .collect_vec()
16970        } else {
16971            vec![]
16972        }
16973    }
16974
16975    fn document_highlights_for_position<'a>(
16976        &'a self,
16977        position: Anchor,
16978        buffer: &'a MultiBufferSnapshot,
16979    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16980        let read_highlights = self
16981            .background_highlights
16982            .get(&TypeId::of::<DocumentHighlightRead>())
16983            .map(|h| &h.1);
16984        let write_highlights = self
16985            .background_highlights
16986            .get(&TypeId::of::<DocumentHighlightWrite>())
16987            .map(|h| &h.1);
16988        let left_position = position.bias_left(buffer);
16989        let right_position = position.bias_right(buffer);
16990        read_highlights
16991            .into_iter()
16992            .chain(write_highlights)
16993            .flat_map(move |ranges| {
16994                let start_ix = match ranges.binary_search_by(|probe| {
16995                    let cmp = probe.end.cmp(&left_position, buffer);
16996                    if cmp.is_ge() {
16997                        Ordering::Greater
16998                    } else {
16999                        Ordering::Less
17000                    }
17001                }) {
17002                    Ok(i) | Err(i) => i,
17003                };
17004
17005                ranges[start_ix..]
17006                    .iter()
17007                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17008            })
17009    }
17010
17011    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17012        self.background_highlights
17013            .get(&TypeId::of::<T>())
17014            .map_or(false, |(_, highlights)| !highlights.is_empty())
17015    }
17016
17017    pub fn background_highlights_in_range(
17018        &self,
17019        search_range: Range<Anchor>,
17020        display_snapshot: &DisplaySnapshot,
17021        theme: &ThemeColors,
17022    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17023        let mut results = Vec::new();
17024        for (color_fetcher, ranges) in self.background_highlights.values() {
17025            let color = color_fetcher(theme);
17026            let start_ix = match ranges.binary_search_by(|probe| {
17027                let cmp = probe
17028                    .end
17029                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17030                if cmp.is_gt() {
17031                    Ordering::Greater
17032                } else {
17033                    Ordering::Less
17034                }
17035            }) {
17036                Ok(i) | Err(i) => i,
17037            };
17038            for range in &ranges[start_ix..] {
17039                if range
17040                    .start
17041                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17042                    .is_ge()
17043                {
17044                    break;
17045                }
17046
17047                let start = range.start.to_display_point(display_snapshot);
17048                let end = range.end.to_display_point(display_snapshot);
17049                results.push((start..end, color))
17050            }
17051        }
17052        results
17053    }
17054
17055    pub fn background_highlight_row_ranges<T: 'static>(
17056        &self,
17057        search_range: Range<Anchor>,
17058        display_snapshot: &DisplaySnapshot,
17059        count: usize,
17060    ) -> Vec<RangeInclusive<DisplayPoint>> {
17061        let mut results = Vec::new();
17062        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17063            return vec![];
17064        };
17065
17066        let start_ix = match ranges.binary_search_by(|probe| {
17067            let cmp = probe
17068                .end
17069                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17070            if cmp.is_gt() {
17071                Ordering::Greater
17072            } else {
17073                Ordering::Less
17074            }
17075        }) {
17076            Ok(i) | Err(i) => i,
17077        };
17078        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17079            if let (Some(start_display), Some(end_display)) = (start, end) {
17080                results.push(
17081                    start_display.to_display_point(display_snapshot)
17082                        ..=end_display.to_display_point(display_snapshot),
17083                );
17084            }
17085        };
17086        let mut start_row: Option<Point> = None;
17087        let mut end_row: Option<Point> = None;
17088        if ranges.len() > count {
17089            return Vec::new();
17090        }
17091        for range in &ranges[start_ix..] {
17092            if range
17093                .start
17094                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17095                .is_ge()
17096            {
17097                break;
17098            }
17099            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17100            if let Some(current_row) = &end_row {
17101                if end.row == current_row.row {
17102                    continue;
17103                }
17104            }
17105            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17106            if start_row.is_none() {
17107                assert_eq!(end_row, None);
17108                start_row = Some(start);
17109                end_row = Some(end);
17110                continue;
17111            }
17112            if let Some(current_end) = end_row.as_mut() {
17113                if start.row > current_end.row + 1 {
17114                    push_region(start_row, end_row);
17115                    start_row = Some(start);
17116                    end_row = Some(end);
17117                } else {
17118                    // Merge two hunks.
17119                    *current_end = end;
17120                }
17121            } else {
17122                unreachable!();
17123            }
17124        }
17125        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17126        push_region(start_row, end_row);
17127        results
17128    }
17129
17130    pub fn gutter_highlights_in_range(
17131        &self,
17132        search_range: Range<Anchor>,
17133        display_snapshot: &DisplaySnapshot,
17134        cx: &App,
17135    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17136        let mut results = Vec::new();
17137        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17138            let color = color_fetcher(cx);
17139            let start_ix = match ranges.binary_search_by(|probe| {
17140                let cmp = probe
17141                    .end
17142                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17143                if cmp.is_gt() {
17144                    Ordering::Greater
17145                } else {
17146                    Ordering::Less
17147                }
17148            }) {
17149                Ok(i) | Err(i) => i,
17150            };
17151            for range in &ranges[start_ix..] {
17152                if range
17153                    .start
17154                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17155                    .is_ge()
17156                {
17157                    break;
17158                }
17159
17160                let start = range.start.to_display_point(display_snapshot);
17161                let end = range.end.to_display_point(display_snapshot);
17162                results.push((start..end, color))
17163            }
17164        }
17165        results
17166    }
17167
17168    /// Get the text ranges corresponding to the redaction query
17169    pub fn redacted_ranges(
17170        &self,
17171        search_range: Range<Anchor>,
17172        display_snapshot: &DisplaySnapshot,
17173        cx: &App,
17174    ) -> Vec<Range<DisplayPoint>> {
17175        display_snapshot
17176            .buffer_snapshot
17177            .redacted_ranges(search_range, |file| {
17178                if let Some(file) = file {
17179                    file.is_private()
17180                        && EditorSettings::get(
17181                            Some(SettingsLocation {
17182                                worktree_id: file.worktree_id(cx),
17183                                path: file.path().as_ref(),
17184                            }),
17185                            cx,
17186                        )
17187                        .redact_private_values
17188                } else {
17189                    false
17190                }
17191            })
17192            .map(|range| {
17193                range.start.to_display_point(display_snapshot)
17194                    ..range.end.to_display_point(display_snapshot)
17195            })
17196            .collect()
17197    }
17198
17199    pub fn highlight_text<T: 'static>(
17200        &mut self,
17201        ranges: Vec<Range<Anchor>>,
17202        style: HighlightStyle,
17203        cx: &mut Context<Self>,
17204    ) {
17205        self.display_map.update(cx, |map, _| {
17206            map.highlight_text(TypeId::of::<T>(), ranges, style)
17207        });
17208        cx.notify();
17209    }
17210
17211    pub(crate) fn highlight_inlays<T: 'static>(
17212        &mut self,
17213        highlights: Vec<InlayHighlight>,
17214        style: HighlightStyle,
17215        cx: &mut Context<Self>,
17216    ) {
17217        self.display_map.update(cx, |map, _| {
17218            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17219        });
17220        cx.notify();
17221    }
17222
17223    pub fn text_highlights<'a, T: 'static>(
17224        &'a self,
17225        cx: &'a App,
17226    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17227        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17228    }
17229
17230    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17231        let cleared = self
17232            .display_map
17233            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17234        if cleared {
17235            cx.notify();
17236        }
17237    }
17238
17239    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17240        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17241            && self.focus_handle.is_focused(window)
17242    }
17243
17244    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17245        self.show_cursor_when_unfocused = is_enabled;
17246        cx.notify();
17247    }
17248
17249    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17250        cx.notify();
17251    }
17252
17253    fn on_buffer_event(
17254        &mut self,
17255        multibuffer: &Entity<MultiBuffer>,
17256        event: &multi_buffer::Event,
17257        window: &mut Window,
17258        cx: &mut Context<Self>,
17259    ) {
17260        match event {
17261            multi_buffer::Event::Edited {
17262                singleton_buffer_edited,
17263                edited_buffer: buffer_edited,
17264            } => {
17265                self.scrollbar_marker_state.dirty = true;
17266                self.active_indent_guides_state.dirty = true;
17267                self.refresh_active_diagnostics(cx);
17268                self.refresh_code_actions(window, cx);
17269                if self.has_active_inline_completion() {
17270                    self.update_visible_inline_completion(window, cx);
17271                }
17272                if let Some(buffer) = buffer_edited {
17273                    let buffer_id = buffer.read(cx).remote_id();
17274                    if !self.registered_buffers.contains_key(&buffer_id) {
17275                        if let Some(project) = self.project.as_ref() {
17276                            project.update(cx, |project, cx| {
17277                                self.registered_buffers.insert(
17278                                    buffer_id,
17279                                    project.register_buffer_with_language_servers(&buffer, cx),
17280                                );
17281                            })
17282                        }
17283                    }
17284                }
17285                cx.emit(EditorEvent::BufferEdited);
17286                cx.emit(SearchEvent::MatchesInvalidated);
17287                if *singleton_buffer_edited {
17288                    if let Some(project) = &self.project {
17289                        #[allow(clippy::mutable_key_type)]
17290                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17291                            multibuffer
17292                                .all_buffers()
17293                                .into_iter()
17294                                .filter_map(|buffer| {
17295                                    buffer.update(cx, |buffer, cx| {
17296                                        let language = buffer.language()?;
17297                                        let should_discard = project.update(cx, |project, cx| {
17298                                            project.is_local()
17299                                                && !project.has_language_servers_for(buffer, cx)
17300                                        });
17301                                        should_discard.not().then_some(language.clone())
17302                                    })
17303                                })
17304                                .collect::<HashSet<_>>()
17305                        });
17306                        if !languages_affected.is_empty() {
17307                            self.refresh_inlay_hints(
17308                                InlayHintRefreshReason::BufferEdited(languages_affected),
17309                                cx,
17310                            );
17311                        }
17312                    }
17313                }
17314
17315                let Some(project) = &self.project else { return };
17316                let (telemetry, is_via_ssh) = {
17317                    let project = project.read(cx);
17318                    let telemetry = project.client().telemetry().clone();
17319                    let is_via_ssh = project.is_via_ssh();
17320                    (telemetry, is_via_ssh)
17321                };
17322                refresh_linked_ranges(self, window, cx);
17323                telemetry.log_edit_event("editor", is_via_ssh);
17324            }
17325            multi_buffer::Event::ExcerptsAdded {
17326                buffer,
17327                predecessor,
17328                excerpts,
17329            } => {
17330                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17331                let buffer_id = buffer.read(cx).remote_id();
17332                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17333                    if let Some(project) = &self.project {
17334                        get_uncommitted_diff_for_buffer(
17335                            project,
17336                            [buffer.clone()],
17337                            self.buffer.clone(),
17338                            cx,
17339                        )
17340                        .detach();
17341                    }
17342                }
17343                cx.emit(EditorEvent::ExcerptsAdded {
17344                    buffer: buffer.clone(),
17345                    predecessor: *predecessor,
17346                    excerpts: excerpts.clone(),
17347                });
17348                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17349            }
17350            multi_buffer::Event::ExcerptsRemoved { ids } => {
17351                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17352                let buffer = self.buffer.read(cx);
17353                self.registered_buffers
17354                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17355                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17356                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17357            }
17358            multi_buffer::Event::ExcerptsEdited {
17359                excerpt_ids,
17360                buffer_ids,
17361            } => {
17362                self.display_map.update(cx, |map, cx| {
17363                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17364                });
17365                cx.emit(EditorEvent::ExcerptsEdited {
17366                    ids: excerpt_ids.clone(),
17367                })
17368            }
17369            multi_buffer::Event::ExcerptsExpanded { ids } => {
17370                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17371                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17372            }
17373            multi_buffer::Event::Reparsed(buffer_id) => {
17374                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17375                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17376
17377                cx.emit(EditorEvent::Reparsed(*buffer_id));
17378            }
17379            multi_buffer::Event::DiffHunksToggled => {
17380                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17381            }
17382            multi_buffer::Event::LanguageChanged(buffer_id) => {
17383                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17384                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17385                cx.emit(EditorEvent::Reparsed(*buffer_id));
17386                cx.notify();
17387            }
17388            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17389            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17390            multi_buffer::Event::FileHandleChanged
17391            | multi_buffer::Event::Reloaded
17392            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17393            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17394            multi_buffer::Event::DiagnosticsUpdated => {
17395                self.refresh_active_diagnostics(cx);
17396                self.refresh_inline_diagnostics(true, window, cx);
17397                self.scrollbar_marker_state.dirty = true;
17398                cx.notify();
17399            }
17400            _ => {}
17401        };
17402    }
17403
17404    fn on_display_map_changed(
17405        &mut self,
17406        _: Entity<DisplayMap>,
17407        _: &mut Window,
17408        cx: &mut Context<Self>,
17409    ) {
17410        cx.notify();
17411    }
17412
17413    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17414        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17415        self.update_edit_prediction_settings(cx);
17416        self.refresh_inline_completion(true, false, window, cx);
17417        self.refresh_inlay_hints(
17418            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17419                self.selections.newest_anchor().head(),
17420                &self.buffer.read(cx).snapshot(cx),
17421                cx,
17422            )),
17423            cx,
17424        );
17425
17426        let old_cursor_shape = self.cursor_shape;
17427
17428        {
17429            let editor_settings = EditorSettings::get_global(cx);
17430            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17431            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17432            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17433            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17434        }
17435
17436        if old_cursor_shape != self.cursor_shape {
17437            cx.emit(EditorEvent::CursorShapeChanged);
17438        }
17439
17440        let project_settings = ProjectSettings::get_global(cx);
17441        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17442
17443        if self.mode.is_full() {
17444            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17445            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17446            if self.show_inline_diagnostics != show_inline_diagnostics {
17447                self.show_inline_diagnostics = show_inline_diagnostics;
17448                self.refresh_inline_diagnostics(false, window, cx);
17449            }
17450
17451            if self.git_blame_inline_enabled != inline_blame_enabled {
17452                self.toggle_git_blame_inline_internal(false, window, cx);
17453            }
17454        }
17455
17456        cx.notify();
17457    }
17458
17459    pub fn set_searchable(&mut self, searchable: bool) {
17460        self.searchable = searchable;
17461    }
17462
17463    pub fn searchable(&self) -> bool {
17464        self.searchable
17465    }
17466
17467    fn open_proposed_changes_editor(
17468        &mut self,
17469        _: &OpenProposedChangesEditor,
17470        window: &mut Window,
17471        cx: &mut Context<Self>,
17472    ) {
17473        let Some(workspace) = self.workspace() else {
17474            cx.propagate();
17475            return;
17476        };
17477
17478        let selections = self.selections.all::<usize>(cx);
17479        let multi_buffer = self.buffer.read(cx);
17480        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17481        let mut new_selections_by_buffer = HashMap::default();
17482        for selection in selections {
17483            for (buffer, range, _) in
17484                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17485            {
17486                let mut range = range.to_point(buffer);
17487                range.start.column = 0;
17488                range.end.column = buffer.line_len(range.end.row);
17489                new_selections_by_buffer
17490                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17491                    .or_insert(Vec::new())
17492                    .push(range)
17493            }
17494        }
17495
17496        let proposed_changes_buffers = new_selections_by_buffer
17497            .into_iter()
17498            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17499            .collect::<Vec<_>>();
17500        let proposed_changes_editor = cx.new(|cx| {
17501            ProposedChangesEditor::new(
17502                "Proposed changes",
17503                proposed_changes_buffers,
17504                self.project.clone(),
17505                window,
17506                cx,
17507            )
17508        });
17509
17510        window.defer(cx, move |window, cx| {
17511            workspace.update(cx, |workspace, cx| {
17512                workspace.active_pane().update(cx, |pane, cx| {
17513                    pane.add_item(
17514                        Box::new(proposed_changes_editor),
17515                        true,
17516                        true,
17517                        None,
17518                        window,
17519                        cx,
17520                    );
17521                });
17522            });
17523        });
17524    }
17525
17526    pub fn open_excerpts_in_split(
17527        &mut self,
17528        _: &OpenExcerptsSplit,
17529        window: &mut Window,
17530        cx: &mut Context<Self>,
17531    ) {
17532        self.open_excerpts_common(None, true, window, cx)
17533    }
17534
17535    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17536        self.open_excerpts_common(None, false, window, cx)
17537    }
17538
17539    fn open_excerpts_common(
17540        &mut self,
17541        jump_data: Option<JumpData>,
17542        split: bool,
17543        window: &mut Window,
17544        cx: &mut Context<Self>,
17545    ) {
17546        let Some(workspace) = self.workspace() else {
17547            cx.propagate();
17548            return;
17549        };
17550
17551        if self.buffer.read(cx).is_singleton() {
17552            cx.propagate();
17553            return;
17554        }
17555
17556        let mut new_selections_by_buffer = HashMap::default();
17557        match &jump_data {
17558            Some(JumpData::MultiBufferPoint {
17559                excerpt_id,
17560                position,
17561                anchor,
17562                line_offset_from_top,
17563            }) => {
17564                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17565                if let Some(buffer) = multi_buffer_snapshot
17566                    .buffer_id_for_excerpt(*excerpt_id)
17567                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17568                {
17569                    let buffer_snapshot = buffer.read(cx).snapshot();
17570                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17571                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17572                    } else {
17573                        buffer_snapshot.clip_point(*position, Bias::Left)
17574                    };
17575                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17576                    new_selections_by_buffer.insert(
17577                        buffer,
17578                        (
17579                            vec![jump_to_offset..jump_to_offset],
17580                            Some(*line_offset_from_top),
17581                        ),
17582                    );
17583                }
17584            }
17585            Some(JumpData::MultiBufferRow {
17586                row,
17587                line_offset_from_top,
17588            }) => {
17589                let point = MultiBufferPoint::new(row.0, 0);
17590                if let Some((buffer, buffer_point, _)) =
17591                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17592                {
17593                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17594                    new_selections_by_buffer
17595                        .entry(buffer)
17596                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17597                        .0
17598                        .push(buffer_offset..buffer_offset)
17599                }
17600            }
17601            None => {
17602                let selections = self.selections.all::<usize>(cx);
17603                let multi_buffer = self.buffer.read(cx);
17604                for selection in selections {
17605                    for (snapshot, range, _, anchor) in multi_buffer
17606                        .snapshot(cx)
17607                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17608                    {
17609                        if let Some(anchor) = anchor {
17610                            // selection is in a deleted hunk
17611                            let Some(buffer_id) = anchor.buffer_id else {
17612                                continue;
17613                            };
17614                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17615                                continue;
17616                            };
17617                            let offset = text::ToOffset::to_offset(
17618                                &anchor.text_anchor,
17619                                &buffer_handle.read(cx).snapshot(),
17620                            );
17621                            let range = offset..offset;
17622                            new_selections_by_buffer
17623                                .entry(buffer_handle)
17624                                .or_insert((Vec::new(), None))
17625                                .0
17626                                .push(range)
17627                        } else {
17628                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17629                            else {
17630                                continue;
17631                            };
17632                            new_selections_by_buffer
17633                                .entry(buffer_handle)
17634                                .or_insert((Vec::new(), None))
17635                                .0
17636                                .push(range)
17637                        }
17638                    }
17639                }
17640            }
17641        }
17642
17643        new_selections_by_buffer
17644            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17645
17646        if new_selections_by_buffer.is_empty() {
17647            return;
17648        }
17649
17650        // We defer the pane interaction because we ourselves are a workspace item
17651        // and activating a new item causes the pane to call a method on us reentrantly,
17652        // which panics if we're on the stack.
17653        window.defer(cx, move |window, cx| {
17654            workspace.update(cx, |workspace, cx| {
17655                let pane = if split {
17656                    workspace.adjacent_pane(window, cx)
17657                } else {
17658                    workspace.active_pane().clone()
17659                };
17660
17661                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17662                    let editor = buffer
17663                        .read(cx)
17664                        .file()
17665                        .is_none()
17666                        .then(|| {
17667                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17668                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17669                            // Instead, we try to activate the existing editor in the pane first.
17670                            let (editor, pane_item_index) =
17671                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17672                                    let editor = item.downcast::<Editor>()?;
17673                                    let singleton_buffer =
17674                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17675                                    if singleton_buffer == buffer {
17676                                        Some((editor, i))
17677                                    } else {
17678                                        None
17679                                    }
17680                                })?;
17681                            pane.update(cx, |pane, cx| {
17682                                pane.activate_item(pane_item_index, true, true, window, cx)
17683                            });
17684                            Some(editor)
17685                        })
17686                        .flatten()
17687                        .unwrap_or_else(|| {
17688                            workspace.open_project_item::<Self>(
17689                                pane.clone(),
17690                                buffer,
17691                                true,
17692                                true,
17693                                window,
17694                                cx,
17695                            )
17696                        });
17697
17698                    editor.update(cx, |editor, cx| {
17699                        let autoscroll = match scroll_offset {
17700                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17701                            None => Autoscroll::newest(),
17702                        };
17703                        let nav_history = editor.nav_history.take();
17704                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17705                            s.select_ranges(ranges);
17706                        });
17707                        editor.nav_history = nav_history;
17708                    });
17709                }
17710            })
17711        });
17712    }
17713
17714    // For now, don't allow opening excerpts in buffers that aren't backed by
17715    // regular project files.
17716    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17717        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17718    }
17719
17720    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17721        let snapshot = self.buffer.read(cx).read(cx);
17722        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17723        Some(
17724            ranges
17725                .iter()
17726                .map(move |range| {
17727                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17728                })
17729                .collect(),
17730        )
17731    }
17732
17733    fn selection_replacement_ranges(
17734        &self,
17735        range: Range<OffsetUtf16>,
17736        cx: &mut App,
17737    ) -> Vec<Range<OffsetUtf16>> {
17738        let selections = self.selections.all::<OffsetUtf16>(cx);
17739        let newest_selection = selections
17740            .iter()
17741            .max_by_key(|selection| selection.id)
17742            .unwrap();
17743        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17744        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17745        let snapshot = self.buffer.read(cx).read(cx);
17746        selections
17747            .into_iter()
17748            .map(|mut selection| {
17749                selection.start.0 =
17750                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17751                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17752                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17753                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17754            })
17755            .collect()
17756    }
17757
17758    fn report_editor_event(
17759        &self,
17760        event_type: &'static str,
17761        file_extension: Option<String>,
17762        cx: &App,
17763    ) {
17764        if cfg!(any(test, feature = "test-support")) {
17765            return;
17766        }
17767
17768        let Some(project) = &self.project else { return };
17769
17770        // If None, we are in a file without an extension
17771        let file = self
17772            .buffer
17773            .read(cx)
17774            .as_singleton()
17775            .and_then(|b| b.read(cx).file());
17776        let file_extension = file_extension.or(file
17777            .as_ref()
17778            .and_then(|file| Path::new(file.file_name(cx)).extension())
17779            .and_then(|e| e.to_str())
17780            .map(|a| a.to_string()));
17781
17782        let vim_mode = cx
17783            .global::<SettingsStore>()
17784            .raw_user_settings()
17785            .get("vim_mode")
17786            == Some(&serde_json::Value::Bool(true));
17787
17788        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17789        let copilot_enabled = edit_predictions_provider
17790            == language::language_settings::EditPredictionProvider::Copilot;
17791        let copilot_enabled_for_language = self
17792            .buffer
17793            .read(cx)
17794            .language_settings(cx)
17795            .show_edit_predictions;
17796
17797        let project = project.read(cx);
17798        telemetry::event!(
17799            event_type,
17800            file_extension,
17801            vim_mode,
17802            copilot_enabled,
17803            copilot_enabled_for_language,
17804            edit_predictions_provider,
17805            is_via_ssh = project.is_via_ssh(),
17806        );
17807    }
17808
17809    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17810    /// with each line being an array of {text, highlight} objects.
17811    fn copy_highlight_json(
17812        &mut self,
17813        _: &CopyHighlightJson,
17814        window: &mut Window,
17815        cx: &mut Context<Self>,
17816    ) {
17817        #[derive(Serialize)]
17818        struct Chunk<'a> {
17819            text: String,
17820            highlight: Option<&'a str>,
17821        }
17822
17823        let snapshot = self.buffer.read(cx).snapshot(cx);
17824        let range = self
17825            .selected_text_range(false, window, cx)
17826            .and_then(|selection| {
17827                if selection.range.is_empty() {
17828                    None
17829                } else {
17830                    Some(selection.range)
17831                }
17832            })
17833            .unwrap_or_else(|| 0..snapshot.len());
17834
17835        let chunks = snapshot.chunks(range, true);
17836        let mut lines = Vec::new();
17837        let mut line: VecDeque<Chunk> = VecDeque::new();
17838
17839        let Some(style) = self.style.as_ref() else {
17840            return;
17841        };
17842
17843        for chunk in chunks {
17844            let highlight = chunk
17845                .syntax_highlight_id
17846                .and_then(|id| id.name(&style.syntax));
17847            let mut chunk_lines = chunk.text.split('\n').peekable();
17848            while let Some(text) = chunk_lines.next() {
17849                let mut merged_with_last_token = false;
17850                if let Some(last_token) = line.back_mut() {
17851                    if last_token.highlight == highlight {
17852                        last_token.text.push_str(text);
17853                        merged_with_last_token = true;
17854                    }
17855                }
17856
17857                if !merged_with_last_token {
17858                    line.push_back(Chunk {
17859                        text: text.into(),
17860                        highlight,
17861                    });
17862                }
17863
17864                if chunk_lines.peek().is_some() {
17865                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17866                        line.pop_front();
17867                    }
17868                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17869                        line.pop_back();
17870                    }
17871
17872                    lines.push(mem::take(&mut line));
17873                }
17874            }
17875        }
17876
17877        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17878            return;
17879        };
17880        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17881    }
17882
17883    pub fn open_context_menu(
17884        &mut self,
17885        _: &OpenContextMenu,
17886        window: &mut Window,
17887        cx: &mut Context<Self>,
17888    ) {
17889        self.request_autoscroll(Autoscroll::newest(), cx);
17890        let position = self.selections.newest_display(cx).start;
17891        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17892    }
17893
17894    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17895        &self.inlay_hint_cache
17896    }
17897
17898    pub fn replay_insert_event(
17899        &mut self,
17900        text: &str,
17901        relative_utf16_range: Option<Range<isize>>,
17902        window: &mut Window,
17903        cx: &mut Context<Self>,
17904    ) {
17905        if !self.input_enabled {
17906            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17907            return;
17908        }
17909        if let Some(relative_utf16_range) = relative_utf16_range {
17910            let selections = self.selections.all::<OffsetUtf16>(cx);
17911            self.change_selections(None, window, cx, |s| {
17912                let new_ranges = selections.into_iter().map(|range| {
17913                    let start = OffsetUtf16(
17914                        range
17915                            .head()
17916                            .0
17917                            .saturating_add_signed(relative_utf16_range.start),
17918                    );
17919                    let end = OffsetUtf16(
17920                        range
17921                            .head()
17922                            .0
17923                            .saturating_add_signed(relative_utf16_range.end),
17924                    );
17925                    start..end
17926                });
17927                s.select_ranges(new_ranges);
17928            });
17929        }
17930
17931        self.handle_input(text, window, cx);
17932    }
17933
17934    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17935        let Some(provider) = self.semantics_provider.as_ref() else {
17936            return false;
17937        };
17938
17939        let mut supports = false;
17940        self.buffer().update(cx, |this, cx| {
17941            this.for_each_buffer(|buffer| {
17942                supports |= provider.supports_inlay_hints(buffer, cx);
17943            });
17944        });
17945
17946        supports
17947    }
17948
17949    pub fn is_focused(&self, window: &Window) -> bool {
17950        self.focus_handle.is_focused(window)
17951    }
17952
17953    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17954        cx.emit(EditorEvent::Focused);
17955
17956        if let Some(descendant) = self
17957            .last_focused_descendant
17958            .take()
17959            .and_then(|descendant| descendant.upgrade())
17960        {
17961            window.focus(&descendant);
17962        } else {
17963            if let Some(blame) = self.blame.as_ref() {
17964                blame.update(cx, GitBlame::focus)
17965            }
17966
17967            self.blink_manager.update(cx, BlinkManager::enable);
17968            self.show_cursor_names(window, cx);
17969            self.buffer.update(cx, |buffer, cx| {
17970                buffer.finalize_last_transaction(cx);
17971                if self.leader_peer_id.is_none() {
17972                    buffer.set_active_selections(
17973                        &self.selections.disjoint_anchors(),
17974                        self.selections.line_mode,
17975                        self.cursor_shape,
17976                        cx,
17977                    );
17978                }
17979            });
17980        }
17981    }
17982
17983    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17984        cx.emit(EditorEvent::FocusedIn)
17985    }
17986
17987    fn handle_focus_out(
17988        &mut self,
17989        event: FocusOutEvent,
17990        _window: &mut Window,
17991        cx: &mut Context<Self>,
17992    ) {
17993        if event.blurred != self.focus_handle {
17994            self.last_focused_descendant = Some(event.blurred);
17995        }
17996        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17997    }
17998
17999    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18000        self.blink_manager.update(cx, BlinkManager::disable);
18001        self.buffer
18002            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18003
18004        if let Some(blame) = self.blame.as_ref() {
18005            blame.update(cx, GitBlame::blur)
18006        }
18007        if !self.hover_state.focused(window, cx) {
18008            hide_hover(self, cx);
18009        }
18010        if !self
18011            .context_menu
18012            .borrow()
18013            .as_ref()
18014            .is_some_and(|context_menu| context_menu.focused(window, cx))
18015        {
18016            self.hide_context_menu(window, cx);
18017        }
18018        self.discard_inline_completion(false, cx);
18019        cx.emit(EditorEvent::Blurred);
18020        cx.notify();
18021    }
18022
18023    pub fn register_action<A: Action>(
18024        &mut self,
18025        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18026    ) -> Subscription {
18027        let id = self.next_editor_action_id.post_inc();
18028        let listener = Arc::new(listener);
18029        self.editor_actions.borrow_mut().insert(
18030            id,
18031            Box::new(move |window, _| {
18032                let listener = listener.clone();
18033                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18034                    let action = action.downcast_ref().unwrap();
18035                    if phase == DispatchPhase::Bubble {
18036                        listener(action, window, cx)
18037                    }
18038                })
18039            }),
18040        );
18041
18042        let editor_actions = self.editor_actions.clone();
18043        Subscription::new(move || {
18044            editor_actions.borrow_mut().remove(&id);
18045        })
18046    }
18047
18048    pub fn file_header_size(&self) -> u32 {
18049        FILE_HEADER_HEIGHT
18050    }
18051
18052    pub fn restore(
18053        &mut self,
18054        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18055        window: &mut Window,
18056        cx: &mut Context<Self>,
18057    ) {
18058        let workspace = self.workspace();
18059        let project = self.project.as_ref();
18060        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18061            let mut tasks = Vec::new();
18062            for (buffer_id, changes) in revert_changes {
18063                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18064                    buffer.update(cx, |buffer, cx| {
18065                        buffer.edit(
18066                            changes
18067                                .into_iter()
18068                                .map(|(range, text)| (range, text.to_string())),
18069                            None,
18070                            cx,
18071                        );
18072                    });
18073
18074                    if let Some(project) =
18075                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18076                    {
18077                        project.update(cx, |project, cx| {
18078                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18079                        })
18080                    }
18081                }
18082            }
18083            tasks
18084        });
18085        cx.spawn_in(window, async move |_, cx| {
18086            for (buffer, task) in save_tasks {
18087                let result = task.await;
18088                if result.is_err() {
18089                    let Some(path) = buffer
18090                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18091                        .ok()
18092                    else {
18093                        continue;
18094                    };
18095                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18096                        let Some(task) = cx
18097                            .update_window_entity(&workspace, |workspace, window, cx| {
18098                                workspace
18099                                    .open_path_preview(path, None, false, false, false, window, cx)
18100                            })
18101                            .ok()
18102                        else {
18103                            continue;
18104                        };
18105                        task.await.log_err();
18106                    }
18107                }
18108            }
18109        })
18110        .detach();
18111        self.change_selections(None, window, cx, |selections| selections.refresh());
18112    }
18113
18114    pub fn to_pixel_point(
18115        &self,
18116        source: multi_buffer::Anchor,
18117        editor_snapshot: &EditorSnapshot,
18118        window: &mut Window,
18119    ) -> Option<gpui::Point<Pixels>> {
18120        let source_point = source.to_display_point(editor_snapshot);
18121        self.display_to_pixel_point(source_point, editor_snapshot, window)
18122    }
18123
18124    pub fn display_to_pixel_point(
18125        &self,
18126        source: DisplayPoint,
18127        editor_snapshot: &EditorSnapshot,
18128        window: &mut Window,
18129    ) -> Option<gpui::Point<Pixels>> {
18130        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18131        let text_layout_details = self.text_layout_details(window);
18132        let scroll_top = text_layout_details
18133            .scroll_anchor
18134            .scroll_position(editor_snapshot)
18135            .y;
18136
18137        if source.row().as_f32() < scroll_top.floor() {
18138            return None;
18139        }
18140        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18141        let source_y = line_height * (source.row().as_f32() - scroll_top);
18142        Some(gpui::Point::new(source_x, source_y))
18143    }
18144
18145    pub fn has_visible_completions_menu(&self) -> bool {
18146        !self.edit_prediction_preview_is_active()
18147            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18148                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18149            })
18150    }
18151
18152    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18153        self.addons
18154            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18155    }
18156
18157    pub fn unregister_addon<T: Addon>(&mut self) {
18158        self.addons.remove(&std::any::TypeId::of::<T>());
18159    }
18160
18161    pub fn addon<T: Addon>(&self) -> Option<&T> {
18162        let type_id = std::any::TypeId::of::<T>();
18163        self.addons
18164            .get(&type_id)
18165            .and_then(|item| item.to_any().downcast_ref::<T>())
18166    }
18167
18168    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18169        let text_layout_details = self.text_layout_details(window);
18170        let style = &text_layout_details.editor_style;
18171        let font_id = window.text_system().resolve_font(&style.text.font());
18172        let font_size = style.text.font_size.to_pixels(window.rem_size());
18173        let line_height = style.text.line_height_in_pixels(window.rem_size());
18174        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18175
18176        gpui::Size::new(em_width, line_height)
18177    }
18178
18179    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18180        self.load_diff_task.clone()
18181    }
18182
18183    fn read_metadata_from_db(
18184        &mut self,
18185        item_id: u64,
18186        workspace_id: WorkspaceId,
18187        window: &mut Window,
18188        cx: &mut Context<Editor>,
18189    ) {
18190        if self.is_singleton(cx)
18191            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18192        {
18193            let buffer_snapshot = OnceCell::new();
18194
18195            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18196                if !folds.is_empty() {
18197                    let snapshot =
18198                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18199                    self.fold_ranges(
18200                        folds
18201                            .into_iter()
18202                            .map(|(start, end)| {
18203                                snapshot.clip_offset(start, Bias::Left)
18204                                    ..snapshot.clip_offset(end, Bias::Right)
18205                            })
18206                            .collect(),
18207                        false,
18208                        window,
18209                        cx,
18210                    );
18211                }
18212            }
18213
18214            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18215                if !selections.is_empty() {
18216                    let snapshot =
18217                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18218                    self.change_selections(None, window, cx, |s| {
18219                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18220                            snapshot.clip_offset(start, Bias::Left)
18221                                ..snapshot.clip_offset(end, Bias::Right)
18222                        }));
18223                    });
18224                }
18225            };
18226        }
18227
18228        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18229    }
18230}
18231
18232// Consider user intent and default settings
18233fn choose_completion_range(
18234    completion: &Completion,
18235    intent: CompletionIntent,
18236    buffer: &Entity<Buffer>,
18237    cx: &mut Context<Editor>,
18238) -> Range<usize> {
18239    fn should_replace(
18240        completion: &Completion,
18241        insert_range: &Range<text::Anchor>,
18242        intent: CompletionIntent,
18243        completion_mode_setting: LspInsertMode,
18244        buffer: &Buffer,
18245    ) -> bool {
18246        // specific actions take precedence over settings
18247        match intent {
18248            CompletionIntent::CompleteWithInsert => return false,
18249            CompletionIntent::CompleteWithReplace => return true,
18250            CompletionIntent::Complete | CompletionIntent::Compose => {}
18251        }
18252
18253        match completion_mode_setting {
18254            LspInsertMode::Insert => false,
18255            LspInsertMode::Replace => true,
18256            LspInsertMode::ReplaceSubsequence => {
18257                let mut text_to_replace = buffer.chars_for_range(
18258                    buffer.anchor_before(completion.replace_range.start)
18259                        ..buffer.anchor_after(completion.replace_range.end),
18260                );
18261                let mut completion_text = completion.new_text.chars();
18262
18263                // is `text_to_replace` a subsequence of `completion_text`
18264                text_to_replace
18265                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18266            }
18267            LspInsertMode::ReplaceSuffix => {
18268                let range_after_cursor = insert_range.end..completion.replace_range.end;
18269
18270                let text_after_cursor = buffer
18271                    .text_for_range(
18272                        buffer.anchor_before(range_after_cursor.start)
18273                            ..buffer.anchor_after(range_after_cursor.end),
18274                    )
18275                    .collect::<String>();
18276                completion.new_text.ends_with(&text_after_cursor)
18277            }
18278        }
18279    }
18280
18281    let buffer = buffer.read(cx);
18282
18283    if let CompletionSource::Lsp {
18284        insert_range: Some(insert_range),
18285        ..
18286    } = &completion.source
18287    {
18288        let completion_mode_setting =
18289            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18290                .completions
18291                .lsp_insert_mode;
18292
18293        if !should_replace(
18294            completion,
18295            &insert_range,
18296            intent,
18297            completion_mode_setting,
18298            buffer,
18299        ) {
18300            return insert_range.to_offset(buffer);
18301        }
18302    }
18303
18304    completion.replace_range.to_offset(buffer)
18305}
18306
18307fn insert_extra_newline_brackets(
18308    buffer: &MultiBufferSnapshot,
18309    range: Range<usize>,
18310    language: &language::LanguageScope,
18311) -> bool {
18312    let leading_whitespace_len = buffer
18313        .reversed_chars_at(range.start)
18314        .take_while(|c| c.is_whitespace() && *c != '\n')
18315        .map(|c| c.len_utf8())
18316        .sum::<usize>();
18317    let trailing_whitespace_len = buffer
18318        .chars_at(range.end)
18319        .take_while(|c| c.is_whitespace() && *c != '\n')
18320        .map(|c| c.len_utf8())
18321        .sum::<usize>();
18322    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18323
18324    language.brackets().any(|(pair, enabled)| {
18325        let pair_start = pair.start.trim_end();
18326        let pair_end = pair.end.trim_start();
18327
18328        enabled
18329            && pair.newline
18330            && buffer.contains_str_at(range.end, pair_end)
18331            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18332    })
18333}
18334
18335fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18336    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18337        [(buffer, range, _)] => (*buffer, range.clone()),
18338        _ => return false,
18339    };
18340    let pair = {
18341        let mut result: Option<BracketMatch> = None;
18342
18343        for pair in buffer
18344            .all_bracket_ranges(range.clone())
18345            .filter(move |pair| {
18346                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18347            })
18348        {
18349            let len = pair.close_range.end - pair.open_range.start;
18350
18351            if let Some(existing) = &result {
18352                let existing_len = existing.close_range.end - existing.open_range.start;
18353                if len > existing_len {
18354                    continue;
18355                }
18356            }
18357
18358            result = Some(pair);
18359        }
18360
18361        result
18362    };
18363    let Some(pair) = pair else {
18364        return false;
18365    };
18366    pair.newline_only
18367        && buffer
18368            .chars_for_range(pair.open_range.end..range.start)
18369            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18370            .all(|c| c.is_whitespace() && c != '\n')
18371}
18372
18373fn get_uncommitted_diff_for_buffer(
18374    project: &Entity<Project>,
18375    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18376    buffer: Entity<MultiBuffer>,
18377    cx: &mut App,
18378) -> Task<()> {
18379    let mut tasks = Vec::new();
18380    project.update(cx, |project, cx| {
18381        for buffer in buffers {
18382            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18383                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18384            }
18385        }
18386    });
18387    cx.spawn(async move |cx| {
18388        let diffs = future::join_all(tasks).await;
18389        buffer
18390            .update(cx, |buffer, cx| {
18391                for diff in diffs.into_iter().flatten() {
18392                    buffer.add_diff(diff, cx);
18393                }
18394            })
18395            .ok();
18396    })
18397}
18398
18399fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18400    let tab_size = tab_size.get() as usize;
18401    let mut width = offset;
18402
18403    for ch in text.chars() {
18404        width += if ch == '\t' {
18405            tab_size - (width % tab_size)
18406        } else {
18407            1
18408        };
18409    }
18410
18411    width - offset
18412}
18413
18414#[cfg(test)]
18415mod tests {
18416    use super::*;
18417
18418    #[test]
18419    fn test_string_size_with_expanded_tabs() {
18420        let nz = |val| NonZeroU32::new(val).unwrap();
18421        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18422        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18423        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18424        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18425        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18426        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18427        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18428        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18429    }
18430}
18431
18432/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18433struct WordBreakingTokenizer<'a> {
18434    input: &'a str,
18435}
18436
18437impl<'a> WordBreakingTokenizer<'a> {
18438    fn new(input: &'a str) -> Self {
18439        Self { input }
18440    }
18441}
18442
18443fn is_char_ideographic(ch: char) -> bool {
18444    use unicode_script::Script::*;
18445    use unicode_script::UnicodeScript;
18446    matches!(ch.script(), Han | Tangut | Yi)
18447}
18448
18449fn is_grapheme_ideographic(text: &str) -> bool {
18450    text.chars().any(is_char_ideographic)
18451}
18452
18453fn is_grapheme_whitespace(text: &str) -> bool {
18454    text.chars().any(|x| x.is_whitespace())
18455}
18456
18457fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18458    text.chars().next().map_or(false, |ch| {
18459        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18460    })
18461}
18462
18463#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18464enum WordBreakToken<'a> {
18465    Word { token: &'a str, grapheme_len: usize },
18466    InlineWhitespace { token: &'a str, grapheme_len: usize },
18467    Newline,
18468}
18469
18470impl<'a> Iterator for WordBreakingTokenizer<'a> {
18471    /// Yields a span, the count of graphemes in the token, and whether it was
18472    /// whitespace. Note that it also breaks at word boundaries.
18473    type Item = WordBreakToken<'a>;
18474
18475    fn next(&mut self) -> Option<Self::Item> {
18476        use unicode_segmentation::UnicodeSegmentation;
18477        if self.input.is_empty() {
18478            return None;
18479        }
18480
18481        let mut iter = self.input.graphemes(true).peekable();
18482        let mut offset = 0;
18483        let mut grapheme_len = 0;
18484        if let Some(first_grapheme) = iter.next() {
18485            let is_newline = first_grapheme == "\n";
18486            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18487            offset += first_grapheme.len();
18488            grapheme_len += 1;
18489            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18490                if let Some(grapheme) = iter.peek().copied() {
18491                    if should_stay_with_preceding_ideograph(grapheme) {
18492                        offset += grapheme.len();
18493                        grapheme_len += 1;
18494                    }
18495                }
18496            } else {
18497                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18498                let mut next_word_bound = words.peek().copied();
18499                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18500                    next_word_bound = words.next();
18501                }
18502                while let Some(grapheme) = iter.peek().copied() {
18503                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18504                        break;
18505                    };
18506                    if is_grapheme_whitespace(grapheme) != is_whitespace
18507                        || (grapheme == "\n") != is_newline
18508                    {
18509                        break;
18510                    };
18511                    offset += grapheme.len();
18512                    grapheme_len += 1;
18513                    iter.next();
18514                }
18515            }
18516            let token = &self.input[..offset];
18517            self.input = &self.input[offset..];
18518            if token == "\n" {
18519                Some(WordBreakToken::Newline)
18520            } else if is_whitespace {
18521                Some(WordBreakToken::InlineWhitespace {
18522                    token,
18523                    grapheme_len,
18524                })
18525            } else {
18526                Some(WordBreakToken::Word {
18527                    token,
18528                    grapheme_len,
18529                })
18530            }
18531        } else {
18532            None
18533        }
18534    }
18535}
18536
18537#[test]
18538fn test_word_breaking_tokenizer() {
18539    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18540        ("", &[]),
18541        ("  ", &[whitespace("  ", 2)]),
18542        ("Ʒ", &[word("Ʒ", 1)]),
18543        ("Ǽ", &[word("Ǽ", 1)]),
18544        ("", &[word("", 1)]),
18545        ("⋑⋑", &[word("⋑⋑", 2)]),
18546        (
18547            "原理,进而",
18548            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18549        ),
18550        (
18551            "hello world",
18552            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18553        ),
18554        (
18555            "hello, world",
18556            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18557        ),
18558        (
18559            "  hello world",
18560            &[
18561                whitespace("  ", 2),
18562                word("hello", 5),
18563                whitespace(" ", 1),
18564                word("world", 5),
18565            ],
18566        ),
18567        (
18568            "这是什么 \n 钢笔",
18569            &[
18570                word("", 1),
18571                word("", 1),
18572                word("", 1),
18573                word("", 1),
18574                whitespace(" ", 1),
18575                newline(),
18576                whitespace(" ", 1),
18577                word("", 1),
18578                word("", 1),
18579            ],
18580        ),
18581        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18582    ];
18583
18584    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18585        WordBreakToken::Word {
18586            token,
18587            grapheme_len,
18588        }
18589    }
18590
18591    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18592        WordBreakToken::InlineWhitespace {
18593            token,
18594            grapheme_len,
18595        }
18596    }
18597
18598    fn newline() -> WordBreakToken<'static> {
18599        WordBreakToken::Newline
18600    }
18601
18602    for (input, result) in tests {
18603        assert_eq!(
18604            WordBreakingTokenizer::new(input)
18605                .collect::<Vec<_>>()
18606                .as_slice(),
18607            *result,
18608        );
18609    }
18610}
18611
18612fn wrap_with_prefix(
18613    line_prefix: String,
18614    unwrapped_text: String,
18615    wrap_column: usize,
18616    tab_size: NonZeroU32,
18617    preserve_existing_whitespace: bool,
18618) -> String {
18619    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18620    let mut wrapped_text = String::new();
18621    let mut current_line = line_prefix.clone();
18622
18623    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18624    let mut current_line_len = line_prefix_len;
18625    let mut in_whitespace = false;
18626    for token in tokenizer {
18627        let have_preceding_whitespace = in_whitespace;
18628        match token {
18629            WordBreakToken::Word {
18630                token,
18631                grapheme_len,
18632            } => {
18633                in_whitespace = false;
18634                if current_line_len + grapheme_len > wrap_column
18635                    && current_line_len != line_prefix_len
18636                {
18637                    wrapped_text.push_str(current_line.trim_end());
18638                    wrapped_text.push('\n');
18639                    current_line.truncate(line_prefix.len());
18640                    current_line_len = line_prefix_len;
18641                }
18642                current_line.push_str(token);
18643                current_line_len += grapheme_len;
18644            }
18645            WordBreakToken::InlineWhitespace {
18646                mut token,
18647                mut grapheme_len,
18648            } => {
18649                in_whitespace = true;
18650                if have_preceding_whitespace && !preserve_existing_whitespace {
18651                    continue;
18652                }
18653                if !preserve_existing_whitespace {
18654                    token = " ";
18655                    grapheme_len = 1;
18656                }
18657                if current_line_len + grapheme_len > wrap_column {
18658                    wrapped_text.push_str(current_line.trim_end());
18659                    wrapped_text.push('\n');
18660                    current_line.truncate(line_prefix.len());
18661                    current_line_len = line_prefix_len;
18662                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18663                    current_line.push_str(token);
18664                    current_line_len += grapheme_len;
18665                }
18666            }
18667            WordBreakToken::Newline => {
18668                in_whitespace = true;
18669                if preserve_existing_whitespace {
18670                    wrapped_text.push_str(current_line.trim_end());
18671                    wrapped_text.push('\n');
18672                    current_line.truncate(line_prefix.len());
18673                    current_line_len = line_prefix_len;
18674                } else if have_preceding_whitespace {
18675                    continue;
18676                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18677                {
18678                    wrapped_text.push_str(current_line.trim_end());
18679                    wrapped_text.push('\n');
18680                    current_line.truncate(line_prefix.len());
18681                    current_line_len = line_prefix_len;
18682                } else if current_line_len != line_prefix_len {
18683                    current_line.push(' ');
18684                    current_line_len += 1;
18685                }
18686            }
18687        }
18688    }
18689
18690    if !current_line.is_empty() {
18691        wrapped_text.push_str(&current_line);
18692    }
18693    wrapped_text
18694}
18695
18696#[test]
18697fn test_wrap_with_prefix() {
18698    assert_eq!(
18699        wrap_with_prefix(
18700            "# ".to_string(),
18701            "abcdefg".to_string(),
18702            4,
18703            NonZeroU32::new(4).unwrap(),
18704            false,
18705        ),
18706        "# abcdefg"
18707    );
18708    assert_eq!(
18709        wrap_with_prefix(
18710            "".to_string(),
18711            "\thello world".to_string(),
18712            8,
18713            NonZeroU32::new(4).unwrap(),
18714            false,
18715        ),
18716        "hello\nworld"
18717    );
18718    assert_eq!(
18719        wrap_with_prefix(
18720            "// ".to_string(),
18721            "xx \nyy zz aa bb cc".to_string(),
18722            12,
18723            NonZeroU32::new(4).unwrap(),
18724            false,
18725        ),
18726        "// xx yy zz\n// aa bb cc"
18727    );
18728    assert_eq!(
18729        wrap_with_prefix(
18730            String::new(),
18731            "这是什么 \n 钢笔".to_string(),
18732            3,
18733            NonZeroU32::new(4).unwrap(),
18734            false,
18735        ),
18736        "这是什\n么 钢\n"
18737    );
18738}
18739
18740pub trait CollaborationHub {
18741    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18742    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18743    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18744}
18745
18746impl CollaborationHub for Entity<Project> {
18747    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18748        self.read(cx).collaborators()
18749    }
18750
18751    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18752        self.read(cx).user_store().read(cx).participant_indices()
18753    }
18754
18755    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18756        let this = self.read(cx);
18757        let user_ids = this.collaborators().values().map(|c| c.user_id);
18758        this.user_store().read_with(cx, |user_store, cx| {
18759            user_store.participant_names(user_ids, cx)
18760        })
18761    }
18762}
18763
18764pub trait SemanticsProvider {
18765    fn hover(
18766        &self,
18767        buffer: &Entity<Buffer>,
18768        position: text::Anchor,
18769        cx: &mut App,
18770    ) -> Option<Task<Vec<project::Hover>>>;
18771
18772    fn inlay_hints(
18773        &self,
18774        buffer_handle: Entity<Buffer>,
18775        range: Range<text::Anchor>,
18776        cx: &mut App,
18777    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18778
18779    fn resolve_inlay_hint(
18780        &self,
18781        hint: InlayHint,
18782        buffer_handle: Entity<Buffer>,
18783        server_id: LanguageServerId,
18784        cx: &mut App,
18785    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18786
18787    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18788
18789    fn document_highlights(
18790        &self,
18791        buffer: &Entity<Buffer>,
18792        position: text::Anchor,
18793        cx: &mut App,
18794    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18795
18796    fn definitions(
18797        &self,
18798        buffer: &Entity<Buffer>,
18799        position: text::Anchor,
18800        kind: GotoDefinitionKind,
18801        cx: &mut App,
18802    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18803
18804    fn range_for_rename(
18805        &self,
18806        buffer: &Entity<Buffer>,
18807        position: text::Anchor,
18808        cx: &mut App,
18809    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18810
18811    fn perform_rename(
18812        &self,
18813        buffer: &Entity<Buffer>,
18814        position: text::Anchor,
18815        new_name: String,
18816        cx: &mut App,
18817    ) -> Option<Task<Result<ProjectTransaction>>>;
18818}
18819
18820pub trait CompletionProvider {
18821    fn completions(
18822        &self,
18823        excerpt_id: ExcerptId,
18824        buffer: &Entity<Buffer>,
18825        buffer_position: text::Anchor,
18826        trigger: CompletionContext,
18827        window: &mut Window,
18828        cx: &mut Context<Editor>,
18829    ) -> Task<Result<Option<Vec<Completion>>>>;
18830
18831    fn resolve_completions(
18832        &self,
18833        buffer: Entity<Buffer>,
18834        completion_indices: Vec<usize>,
18835        completions: Rc<RefCell<Box<[Completion]>>>,
18836        cx: &mut Context<Editor>,
18837    ) -> Task<Result<bool>>;
18838
18839    fn apply_additional_edits_for_completion(
18840        &self,
18841        _buffer: Entity<Buffer>,
18842        _completions: Rc<RefCell<Box<[Completion]>>>,
18843        _completion_index: usize,
18844        _push_to_history: bool,
18845        _cx: &mut Context<Editor>,
18846    ) -> Task<Result<Option<language::Transaction>>> {
18847        Task::ready(Ok(None))
18848    }
18849
18850    fn is_completion_trigger(
18851        &self,
18852        buffer: &Entity<Buffer>,
18853        position: language::Anchor,
18854        text: &str,
18855        trigger_in_words: bool,
18856        cx: &mut Context<Editor>,
18857    ) -> bool;
18858
18859    fn sort_completions(&self) -> bool {
18860        true
18861    }
18862
18863    fn filter_completions(&self) -> bool {
18864        true
18865    }
18866}
18867
18868pub trait CodeActionProvider {
18869    fn id(&self) -> Arc<str>;
18870
18871    fn code_actions(
18872        &self,
18873        buffer: &Entity<Buffer>,
18874        range: Range<text::Anchor>,
18875        window: &mut Window,
18876        cx: &mut App,
18877    ) -> Task<Result<Vec<CodeAction>>>;
18878
18879    fn apply_code_action(
18880        &self,
18881        buffer_handle: Entity<Buffer>,
18882        action: CodeAction,
18883        excerpt_id: ExcerptId,
18884        push_to_history: bool,
18885        window: &mut Window,
18886        cx: &mut App,
18887    ) -> Task<Result<ProjectTransaction>>;
18888}
18889
18890impl CodeActionProvider for Entity<Project> {
18891    fn id(&self) -> Arc<str> {
18892        "project".into()
18893    }
18894
18895    fn code_actions(
18896        &self,
18897        buffer: &Entity<Buffer>,
18898        range: Range<text::Anchor>,
18899        _window: &mut Window,
18900        cx: &mut App,
18901    ) -> Task<Result<Vec<CodeAction>>> {
18902        self.update(cx, |project, cx| {
18903            let code_lens = project.code_lens(buffer, range.clone(), cx);
18904            let code_actions = project.code_actions(buffer, range, None, cx);
18905            cx.background_spawn(async move {
18906                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18907                Ok(code_lens
18908                    .context("code lens fetch")?
18909                    .into_iter()
18910                    .chain(code_actions.context("code action fetch")?)
18911                    .collect())
18912            })
18913        })
18914    }
18915
18916    fn apply_code_action(
18917        &self,
18918        buffer_handle: Entity<Buffer>,
18919        action: CodeAction,
18920        _excerpt_id: ExcerptId,
18921        push_to_history: bool,
18922        _window: &mut Window,
18923        cx: &mut App,
18924    ) -> Task<Result<ProjectTransaction>> {
18925        self.update(cx, |project, cx| {
18926            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18927        })
18928    }
18929}
18930
18931fn snippet_completions(
18932    project: &Project,
18933    buffer: &Entity<Buffer>,
18934    buffer_position: text::Anchor,
18935    cx: &mut App,
18936) -> Task<Result<Vec<Completion>>> {
18937    let languages = buffer.read(cx).languages_at(buffer_position);
18938    let snippet_store = project.snippets().read(cx);
18939
18940    let scopes: Vec<_> = languages
18941        .iter()
18942        .filter_map(|language| {
18943            let language_name = language.lsp_id();
18944            let snippets = snippet_store.snippets_for(Some(language_name), cx);
18945
18946            if snippets.is_empty() {
18947                None
18948            } else {
18949                Some((language.default_scope(), snippets))
18950            }
18951        })
18952        .collect();
18953
18954    if scopes.is_empty() {
18955        return Task::ready(Ok(vec![]));
18956    }
18957
18958    let snapshot = buffer.read(cx).text_snapshot();
18959    let chars: String = snapshot
18960        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18961        .collect();
18962    let executor = cx.background_executor().clone();
18963
18964    cx.background_spawn(async move {
18965        let mut all_results: Vec<Completion> = Vec::new();
18966        for (scope, snippets) in scopes.into_iter() {
18967            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
18968            let mut last_word = chars
18969                .chars()
18970                .take_while(|c| classifier.is_word(*c))
18971                .collect::<String>();
18972            last_word = last_word.chars().rev().collect();
18973
18974            if last_word.is_empty() {
18975                return Ok(vec![]);
18976            }
18977
18978            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18979            let to_lsp = |point: &text::Anchor| {
18980                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18981                point_to_lsp(end)
18982            };
18983            let lsp_end = to_lsp(&buffer_position);
18984
18985            let candidates = snippets
18986                .iter()
18987                .enumerate()
18988                .flat_map(|(ix, snippet)| {
18989                    snippet
18990                        .prefix
18991                        .iter()
18992                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18993                })
18994                .collect::<Vec<StringMatchCandidate>>();
18995
18996            let mut matches = fuzzy::match_strings(
18997                &candidates,
18998                &last_word,
18999                last_word.chars().any(|c| c.is_uppercase()),
19000                100,
19001                &Default::default(),
19002                executor.clone(),
19003            )
19004            .await;
19005
19006            // Remove all candidates where the query's start does not match the start of any word in the candidate
19007            if let Some(query_start) = last_word.chars().next() {
19008                matches.retain(|string_match| {
19009                    split_words(&string_match.string).any(|word| {
19010                        // Check that the first codepoint of the word as lowercase matches the first
19011                        // codepoint of the query as lowercase
19012                        word.chars()
19013                            .flat_map(|codepoint| codepoint.to_lowercase())
19014                            .zip(query_start.to_lowercase())
19015                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19016                    })
19017                });
19018            }
19019
19020            let matched_strings = matches
19021                .into_iter()
19022                .map(|m| m.string)
19023                .collect::<HashSet<_>>();
19024
19025            let mut result: Vec<Completion> = snippets
19026                .iter()
19027                .filter_map(|snippet| {
19028                    let matching_prefix = snippet
19029                        .prefix
19030                        .iter()
19031                        .find(|prefix| matched_strings.contains(*prefix))?;
19032                    let start = as_offset - last_word.len();
19033                    let start = snapshot.anchor_before(start);
19034                    let range = start..buffer_position;
19035                    let lsp_start = to_lsp(&start);
19036                    let lsp_range = lsp::Range {
19037                        start: lsp_start,
19038                        end: lsp_end,
19039                    };
19040                    Some(Completion {
19041                        replace_range: range,
19042                        new_text: snippet.body.clone(),
19043                        source: CompletionSource::Lsp {
19044                            insert_range: None,
19045                            server_id: LanguageServerId(usize::MAX),
19046                            resolved: true,
19047                            lsp_completion: Box::new(lsp::CompletionItem {
19048                                label: snippet.prefix.first().unwrap().clone(),
19049                                kind: Some(CompletionItemKind::SNIPPET),
19050                                label_details: snippet.description.as_ref().map(|description| {
19051                                    lsp::CompletionItemLabelDetails {
19052                                        detail: Some(description.clone()),
19053                                        description: None,
19054                                    }
19055                                }),
19056                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19057                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19058                                    lsp::InsertReplaceEdit {
19059                                        new_text: snippet.body.clone(),
19060                                        insert: lsp_range,
19061                                        replace: lsp_range,
19062                                    },
19063                                )),
19064                                filter_text: Some(snippet.body.clone()),
19065                                sort_text: Some(char::MAX.to_string()),
19066                                ..lsp::CompletionItem::default()
19067                            }),
19068                            lsp_defaults: None,
19069                        },
19070                        label: CodeLabel {
19071                            text: matching_prefix.clone(),
19072                            runs: Vec::new(),
19073                            filter_range: 0..matching_prefix.len(),
19074                        },
19075                        icon_path: None,
19076                        documentation: snippet.description.clone().map(|description| {
19077                            CompletionDocumentation::SingleLine(description.into())
19078                        }),
19079                        insert_text_mode: None,
19080                        confirm: None,
19081                    })
19082                })
19083                .collect();
19084
19085            all_results.append(&mut result);
19086        }
19087
19088        Ok(all_results)
19089    })
19090}
19091
19092impl CompletionProvider for Entity<Project> {
19093    fn completions(
19094        &self,
19095        _excerpt_id: ExcerptId,
19096        buffer: &Entity<Buffer>,
19097        buffer_position: text::Anchor,
19098        options: CompletionContext,
19099        _window: &mut Window,
19100        cx: &mut Context<Editor>,
19101    ) -> Task<Result<Option<Vec<Completion>>>> {
19102        self.update(cx, |project, cx| {
19103            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19104            let project_completions = project.completions(buffer, buffer_position, options, cx);
19105            cx.background_spawn(async move {
19106                let snippets_completions = snippets.await?;
19107                match project_completions.await? {
19108                    Some(mut completions) => {
19109                        completions.extend(snippets_completions);
19110                        Ok(Some(completions))
19111                    }
19112                    None => {
19113                        if snippets_completions.is_empty() {
19114                            Ok(None)
19115                        } else {
19116                            Ok(Some(snippets_completions))
19117                        }
19118                    }
19119                }
19120            })
19121        })
19122    }
19123
19124    fn resolve_completions(
19125        &self,
19126        buffer: Entity<Buffer>,
19127        completion_indices: Vec<usize>,
19128        completions: Rc<RefCell<Box<[Completion]>>>,
19129        cx: &mut Context<Editor>,
19130    ) -> Task<Result<bool>> {
19131        self.update(cx, |project, cx| {
19132            project.lsp_store().update(cx, |lsp_store, cx| {
19133                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19134            })
19135        })
19136    }
19137
19138    fn apply_additional_edits_for_completion(
19139        &self,
19140        buffer: Entity<Buffer>,
19141        completions: Rc<RefCell<Box<[Completion]>>>,
19142        completion_index: usize,
19143        push_to_history: bool,
19144        cx: &mut Context<Editor>,
19145    ) -> Task<Result<Option<language::Transaction>>> {
19146        self.update(cx, |project, cx| {
19147            project.lsp_store().update(cx, |lsp_store, cx| {
19148                lsp_store.apply_additional_edits_for_completion(
19149                    buffer,
19150                    completions,
19151                    completion_index,
19152                    push_to_history,
19153                    cx,
19154                )
19155            })
19156        })
19157    }
19158
19159    fn is_completion_trigger(
19160        &self,
19161        buffer: &Entity<Buffer>,
19162        position: language::Anchor,
19163        text: &str,
19164        trigger_in_words: bool,
19165        cx: &mut Context<Editor>,
19166    ) -> bool {
19167        let mut chars = text.chars();
19168        let char = if let Some(char) = chars.next() {
19169            char
19170        } else {
19171            return false;
19172        };
19173        if chars.next().is_some() {
19174            return false;
19175        }
19176
19177        let buffer = buffer.read(cx);
19178        let snapshot = buffer.snapshot();
19179        if !snapshot.settings_at(position, cx).show_completions_on_input {
19180            return false;
19181        }
19182        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19183        if trigger_in_words && classifier.is_word(char) {
19184            return true;
19185        }
19186
19187        buffer.completion_triggers().contains(text)
19188    }
19189}
19190
19191impl SemanticsProvider for Entity<Project> {
19192    fn hover(
19193        &self,
19194        buffer: &Entity<Buffer>,
19195        position: text::Anchor,
19196        cx: &mut App,
19197    ) -> Option<Task<Vec<project::Hover>>> {
19198        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19199    }
19200
19201    fn document_highlights(
19202        &self,
19203        buffer: &Entity<Buffer>,
19204        position: text::Anchor,
19205        cx: &mut App,
19206    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19207        Some(self.update(cx, |project, cx| {
19208            project.document_highlights(buffer, position, cx)
19209        }))
19210    }
19211
19212    fn definitions(
19213        &self,
19214        buffer: &Entity<Buffer>,
19215        position: text::Anchor,
19216        kind: GotoDefinitionKind,
19217        cx: &mut App,
19218    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19219        Some(self.update(cx, |project, cx| match kind {
19220            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19221            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19222            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19223            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19224        }))
19225    }
19226
19227    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19228        // TODO: make this work for remote projects
19229        self.update(cx, |this, cx| {
19230            buffer.update(cx, |buffer, cx| {
19231                this.any_language_server_supports_inlay_hints(buffer, cx)
19232            })
19233        })
19234    }
19235
19236    fn inlay_hints(
19237        &self,
19238        buffer_handle: Entity<Buffer>,
19239        range: Range<text::Anchor>,
19240        cx: &mut App,
19241    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19242        Some(self.update(cx, |project, cx| {
19243            project.inlay_hints(buffer_handle, range, cx)
19244        }))
19245    }
19246
19247    fn resolve_inlay_hint(
19248        &self,
19249        hint: InlayHint,
19250        buffer_handle: Entity<Buffer>,
19251        server_id: LanguageServerId,
19252        cx: &mut App,
19253    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19254        Some(self.update(cx, |project, cx| {
19255            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19256        }))
19257    }
19258
19259    fn range_for_rename(
19260        &self,
19261        buffer: &Entity<Buffer>,
19262        position: text::Anchor,
19263        cx: &mut App,
19264    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19265        Some(self.update(cx, |project, cx| {
19266            let buffer = buffer.clone();
19267            let task = project.prepare_rename(buffer.clone(), position, cx);
19268            cx.spawn(async move |_, cx| {
19269                Ok(match task.await? {
19270                    PrepareRenameResponse::Success(range) => Some(range),
19271                    PrepareRenameResponse::InvalidPosition => None,
19272                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19273                        // Fallback on using TreeSitter info to determine identifier range
19274                        buffer.update(cx, |buffer, _| {
19275                            let snapshot = buffer.snapshot();
19276                            let (range, kind) = snapshot.surrounding_word(position);
19277                            if kind != Some(CharKind::Word) {
19278                                return None;
19279                            }
19280                            Some(
19281                                snapshot.anchor_before(range.start)
19282                                    ..snapshot.anchor_after(range.end),
19283                            )
19284                        })?
19285                    }
19286                })
19287            })
19288        }))
19289    }
19290
19291    fn perform_rename(
19292        &self,
19293        buffer: &Entity<Buffer>,
19294        position: text::Anchor,
19295        new_name: String,
19296        cx: &mut App,
19297    ) -> Option<Task<Result<ProjectTransaction>>> {
19298        Some(self.update(cx, |project, cx| {
19299            project.perform_rename(buffer.clone(), position, new_name, cx)
19300        }))
19301    }
19302}
19303
19304fn inlay_hint_settings(
19305    location: Anchor,
19306    snapshot: &MultiBufferSnapshot,
19307    cx: &mut Context<Editor>,
19308) -> InlayHintSettings {
19309    let file = snapshot.file_at(location);
19310    let language = snapshot.language_at(location).map(|l| l.name());
19311    language_settings(language, file, cx).inlay_hints
19312}
19313
19314fn consume_contiguous_rows(
19315    contiguous_row_selections: &mut Vec<Selection<Point>>,
19316    selection: &Selection<Point>,
19317    display_map: &DisplaySnapshot,
19318    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19319) -> (MultiBufferRow, MultiBufferRow) {
19320    contiguous_row_selections.push(selection.clone());
19321    let start_row = MultiBufferRow(selection.start.row);
19322    let mut end_row = ending_row(selection, display_map);
19323
19324    while let Some(next_selection) = selections.peek() {
19325        if next_selection.start.row <= end_row.0 {
19326            end_row = ending_row(next_selection, display_map);
19327            contiguous_row_selections.push(selections.next().unwrap().clone());
19328        } else {
19329            break;
19330        }
19331    }
19332    (start_row, end_row)
19333}
19334
19335fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19336    if next_selection.end.column > 0 || next_selection.is_empty() {
19337        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19338    } else {
19339        MultiBufferRow(next_selection.end.row)
19340    }
19341}
19342
19343impl EditorSnapshot {
19344    pub fn remote_selections_in_range<'a>(
19345        &'a self,
19346        range: &'a Range<Anchor>,
19347        collaboration_hub: &dyn CollaborationHub,
19348        cx: &'a App,
19349    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19350        let participant_names = collaboration_hub.user_names(cx);
19351        let participant_indices = collaboration_hub.user_participant_indices(cx);
19352        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19353        let collaborators_by_replica_id = collaborators_by_peer_id
19354            .iter()
19355            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19356            .collect::<HashMap<_, _>>();
19357        self.buffer_snapshot
19358            .selections_in_range(range, false)
19359            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19360                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19361                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19362                let user_name = participant_names.get(&collaborator.user_id).cloned();
19363                Some(RemoteSelection {
19364                    replica_id,
19365                    selection,
19366                    cursor_shape,
19367                    line_mode,
19368                    participant_index,
19369                    peer_id: collaborator.peer_id,
19370                    user_name,
19371                })
19372            })
19373    }
19374
19375    pub fn hunks_for_ranges(
19376        &self,
19377        ranges: impl IntoIterator<Item = Range<Point>>,
19378    ) -> Vec<MultiBufferDiffHunk> {
19379        let mut hunks = Vec::new();
19380        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19381            HashMap::default();
19382        for query_range in ranges {
19383            let query_rows =
19384                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19385            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19386                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19387            ) {
19388                // Include deleted hunks that are adjacent to the query range, because
19389                // otherwise they would be missed.
19390                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19391                if hunk.status().is_deleted() {
19392                    intersects_range |= hunk.row_range.start == query_rows.end;
19393                    intersects_range |= hunk.row_range.end == query_rows.start;
19394                }
19395                if intersects_range {
19396                    if !processed_buffer_rows
19397                        .entry(hunk.buffer_id)
19398                        .or_default()
19399                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19400                    {
19401                        continue;
19402                    }
19403                    hunks.push(hunk);
19404                }
19405            }
19406        }
19407
19408        hunks
19409    }
19410
19411    fn display_diff_hunks_for_rows<'a>(
19412        &'a self,
19413        display_rows: Range<DisplayRow>,
19414        folded_buffers: &'a HashSet<BufferId>,
19415    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19416        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19417        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19418
19419        self.buffer_snapshot
19420            .diff_hunks_in_range(buffer_start..buffer_end)
19421            .filter_map(|hunk| {
19422                if folded_buffers.contains(&hunk.buffer_id) {
19423                    return None;
19424                }
19425
19426                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19427                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19428
19429                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19430                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19431
19432                let display_hunk = if hunk_display_start.column() != 0 {
19433                    DisplayDiffHunk::Folded {
19434                        display_row: hunk_display_start.row(),
19435                    }
19436                } else {
19437                    let mut end_row = hunk_display_end.row();
19438                    if hunk_display_end.column() > 0 {
19439                        end_row.0 += 1;
19440                    }
19441                    let is_created_file = hunk.is_created_file();
19442                    DisplayDiffHunk::Unfolded {
19443                        status: hunk.status(),
19444                        diff_base_byte_range: hunk.diff_base_byte_range,
19445                        display_row_range: hunk_display_start.row()..end_row,
19446                        multi_buffer_range: Anchor::range_in_buffer(
19447                            hunk.excerpt_id,
19448                            hunk.buffer_id,
19449                            hunk.buffer_range,
19450                        ),
19451                        is_created_file,
19452                    }
19453                };
19454
19455                Some(display_hunk)
19456            })
19457    }
19458
19459    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19460        self.display_snapshot.buffer_snapshot.language_at(position)
19461    }
19462
19463    pub fn is_focused(&self) -> bool {
19464        self.is_focused
19465    }
19466
19467    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19468        self.placeholder_text.as_ref()
19469    }
19470
19471    pub fn scroll_position(&self) -> gpui::Point<f32> {
19472        self.scroll_anchor.scroll_position(&self.display_snapshot)
19473    }
19474
19475    fn gutter_dimensions(
19476        &self,
19477        font_id: FontId,
19478        font_size: Pixels,
19479        max_line_number_width: Pixels,
19480        cx: &App,
19481    ) -> Option<GutterDimensions> {
19482        if !self.show_gutter {
19483            return None;
19484        }
19485
19486        let descent = cx.text_system().descent(font_id, font_size);
19487        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19488        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19489
19490        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19491            matches!(
19492                ProjectSettings::get_global(cx).git.git_gutter,
19493                Some(GitGutterSetting::TrackedFiles)
19494            )
19495        });
19496        let gutter_settings = EditorSettings::get_global(cx).gutter;
19497        let show_line_numbers = self
19498            .show_line_numbers
19499            .unwrap_or(gutter_settings.line_numbers);
19500        let line_gutter_width = if show_line_numbers {
19501            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19502            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19503            max_line_number_width.max(min_width_for_number_on_gutter)
19504        } else {
19505            0.0.into()
19506        };
19507
19508        let show_code_actions = self
19509            .show_code_actions
19510            .unwrap_or(gutter_settings.code_actions);
19511
19512        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19513        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19514
19515        let git_blame_entries_width =
19516            self.git_blame_gutter_max_author_length
19517                .map(|max_author_length| {
19518                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19519                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19520
19521                    /// The number of characters to dedicate to gaps and margins.
19522                    const SPACING_WIDTH: usize = 4;
19523
19524                    let max_char_count = max_author_length.min(renderer.max_author_length())
19525                        + ::git::SHORT_SHA_LENGTH
19526                        + MAX_RELATIVE_TIMESTAMP.len()
19527                        + SPACING_WIDTH;
19528
19529                    em_advance * max_char_count
19530                });
19531
19532        let is_singleton = self.buffer_snapshot.is_singleton();
19533
19534        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19535        left_padding += if !is_singleton {
19536            em_width * 4.0
19537        } else if show_code_actions || show_runnables || show_breakpoints {
19538            em_width * 3.0
19539        } else if show_git_gutter && show_line_numbers {
19540            em_width * 2.0
19541        } else if show_git_gutter || show_line_numbers {
19542            em_width
19543        } else {
19544            px(0.)
19545        };
19546
19547        let shows_folds = is_singleton && gutter_settings.folds;
19548
19549        let right_padding = if shows_folds && show_line_numbers {
19550            em_width * 4.0
19551        } else if shows_folds || (!is_singleton && show_line_numbers) {
19552            em_width * 3.0
19553        } else if show_line_numbers {
19554            em_width
19555        } else {
19556            px(0.)
19557        };
19558
19559        Some(GutterDimensions {
19560            left_padding,
19561            right_padding,
19562            width: line_gutter_width + left_padding + right_padding,
19563            margin: -descent,
19564            git_blame_entries_width,
19565        })
19566    }
19567
19568    pub fn render_crease_toggle(
19569        &self,
19570        buffer_row: MultiBufferRow,
19571        row_contains_cursor: bool,
19572        editor: Entity<Editor>,
19573        window: &mut Window,
19574        cx: &mut App,
19575    ) -> Option<AnyElement> {
19576        let folded = self.is_line_folded(buffer_row);
19577        let mut is_foldable = false;
19578
19579        if let Some(crease) = self
19580            .crease_snapshot
19581            .query_row(buffer_row, &self.buffer_snapshot)
19582        {
19583            is_foldable = true;
19584            match crease {
19585                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19586                    if let Some(render_toggle) = render_toggle {
19587                        let toggle_callback =
19588                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19589                                if folded {
19590                                    editor.update(cx, |editor, cx| {
19591                                        editor.fold_at(buffer_row, window, cx)
19592                                    });
19593                                } else {
19594                                    editor.update(cx, |editor, cx| {
19595                                        editor.unfold_at(buffer_row, window, cx)
19596                                    });
19597                                }
19598                            });
19599                        return Some((render_toggle)(
19600                            buffer_row,
19601                            folded,
19602                            toggle_callback,
19603                            window,
19604                            cx,
19605                        ));
19606                    }
19607                }
19608            }
19609        }
19610
19611        is_foldable |= self.starts_indent(buffer_row);
19612
19613        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19614            Some(
19615                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19616                    .toggle_state(folded)
19617                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19618                        if folded {
19619                            this.unfold_at(buffer_row, window, cx);
19620                        } else {
19621                            this.fold_at(buffer_row, window, cx);
19622                        }
19623                    }))
19624                    .into_any_element(),
19625            )
19626        } else {
19627            None
19628        }
19629    }
19630
19631    pub fn render_crease_trailer(
19632        &self,
19633        buffer_row: MultiBufferRow,
19634        window: &mut Window,
19635        cx: &mut App,
19636    ) -> Option<AnyElement> {
19637        let folded = self.is_line_folded(buffer_row);
19638        if let Crease::Inline { render_trailer, .. } = self
19639            .crease_snapshot
19640            .query_row(buffer_row, &self.buffer_snapshot)?
19641        {
19642            let render_trailer = render_trailer.as_ref()?;
19643            Some(render_trailer(buffer_row, folded, window, cx))
19644        } else {
19645            None
19646        }
19647    }
19648}
19649
19650impl Deref for EditorSnapshot {
19651    type Target = DisplaySnapshot;
19652
19653    fn deref(&self) -> &Self::Target {
19654        &self.display_snapshot
19655    }
19656}
19657
19658#[derive(Clone, Debug, PartialEq, Eq)]
19659pub enum EditorEvent {
19660    InputIgnored {
19661        text: Arc<str>,
19662    },
19663    InputHandled {
19664        utf16_range_to_replace: Option<Range<isize>>,
19665        text: Arc<str>,
19666    },
19667    ExcerptsAdded {
19668        buffer: Entity<Buffer>,
19669        predecessor: ExcerptId,
19670        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19671    },
19672    ExcerptsRemoved {
19673        ids: Vec<ExcerptId>,
19674    },
19675    BufferFoldToggled {
19676        ids: Vec<ExcerptId>,
19677        folded: bool,
19678    },
19679    ExcerptsEdited {
19680        ids: Vec<ExcerptId>,
19681    },
19682    ExcerptsExpanded {
19683        ids: Vec<ExcerptId>,
19684    },
19685    BufferEdited,
19686    Edited {
19687        transaction_id: clock::Lamport,
19688    },
19689    Reparsed(BufferId),
19690    Focused,
19691    FocusedIn,
19692    Blurred,
19693    DirtyChanged,
19694    Saved,
19695    TitleChanged,
19696    DiffBaseChanged,
19697    SelectionsChanged {
19698        local: bool,
19699    },
19700    ScrollPositionChanged {
19701        local: bool,
19702        autoscroll: bool,
19703    },
19704    Closed,
19705    TransactionUndone {
19706        transaction_id: clock::Lamport,
19707    },
19708    TransactionBegun {
19709        transaction_id: clock::Lamport,
19710    },
19711    Reloaded,
19712    CursorShapeChanged,
19713    PushedToNavHistory {
19714        anchor: Anchor,
19715        is_deactivate: bool,
19716    },
19717}
19718
19719impl EventEmitter<EditorEvent> for Editor {}
19720
19721impl Focusable for Editor {
19722    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19723        self.focus_handle.clone()
19724    }
19725}
19726
19727impl Render for Editor {
19728    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19729        let settings = ThemeSettings::get_global(cx);
19730
19731        let mut text_style = match self.mode {
19732            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19733                color: cx.theme().colors().editor_foreground,
19734                font_family: settings.ui_font.family.clone(),
19735                font_features: settings.ui_font.features.clone(),
19736                font_fallbacks: settings.ui_font.fallbacks.clone(),
19737                font_size: rems(0.875).into(),
19738                font_weight: settings.ui_font.weight,
19739                line_height: relative(settings.buffer_line_height.value()),
19740                ..Default::default()
19741            },
19742            EditorMode::Full { .. } => TextStyle {
19743                color: cx.theme().colors().editor_foreground,
19744                font_family: settings.buffer_font.family.clone(),
19745                font_features: settings.buffer_font.features.clone(),
19746                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19747                font_size: settings.buffer_font_size(cx).into(),
19748                font_weight: settings.buffer_font.weight,
19749                line_height: relative(settings.buffer_line_height.value()),
19750                ..Default::default()
19751            },
19752        };
19753        if let Some(text_style_refinement) = &self.text_style_refinement {
19754            text_style.refine(text_style_refinement)
19755        }
19756
19757        let background = match self.mode {
19758            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19759            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19760            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19761        };
19762
19763        EditorElement::new(
19764            &cx.entity(),
19765            EditorStyle {
19766                background,
19767                local_player: cx.theme().players().local(),
19768                text: text_style,
19769                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19770                syntax: cx.theme().syntax().clone(),
19771                status: cx.theme().status().clone(),
19772                inlay_hints_style: make_inlay_hints_style(cx),
19773                inline_completion_styles: make_suggestion_styles(cx),
19774                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19775            },
19776        )
19777    }
19778}
19779
19780impl EntityInputHandler for Editor {
19781    fn text_for_range(
19782        &mut self,
19783        range_utf16: Range<usize>,
19784        adjusted_range: &mut Option<Range<usize>>,
19785        _: &mut Window,
19786        cx: &mut Context<Self>,
19787    ) -> Option<String> {
19788        let snapshot = self.buffer.read(cx).read(cx);
19789        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19790        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19791        if (start.0..end.0) != range_utf16 {
19792            adjusted_range.replace(start.0..end.0);
19793        }
19794        Some(snapshot.text_for_range(start..end).collect())
19795    }
19796
19797    fn selected_text_range(
19798        &mut self,
19799        ignore_disabled_input: bool,
19800        _: &mut Window,
19801        cx: &mut Context<Self>,
19802    ) -> Option<UTF16Selection> {
19803        // Prevent the IME menu from appearing when holding down an alphabetic key
19804        // while input is disabled.
19805        if !ignore_disabled_input && !self.input_enabled {
19806            return None;
19807        }
19808
19809        let selection = self.selections.newest::<OffsetUtf16>(cx);
19810        let range = selection.range();
19811
19812        Some(UTF16Selection {
19813            range: range.start.0..range.end.0,
19814            reversed: selection.reversed,
19815        })
19816    }
19817
19818    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19819        let snapshot = self.buffer.read(cx).read(cx);
19820        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19821        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19822    }
19823
19824    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19825        self.clear_highlights::<InputComposition>(cx);
19826        self.ime_transaction.take();
19827    }
19828
19829    fn replace_text_in_range(
19830        &mut self,
19831        range_utf16: Option<Range<usize>>,
19832        text: &str,
19833        window: &mut Window,
19834        cx: &mut Context<Self>,
19835    ) {
19836        if !self.input_enabled {
19837            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19838            return;
19839        }
19840
19841        self.transact(window, cx, |this, window, cx| {
19842            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19843                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19844                Some(this.selection_replacement_ranges(range_utf16, cx))
19845            } else {
19846                this.marked_text_ranges(cx)
19847            };
19848
19849            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19850                let newest_selection_id = this.selections.newest_anchor().id;
19851                this.selections
19852                    .all::<OffsetUtf16>(cx)
19853                    .iter()
19854                    .zip(ranges_to_replace.iter())
19855                    .find_map(|(selection, range)| {
19856                        if selection.id == newest_selection_id {
19857                            Some(
19858                                (range.start.0 as isize - selection.head().0 as isize)
19859                                    ..(range.end.0 as isize - selection.head().0 as isize),
19860                            )
19861                        } else {
19862                            None
19863                        }
19864                    })
19865            });
19866
19867            cx.emit(EditorEvent::InputHandled {
19868                utf16_range_to_replace: range_to_replace,
19869                text: text.into(),
19870            });
19871
19872            if let Some(new_selected_ranges) = new_selected_ranges {
19873                this.change_selections(None, window, cx, |selections| {
19874                    selections.select_ranges(new_selected_ranges)
19875                });
19876                this.backspace(&Default::default(), window, cx);
19877            }
19878
19879            this.handle_input(text, window, cx);
19880        });
19881
19882        if let Some(transaction) = self.ime_transaction {
19883            self.buffer.update(cx, |buffer, cx| {
19884                buffer.group_until_transaction(transaction, cx);
19885            });
19886        }
19887
19888        self.unmark_text(window, cx);
19889    }
19890
19891    fn replace_and_mark_text_in_range(
19892        &mut self,
19893        range_utf16: Option<Range<usize>>,
19894        text: &str,
19895        new_selected_range_utf16: Option<Range<usize>>,
19896        window: &mut Window,
19897        cx: &mut Context<Self>,
19898    ) {
19899        if !self.input_enabled {
19900            return;
19901        }
19902
19903        let transaction = self.transact(window, cx, |this, window, cx| {
19904            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19905                let snapshot = this.buffer.read(cx).read(cx);
19906                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19907                    for marked_range in &mut marked_ranges {
19908                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19909                        marked_range.start.0 += relative_range_utf16.start;
19910                        marked_range.start =
19911                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19912                        marked_range.end =
19913                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19914                    }
19915                }
19916                Some(marked_ranges)
19917            } else if let Some(range_utf16) = range_utf16 {
19918                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19919                Some(this.selection_replacement_ranges(range_utf16, cx))
19920            } else {
19921                None
19922            };
19923
19924            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19925                let newest_selection_id = this.selections.newest_anchor().id;
19926                this.selections
19927                    .all::<OffsetUtf16>(cx)
19928                    .iter()
19929                    .zip(ranges_to_replace.iter())
19930                    .find_map(|(selection, range)| {
19931                        if selection.id == newest_selection_id {
19932                            Some(
19933                                (range.start.0 as isize - selection.head().0 as isize)
19934                                    ..(range.end.0 as isize - selection.head().0 as isize),
19935                            )
19936                        } else {
19937                            None
19938                        }
19939                    })
19940            });
19941
19942            cx.emit(EditorEvent::InputHandled {
19943                utf16_range_to_replace: range_to_replace,
19944                text: text.into(),
19945            });
19946
19947            if let Some(ranges) = ranges_to_replace {
19948                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19949            }
19950
19951            let marked_ranges = {
19952                let snapshot = this.buffer.read(cx).read(cx);
19953                this.selections
19954                    .disjoint_anchors()
19955                    .iter()
19956                    .map(|selection| {
19957                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19958                    })
19959                    .collect::<Vec<_>>()
19960            };
19961
19962            if text.is_empty() {
19963                this.unmark_text(window, cx);
19964            } else {
19965                this.highlight_text::<InputComposition>(
19966                    marked_ranges.clone(),
19967                    HighlightStyle {
19968                        underline: Some(UnderlineStyle {
19969                            thickness: px(1.),
19970                            color: None,
19971                            wavy: false,
19972                        }),
19973                        ..Default::default()
19974                    },
19975                    cx,
19976                );
19977            }
19978
19979            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19980            let use_autoclose = this.use_autoclose;
19981            let use_auto_surround = this.use_auto_surround;
19982            this.set_use_autoclose(false);
19983            this.set_use_auto_surround(false);
19984            this.handle_input(text, window, cx);
19985            this.set_use_autoclose(use_autoclose);
19986            this.set_use_auto_surround(use_auto_surround);
19987
19988            if let Some(new_selected_range) = new_selected_range_utf16 {
19989                let snapshot = this.buffer.read(cx).read(cx);
19990                let new_selected_ranges = marked_ranges
19991                    .into_iter()
19992                    .map(|marked_range| {
19993                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19994                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19995                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19996                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19997                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19998                    })
19999                    .collect::<Vec<_>>();
20000
20001                drop(snapshot);
20002                this.change_selections(None, window, cx, |selections| {
20003                    selections.select_ranges(new_selected_ranges)
20004                });
20005            }
20006        });
20007
20008        self.ime_transaction = self.ime_transaction.or(transaction);
20009        if let Some(transaction) = self.ime_transaction {
20010            self.buffer.update(cx, |buffer, cx| {
20011                buffer.group_until_transaction(transaction, cx);
20012            });
20013        }
20014
20015        if self.text_highlights::<InputComposition>(cx).is_none() {
20016            self.ime_transaction.take();
20017        }
20018    }
20019
20020    fn bounds_for_range(
20021        &mut self,
20022        range_utf16: Range<usize>,
20023        element_bounds: gpui::Bounds<Pixels>,
20024        window: &mut Window,
20025        cx: &mut Context<Self>,
20026    ) -> Option<gpui::Bounds<Pixels>> {
20027        let text_layout_details = self.text_layout_details(window);
20028        let gpui::Size {
20029            width: em_width,
20030            height: line_height,
20031        } = self.character_size(window);
20032
20033        let snapshot = self.snapshot(window, cx);
20034        let scroll_position = snapshot.scroll_position();
20035        let scroll_left = scroll_position.x * em_width;
20036
20037        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20038        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20039            + self.gutter_dimensions.width
20040            + self.gutter_dimensions.margin;
20041        let y = line_height * (start.row().as_f32() - scroll_position.y);
20042
20043        Some(Bounds {
20044            origin: element_bounds.origin + point(x, y),
20045            size: size(em_width, line_height),
20046        })
20047    }
20048
20049    fn character_index_for_point(
20050        &mut self,
20051        point: gpui::Point<Pixels>,
20052        _window: &mut Window,
20053        _cx: &mut Context<Self>,
20054    ) -> Option<usize> {
20055        let position_map = self.last_position_map.as_ref()?;
20056        if !position_map.text_hitbox.contains(&point) {
20057            return None;
20058        }
20059        let display_point = position_map.point_for_position(point).previous_valid;
20060        let anchor = position_map
20061            .snapshot
20062            .display_point_to_anchor(display_point, Bias::Left);
20063        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20064        Some(utf16_offset.0)
20065    }
20066}
20067
20068trait SelectionExt {
20069    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20070    fn spanned_rows(
20071        &self,
20072        include_end_if_at_line_start: bool,
20073        map: &DisplaySnapshot,
20074    ) -> Range<MultiBufferRow>;
20075}
20076
20077impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20078    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20079        let start = self
20080            .start
20081            .to_point(&map.buffer_snapshot)
20082            .to_display_point(map);
20083        let end = self
20084            .end
20085            .to_point(&map.buffer_snapshot)
20086            .to_display_point(map);
20087        if self.reversed {
20088            end..start
20089        } else {
20090            start..end
20091        }
20092    }
20093
20094    fn spanned_rows(
20095        &self,
20096        include_end_if_at_line_start: bool,
20097        map: &DisplaySnapshot,
20098    ) -> Range<MultiBufferRow> {
20099        let start = self.start.to_point(&map.buffer_snapshot);
20100        let mut end = self.end.to_point(&map.buffer_snapshot);
20101        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20102            end.row -= 1;
20103        }
20104
20105        let buffer_start = map.prev_line_boundary(start).0;
20106        let buffer_end = map.next_line_boundary(end).0;
20107        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20108    }
20109}
20110
20111impl<T: InvalidationRegion> InvalidationStack<T> {
20112    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20113    where
20114        S: Clone + ToOffset,
20115    {
20116        while let Some(region) = self.last() {
20117            let all_selections_inside_invalidation_ranges =
20118                if selections.len() == region.ranges().len() {
20119                    selections
20120                        .iter()
20121                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20122                        .all(|(selection, invalidation_range)| {
20123                            let head = selection.head().to_offset(buffer);
20124                            invalidation_range.start <= head && invalidation_range.end >= head
20125                        })
20126                } else {
20127                    false
20128                };
20129
20130            if all_selections_inside_invalidation_ranges {
20131                break;
20132            } else {
20133                self.pop();
20134            }
20135        }
20136    }
20137}
20138
20139impl<T> Default for InvalidationStack<T> {
20140    fn default() -> Self {
20141        Self(Default::default())
20142    }
20143}
20144
20145impl<T> Deref for InvalidationStack<T> {
20146    type Target = Vec<T>;
20147
20148    fn deref(&self) -> &Self::Target {
20149        &self.0
20150    }
20151}
20152
20153impl<T> DerefMut for InvalidationStack<T> {
20154    fn deref_mut(&mut self) -> &mut Self::Target {
20155        &mut self.0
20156    }
20157}
20158
20159impl InvalidationRegion for SnippetState {
20160    fn ranges(&self) -> &[Range<Anchor>] {
20161        &self.ranges[self.active_index]
20162    }
20163}
20164
20165fn inline_completion_edit_text(
20166    current_snapshot: &BufferSnapshot,
20167    edits: &[(Range<Anchor>, String)],
20168    edit_preview: &EditPreview,
20169    include_deletions: bool,
20170    cx: &App,
20171) -> HighlightedText {
20172    let edits = edits
20173        .iter()
20174        .map(|(anchor, text)| {
20175            (
20176                anchor.start.text_anchor..anchor.end.text_anchor,
20177                text.clone(),
20178            )
20179        })
20180        .collect::<Vec<_>>();
20181
20182    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20183}
20184
20185pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20186    match severity {
20187        DiagnosticSeverity::ERROR => colors.error,
20188        DiagnosticSeverity::WARNING => colors.warning,
20189        DiagnosticSeverity::INFORMATION => colors.info,
20190        DiagnosticSeverity::HINT => colors.info,
20191        _ => colors.ignored,
20192    }
20193}
20194
20195pub fn styled_runs_for_code_label<'a>(
20196    label: &'a CodeLabel,
20197    syntax_theme: &'a theme::SyntaxTheme,
20198) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20199    let fade_out = HighlightStyle {
20200        fade_out: Some(0.35),
20201        ..Default::default()
20202    };
20203
20204    let mut prev_end = label.filter_range.end;
20205    label
20206        .runs
20207        .iter()
20208        .enumerate()
20209        .flat_map(move |(ix, (range, highlight_id))| {
20210            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20211                style
20212            } else {
20213                return Default::default();
20214            };
20215            let mut muted_style = style;
20216            muted_style.highlight(fade_out);
20217
20218            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20219            if range.start >= label.filter_range.end {
20220                if range.start > prev_end {
20221                    runs.push((prev_end..range.start, fade_out));
20222                }
20223                runs.push((range.clone(), muted_style));
20224            } else if range.end <= label.filter_range.end {
20225                runs.push((range.clone(), style));
20226            } else {
20227                runs.push((range.start..label.filter_range.end, style));
20228                runs.push((label.filter_range.end..range.end, muted_style));
20229            }
20230            prev_end = cmp::max(prev_end, range.end);
20231
20232            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20233                runs.push((prev_end..label.text.len(), fade_out));
20234            }
20235
20236            runs
20237        })
20238}
20239
20240pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20241    let mut prev_index = 0;
20242    let mut prev_codepoint: Option<char> = None;
20243    text.char_indices()
20244        .chain([(text.len(), '\0')])
20245        .filter_map(move |(index, codepoint)| {
20246            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20247            let is_boundary = index == text.len()
20248                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20249                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20250            if is_boundary {
20251                let chunk = &text[prev_index..index];
20252                prev_index = index;
20253                Some(chunk)
20254            } else {
20255                None
20256            }
20257        })
20258}
20259
20260pub trait RangeToAnchorExt: Sized {
20261    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20262
20263    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20264        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20265        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20266    }
20267}
20268
20269impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20270    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20271        let start_offset = self.start.to_offset(snapshot);
20272        let end_offset = self.end.to_offset(snapshot);
20273        if start_offset == end_offset {
20274            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20275        } else {
20276            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20277        }
20278    }
20279}
20280
20281pub trait RowExt {
20282    fn as_f32(&self) -> f32;
20283
20284    fn next_row(&self) -> Self;
20285
20286    fn previous_row(&self) -> Self;
20287
20288    fn minus(&self, other: Self) -> u32;
20289}
20290
20291impl RowExt for DisplayRow {
20292    fn as_f32(&self) -> f32 {
20293        self.0 as f32
20294    }
20295
20296    fn next_row(&self) -> Self {
20297        Self(self.0 + 1)
20298    }
20299
20300    fn previous_row(&self) -> Self {
20301        Self(self.0.saturating_sub(1))
20302    }
20303
20304    fn minus(&self, other: Self) -> u32 {
20305        self.0 - other.0
20306    }
20307}
20308
20309impl RowExt for MultiBufferRow {
20310    fn as_f32(&self) -> f32 {
20311        self.0 as f32
20312    }
20313
20314    fn next_row(&self) -> Self {
20315        Self(self.0 + 1)
20316    }
20317
20318    fn previous_row(&self) -> Self {
20319        Self(self.0.saturating_sub(1))
20320    }
20321
20322    fn minus(&self, other: Self) -> u32 {
20323        self.0 - other.0
20324    }
20325}
20326
20327trait RowRangeExt {
20328    type Row;
20329
20330    fn len(&self) -> usize;
20331
20332    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20333}
20334
20335impl RowRangeExt for Range<MultiBufferRow> {
20336    type Row = MultiBufferRow;
20337
20338    fn len(&self) -> usize {
20339        (self.end.0 - self.start.0) as usize
20340    }
20341
20342    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20343        (self.start.0..self.end.0).map(MultiBufferRow)
20344    }
20345}
20346
20347impl RowRangeExt for Range<DisplayRow> {
20348    type Row = DisplayRow;
20349
20350    fn len(&self) -> usize {
20351        (self.end.0 - self.start.0) as usize
20352    }
20353
20354    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20355        (self.start.0..self.end.0).map(DisplayRow)
20356    }
20357}
20358
20359/// If select range has more than one line, we
20360/// just point the cursor to range.start.
20361fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20362    if range.start.row == range.end.row {
20363        range
20364    } else {
20365        range.start..range.start
20366    }
20367}
20368pub struct KillRing(ClipboardItem);
20369impl Global for KillRing {}
20370
20371const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20372
20373enum BreakpointPromptEditAction {
20374    Log,
20375    Condition,
20376    HitCondition,
20377}
20378
20379struct BreakpointPromptEditor {
20380    pub(crate) prompt: Entity<Editor>,
20381    editor: WeakEntity<Editor>,
20382    breakpoint_anchor: Anchor,
20383    breakpoint: Breakpoint,
20384    edit_action: BreakpointPromptEditAction,
20385    block_ids: HashSet<CustomBlockId>,
20386    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20387    _subscriptions: Vec<Subscription>,
20388}
20389
20390impl BreakpointPromptEditor {
20391    const MAX_LINES: u8 = 4;
20392
20393    fn new(
20394        editor: WeakEntity<Editor>,
20395        breakpoint_anchor: Anchor,
20396        breakpoint: Breakpoint,
20397        edit_action: BreakpointPromptEditAction,
20398        window: &mut Window,
20399        cx: &mut Context<Self>,
20400    ) -> Self {
20401        let base_text = match edit_action {
20402            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20403            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20404            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20405        }
20406        .map(|msg| msg.to_string())
20407        .unwrap_or_default();
20408
20409        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20410        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20411
20412        let prompt = cx.new(|cx| {
20413            let mut prompt = Editor::new(
20414                EditorMode::AutoHeight {
20415                    max_lines: Self::MAX_LINES as usize,
20416                },
20417                buffer,
20418                None,
20419                window,
20420                cx,
20421            );
20422            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20423            prompt.set_show_cursor_when_unfocused(false, cx);
20424            prompt.set_placeholder_text(
20425                match edit_action {
20426                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20427                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20428                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20429                },
20430                cx,
20431            );
20432
20433            prompt
20434        });
20435
20436        Self {
20437            prompt,
20438            editor,
20439            breakpoint_anchor,
20440            breakpoint,
20441            edit_action,
20442            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20443            block_ids: Default::default(),
20444            _subscriptions: vec![],
20445        }
20446    }
20447
20448    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20449        self.block_ids.extend(block_ids)
20450    }
20451
20452    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20453        if let Some(editor) = self.editor.upgrade() {
20454            let message = self
20455                .prompt
20456                .read(cx)
20457                .buffer
20458                .read(cx)
20459                .as_singleton()
20460                .expect("A multi buffer in breakpoint prompt isn't possible")
20461                .read(cx)
20462                .as_rope()
20463                .to_string();
20464
20465            editor.update(cx, |editor, cx| {
20466                editor.edit_breakpoint_at_anchor(
20467                    self.breakpoint_anchor,
20468                    self.breakpoint.clone(),
20469                    match self.edit_action {
20470                        BreakpointPromptEditAction::Log => {
20471                            BreakpointEditAction::EditLogMessage(message.into())
20472                        }
20473                        BreakpointPromptEditAction::Condition => {
20474                            BreakpointEditAction::EditCondition(message.into())
20475                        }
20476                        BreakpointPromptEditAction::HitCondition => {
20477                            BreakpointEditAction::EditHitCondition(message.into())
20478                        }
20479                    },
20480                    cx,
20481                );
20482
20483                editor.remove_blocks(self.block_ids.clone(), None, cx);
20484                cx.focus_self(window);
20485            });
20486        }
20487    }
20488
20489    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20490        self.editor
20491            .update(cx, |editor, cx| {
20492                editor.remove_blocks(self.block_ids.clone(), None, cx);
20493                window.focus(&editor.focus_handle);
20494            })
20495            .log_err();
20496    }
20497
20498    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20499        let settings = ThemeSettings::get_global(cx);
20500        let text_style = TextStyle {
20501            color: if self.prompt.read(cx).read_only(cx) {
20502                cx.theme().colors().text_disabled
20503            } else {
20504                cx.theme().colors().text
20505            },
20506            font_family: settings.buffer_font.family.clone(),
20507            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20508            font_size: settings.buffer_font_size(cx).into(),
20509            font_weight: settings.buffer_font.weight,
20510            line_height: relative(settings.buffer_line_height.value()),
20511            ..Default::default()
20512        };
20513        EditorElement::new(
20514            &self.prompt,
20515            EditorStyle {
20516                background: cx.theme().colors().editor_background,
20517                local_player: cx.theme().players().local(),
20518                text: text_style,
20519                ..Default::default()
20520            },
20521        )
20522    }
20523}
20524
20525impl Render for BreakpointPromptEditor {
20526    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20527        let gutter_dimensions = *self.gutter_dimensions.lock();
20528        h_flex()
20529            .key_context("Editor")
20530            .bg(cx.theme().colors().editor_background)
20531            .border_y_1()
20532            .border_color(cx.theme().status().info_border)
20533            .size_full()
20534            .py(window.line_height() / 2.5)
20535            .on_action(cx.listener(Self::confirm))
20536            .on_action(cx.listener(Self::cancel))
20537            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20538            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20539    }
20540}
20541
20542impl Focusable for BreakpointPromptEditor {
20543    fn focus_handle(&self, cx: &App) -> FocusHandle {
20544        self.prompt.focus_handle(cx)
20545    }
20546}
20547
20548fn all_edits_insertions_or_deletions(
20549    edits: &Vec<(Range<Anchor>, String)>,
20550    snapshot: &MultiBufferSnapshot,
20551) -> bool {
20552    let mut all_insertions = true;
20553    let mut all_deletions = true;
20554
20555    for (range, new_text) in edits.iter() {
20556        let range_is_empty = range.to_offset(&snapshot).is_empty();
20557        let text_is_empty = new_text.is_empty();
20558
20559        if range_is_empty != text_is_empty {
20560            if range_is_empty {
20561                all_deletions = false;
20562            } else {
20563                all_insertions = false;
20564            }
20565        } else {
20566            return false;
20567        }
20568
20569        if !all_insertions && !all_deletions {
20570            return false;
20571        }
20572    }
20573    all_insertions || all_deletions
20574}
20575
20576struct MissingEditPredictionKeybindingTooltip;
20577
20578impl Render for MissingEditPredictionKeybindingTooltip {
20579    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20580        ui::tooltip_container(window, cx, |container, _, cx| {
20581            container
20582                .flex_shrink_0()
20583                .max_w_80()
20584                .min_h(rems_from_px(124.))
20585                .justify_between()
20586                .child(
20587                    v_flex()
20588                        .flex_1()
20589                        .text_ui_sm(cx)
20590                        .child(Label::new("Conflict with Accept Keybinding"))
20591                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20592                )
20593                .child(
20594                    h_flex()
20595                        .pb_1()
20596                        .gap_1()
20597                        .items_end()
20598                        .w_full()
20599                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20600                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20601                        }))
20602                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20603                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20604                        })),
20605                )
20606        })
20607    }
20608}
20609
20610#[derive(Debug, Clone, Copy, PartialEq)]
20611pub struct LineHighlight {
20612    pub background: Background,
20613    pub border: Option<gpui::Hsla>,
20614}
20615
20616impl From<Hsla> for LineHighlight {
20617    fn from(hsla: Hsla) -> Self {
20618        Self {
20619            background: hsla.into(),
20620            border: None,
20621        }
20622    }
20623}
20624
20625impl From<Background> for LineHighlight {
20626    fn from(background: Background) -> Self {
20627        Self {
20628            background,
20629            border: None,
20630        }
20631    }
20632}
20633
20634fn render_diff_hunk_controls(
20635    row: u32,
20636    status: &DiffHunkStatus,
20637    hunk_range: Range<Anchor>,
20638    is_created_file: bool,
20639    line_height: Pixels,
20640    editor: &Entity<Editor>,
20641    _window: &mut Window,
20642    cx: &mut App,
20643) -> AnyElement {
20644    h_flex()
20645        .h(line_height)
20646        .mr_1()
20647        .gap_1()
20648        .px_0p5()
20649        .pb_1()
20650        .border_x_1()
20651        .border_b_1()
20652        .border_color(cx.theme().colors().border_variant)
20653        .rounded_b_lg()
20654        .bg(cx.theme().colors().editor_background)
20655        .gap_1()
20656        .occlude()
20657        .shadow_md()
20658        .child(if status.has_secondary_hunk() {
20659            Button::new(("stage", row as u64), "Stage")
20660                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20661                .tooltip({
20662                    let focus_handle = editor.focus_handle(cx);
20663                    move |window, cx| {
20664                        Tooltip::for_action_in(
20665                            "Stage Hunk",
20666                            &::git::ToggleStaged,
20667                            &focus_handle,
20668                            window,
20669                            cx,
20670                        )
20671                    }
20672                })
20673                .on_click({
20674                    let editor = editor.clone();
20675                    move |_event, _window, cx| {
20676                        editor.update(cx, |editor, cx| {
20677                            editor.stage_or_unstage_diff_hunks(
20678                                true,
20679                                vec![hunk_range.start..hunk_range.start],
20680                                cx,
20681                            );
20682                        });
20683                    }
20684                })
20685        } else {
20686            Button::new(("unstage", row as u64), "Unstage")
20687                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20688                .tooltip({
20689                    let focus_handle = editor.focus_handle(cx);
20690                    move |window, cx| {
20691                        Tooltip::for_action_in(
20692                            "Unstage Hunk",
20693                            &::git::ToggleStaged,
20694                            &focus_handle,
20695                            window,
20696                            cx,
20697                        )
20698                    }
20699                })
20700                .on_click({
20701                    let editor = editor.clone();
20702                    move |_event, _window, cx| {
20703                        editor.update(cx, |editor, cx| {
20704                            editor.stage_or_unstage_diff_hunks(
20705                                false,
20706                                vec![hunk_range.start..hunk_range.start],
20707                                cx,
20708                            );
20709                        });
20710                    }
20711                })
20712        })
20713        .child(
20714            Button::new(("restore", row as u64), "Restore")
20715                .tooltip({
20716                    let focus_handle = editor.focus_handle(cx);
20717                    move |window, cx| {
20718                        Tooltip::for_action_in(
20719                            "Restore Hunk",
20720                            &::git::Restore,
20721                            &focus_handle,
20722                            window,
20723                            cx,
20724                        )
20725                    }
20726                })
20727                .on_click({
20728                    let editor = editor.clone();
20729                    move |_event, window, cx| {
20730                        editor.update(cx, |editor, cx| {
20731                            let snapshot = editor.snapshot(window, cx);
20732                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20733                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20734                        });
20735                    }
20736                })
20737                .disabled(is_created_file),
20738        )
20739        .when(
20740            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20741            |el| {
20742                el.child(
20743                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20744                        .shape(IconButtonShape::Square)
20745                        .icon_size(IconSize::Small)
20746                        // .disabled(!has_multiple_hunks)
20747                        .tooltip({
20748                            let focus_handle = editor.focus_handle(cx);
20749                            move |window, cx| {
20750                                Tooltip::for_action_in(
20751                                    "Next Hunk",
20752                                    &GoToHunk,
20753                                    &focus_handle,
20754                                    window,
20755                                    cx,
20756                                )
20757                            }
20758                        })
20759                        .on_click({
20760                            let editor = editor.clone();
20761                            move |_event, window, cx| {
20762                                editor.update(cx, |editor, cx| {
20763                                    let snapshot = editor.snapshot(window, cx);
20764                                    let position =
20765                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20766                                    editor.go_to_hunk_before_or_after_position(
20767                                        &snapshot,
20768                                        position,
20769                                        Direction::Next,
20770                                        window,
20771                                        cx,
20772                                    );
20773                                    editor.expand_selected_diff_hunks(cx);
20774                                });
20775                            }
20776                        }),
20777                )
20778                .child(
20779                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20780                        .shape(IconButtonShape::Square)
20781                        .icon_size(IconSize::Small)
20782                        // .disabled(!has_multiple_hunks)
20783                        .tooltip({
20784                            let focus_handle = editor.focus_handle(cx);
20785                            move |window, cx| {
20786                                Tooltip::for_action_in(
20787                                    "Previous Hunk",
20788                                    &GoToPreviousHunk,
20789                                    &focus_handle,
20790                                    window,
20791                                    cx,
20792                                )
20793                            }
20794                        })
20795                        .on_click({
20796                            let editor = editor.clone();
20797                            move |_event, window, cx| {
20798                                editor.update(cx, |editor, cx| {
20799                                    let snapshot = editor.snapshot(window, cx);
20800                                    let point =
20801                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20802                                    editor.go_to_hunk_before_or_after_position(
20803                                        &snapshot,
20804                                        point,
20805                                        Direction::Prev,
20806                                        window,
20807                                        cx,
20808                                    );
20809                                    editor.expand_selected_diff_hunks(cx);
20810                                });
20811                            }
20812                        }),
20813                )
20814            },
20815        )
20816        .into_any_element()
20817}