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/// A set of caret positions, registered when the editor was edited.
  698pub struct ChangeList {
  699    changes: Vec<Vec<Anchor>>,
  700    /// Currently "selected" change.
  701    position: Option<usize>,
  702}
  703
  704impl ChangeList {
  705    pub fn new() -> Self {
  706        Self {
  707            changes: Vec::new(),
  708            position: None,
  709        }
  710    }
  711
  712    /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
  713    /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
  714    pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
  715        if self.changes.is_empty() {
  716            return None;
  717        }
  718
  719        let prev = self.position.unwrap_or(self.changes.len());
  720        let next = if direction == Direction::Prev {
  721            prev.saturating_sub(count)
  722        } else {
  723            (prev + count).min(self.changes.len() - 1)
  724        };
  725        self.position = Some(next);
  726        self.changes.get(next).map(|anchors| anchors.as_slice())
  727    }
  728
  729    /// Adds a new change to the list, resetting the change list position.
  730    pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
  731        self.position.take();
  732        if pop_state {
  733            self.changes.pop();
  734        }
  735        self.changes.push(new_positions.clone());
  736    }
  737
  738    pub fn last(&self) -> Option<&[Anchor]> {
  739        self.changes.last().map(|anchors| anchors.as_slice())
  740    }
  741}
  742
  743/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  744///
  745/// See the [module level documentation](self) for more information.
  746pub struct Editor {
  747    focus_handle: FocusHandle,
  748    last_focused_descendant: Option<WeakFocusHandle>,
  749    /// The text buffer being edited
  750    buffer: Entity<MultiBuffer>,
  751    /// Map of how text in the buffer should be displayed.
  752    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  753    pub display_map: Entity<DisplayMap>,
  754    pub selections: SelectionsCollection,
  755    pub scroll_manager: ScrollManager,
  756    /// When inline assist editors are linked, they all render cursors because
  757    /// typing enters text into each of them, even the ones that aren't focused.
  758    pub(crate) show_cursor_when_unfocused: bool,
  759    columnar_selection_tail: Option<Anchor>,
  760    add_selections_state: Option<AddSelectionsState>,
  761    select_next_state: Option<SelectNextState>,
  762    select_prev_state: Option<SelectNextState>,
  763    selection_history: SelectionHistory,
  764    autoclose_regions: Vec<AutocloseRegion>,
  765    snippet_stack: InvalidationStack<SnippetState>,
  766    select_syntax_node_history: SelectSyntaxNodeHistory,
  767    ime_transaction: Option<TransactionId>,
  768    active_diagnostics: ActiveDiagnostic,
  769    show_inline_diagnostics: bool,
  770    inline_diagnostics_update: Task<()>,
  771    inline_diagnostics_enabled: bool,
  772    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  773    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  774    hard_wrap: Option<usize>,
  775
  776    // TODO: make this a access method
  777    pub project: Option<Entity<Project>>,
  778    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  779    completion_provider: Option<Box<dyn CompletionProvider>>,
  780    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  781    blink_manager: Entity<BlinkManager>,
  782    show_cursor_names: bool,
  783    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  784    pub show_local_selections: bool,
  785    mode: EditorMode,
  786    show_breadcrumbs: bool,
  787    show_gutter: bool,
  788    show_scrollbars: bool,
  789    show_line_numbers: Option<bool>,
  790    use_relative_line_numbers: Option<bool>,
  791    show_git_diff_gutter: Option<bool>,
  792    show_code_actions: Option<bool>,
  793    show_runnables: Option<bool>,
  794    show_breakpoints: Option<bool>,
  795    show_wrap_guides: Option<bool>,
  796    show_indent_guides: Option<bool>,
  797    placeholder_text: Option<Arc<str>>,
  798    highlight_order: usize,
  799    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  800    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  801    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  802    scrollbar_marker_state: ScrollbarMarkerState,
  803    active_indent_guides_state: ActiveIndentGuidesState,
  804    nav_history: Option<ItemNavHistory>,
  805    context_menu: RefCell<Option<CodeContextMenu>>,
  806    context_menu_options: Option<ContextMenuOptions>,
  807    mouse_context_menu: Option<MouseContextMenu>,
  808    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  809    signature_help_state: SignatureHelpState,
  810    auto_signature_help: Option<bool>,
  811    find_all_references_task_sources: Vec<Anchor>,
  812    next_completion_id: CompletionId,
  813    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  814    code_actions_task: Option<Task<Result<()>>>,
  815    quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  816    debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
  817    document_highlights_task: Option<Task<()>>,
  818    linked_editing_range_task: Option<Task<Option<()>>>,
  819    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  820    pending_rename: Option<RenameState>,
  821    searchable: bool,
  822    cursor_shape: CursorShape,
  823    current_line_highlight: Option<CurrentLineHighlight>,
  824    collapse_matches: bool,
  825    autoindent_mode: Option<AutoindentMode>,
  826    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  827    input_enabled: bool,
  828    use_modal_editing: bool,
  829    read_only: bool,
  830    leader_peer_id: Option<PeerId>,
  831    remote_id: Option<ViewId>,
  832    hover_state: HoverState,
  833    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  834    gutter_hovered: bool,
  835    hovered_link_state: Option<HoveredLinkState>,
  836    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  837    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  838    active_inline_completion: Option<InlineCompletionState>,
  839    /// Used to prevent flickering as the user types while the menu is open
  840    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  841    edit_prediction_settings: EditPredictionSettings,
  842    inline_completions_hidden_for_vim_mode: bool,
  843    show_inline_completions_override: Option<bool>,
  844    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  845    edit_prediction_preview: EditPredictionPreview,
  846    edit_prediction_indent_conflict: bool,
  847    edit_prediction_requires_modifier_in_indent_conflict: bool,
  848    inlay_hint_cache: InlayHintCache,
  849    next_inlay_id: usize,
  850    _subscriptions: Vec<Subscription>,
  851    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  852    gutter_dimensions: GutterDimensions,
  853    style: Option<EditorStyle>,
  854    text_style_refinement: Option<TextStyleRefinement>,
  855    next_editor_action_id: EditorActionId,
  856    editor_actions:
  857        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  858    use_autoclose: bool,
  859    use_auto_surround: bool,
  860    auto_replace_emoji_shortcode: bool,
  861    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  862    show_git_blame_gutter: bool,
  863    show_git_blame_inline: bool,
  864    show_git_blame_inline_delay_task: Option<Task<()>>,
  865    pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
  866    git_blame_inline_enabled: bool,
  867    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  868    serialize_dirty_buffers: bool,
  869    show_selection_menu: Option<bool>,
  870    blame: Option<Entity<GitBlame>>,
  871    blame_subscription: Option<Subscription>,
  872    custom_context_menu: Option<
  873        Box<
  874            dyn 'static
  875                + Fn(
  876                    &mut Self,
  877                    DisplayPoint,
  878                    &mut Window,
  879                    &mut Context<Self>,
  880                ) -> Option<Entity<ui::ContextMenu>>,
  881        >,
  882    >,
  883    last_bounds: Option<Bounds<Pixels>>,
  884    last_position_map: Option<Rc<PositionMap>>,
  885    expect_bounds_change: Option<Bounds<Pixels>>,
  886    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  887    tasks_update_task: Option<Task<()>>,
  888    breakpoint_store: Option<Entity<BreakpointStore>>,
  889    /// Allow's a user to create a breakpoint by selecting this indicator
  890    /// It should be None while a user is not hovering over the gutter
  891    /// Otherwise it represents the point that the breakpoint will be shown
  892    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  893    in_project_search: bool,
  894    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  895    breadcrumb_header: Option<String>,
  896    focused_block: Option<FocusedBlock>,
  897    next_scroll_position: NextScrollCursorCenterTopBottom,
  898    addons: HashMap<TypeId, Box<dyn Addon>>,
  899    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  900    load_diff_task: Option<Shared<Task<()>>>,
  901    selection_mark_mode: bool,
  902    toggle_fold_multiple_buffers: Task<()>,
  903    _scroll_cursor_center_top_bottom_task: Task<()>,
  904    serialize_selections: Task<()>,
  905    serialize_folds: Task<()>,
  906    mouse_cursor_hidden: bool,
  907    hide_mouse_mode: HideMouseMode,
  908    pub change_list: ChangeList,
  909}
  910
  911#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  912enum NextScrollCursorCenterTopBottom {
  913    #[default]
  914    Center,
  915    Top,
  916    Bottom,
  917}
  918
  919impl NextScrollCursorCenterTopBottom {
  920    fn next(&self) -> Self {
  921        match self {
  922            Self::Center => Self::Top,
  923            Self::Top => Self::Bottom,
  924            Self::Bottom => Self::Center,
  925        }
  926    }
  927}
  928
  929#[derive(Clone)]
  930pub struct EditorSnapshot {
  931    pub mode: EditorMode,
  932    show_gutter: bool,
  933    show_line_numbers: Option<bool>,
  934    show_git_diff_gutter: Option<bool>,
  935    show_code_actions: Option<bool>,
  936    show_runnables: Option<bool>,
  937    show_breakpoints: Option<bool>,
  938    git_blame_gutter_max_author_length: Option<usize>,
  939    pub display_snapshot: DisplaySnapshot,
  940    pub placeholder_text: Option<Arc<str>>,
  941    is_focused: bool,
  942    scroll_anchor: ScrollAnchor,
  943    ongoing_scroll: OngoingScroll,
  944    current_line_highlight: CurrentLineHighlight,
  945    gutter_hovered: bool,
  946}
  947
  948#[derive(Default, Debug, Clone, Copy)]
  949pub struct GutterDimensions {
  950    pub left_padding: Pixels,
  951    pub right_padding: Pixels,
  952    pub width: Pixels,
  953    pub margin: Pixels,
  954    pub git_blame_entries_width: Option<Pixels>,
  955}
  956
  957impl GutterDimensions {
  958    /// The full width of the space taken up by the gutter.
  959    pub fn full_width(&self) -> Pixels {
  960        self.margin + self.width
  961    }
  962
  963    /// The width of the space reserved for the fold indicators,
  964    /// use alongside 'justify_end' and `gutter_width` to
  965    /// right align content with the line numbers
  966    pub fn fold_area_width(&self) -> Pixels {
  967        self.margin + self.right_padding
  968    }
  969}
  970
  971#[derive(Debug)]
  972pub struct RemoteSelection {
  973    pub replica_id: ReplicaId,
  974    pub selection: Selection<Anchor>,
  975    pub cursor_shape: CursorShape,
  976    pub peer_id: PeerId,
  977    pub line_mode: bool,
  978    pub participant_index: Option<ParticipantIndex>,
  979    pub user_name: Option<SharedString>,
  980}
  981
  982#[derive(Clone, Debug)]
  983struct SelectionHistoryEntry {
  984    selections: Arc<[Selection<Anchor>]>,
  985    select_next_state: Option<SelectNextState>,
  986    select_prev_state: Option<SelectNextState>,
  987    add_selections_state: Option<AddSelectionsState>,
  988}
  989
  990enum SelectionHistoryMode {
  991    Normal,
  992    Undoing,
  993    Redoing,
  994}
  995
  996#[derive(Clone, PartialEq, Eq, Hash)]
  997struct HoveredCursor {
  998    replica_id: u16,
  999    selection_id: usize,
 1000}
 1001
 1002impl Default for SelectionHistoryMode {
 1003    fn default() -> Self {
 1004        Self::Normal
 1005    }
 1006}
 1007
 1008#[derive(Default)]
 1009struct SelectionHistory {
 1010    #[allow(clippy::type_complexity)]
 1011    selections_by_transaction:
 1012        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 1013    mode: SelectionHistoryMode,
 1014    undo_stack: VecDeque<SelectionHistoryEntry>,
 1015    redo_stack: VecDeque<SelectionHistoryEntry>,
 1016}
 1017
 1018impl SelectionHistory {
 1019    fn insert_transaction(
 1020        &mut self,
 1021        transaction_id: TransactionId,
 1022        selections: Arc<[Selection<Anchor>]>,
 1023    ) {
 1024        self.selections_by_transaction
 1025            .insert(transaction_id, (selections, None));
 1026    }
 1027
 1028    #[allow(clippy::type_complexity)]
 1029    fn transaction(
 1030        &self,
 1031        transaction_id: TransactionId,
 1032    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1033        self.selections_by_transaction.get(&transaction_id)
 1034    }
 1035
 1036    #[allow(clippy::type_complexity)]
 1037    fn transaction_mut(
 1038        &mut self,
 1039        transaction_id: TransactionId,
 1040    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 1041        self.selections_by_transaction.get_mut(&transaction_id)
 1042    }
 1043
 1044    fn push(&mut self, entry: SelectionHistoryEntry) {
 1045        if !entry.selections.is_empty() {
 1046            match self.mode {
 1047                SelectionHistoryMode::Normal => {
 1048                    self.push_undo(entry);
 1049                    self.redo_stack.clear();
 1050                }
 1051                SelectionHistoryMode::Undoing => self.push_redo(entry),
 1052                SelectionHistoryMode::Redoing => self.push_undo(entry),
 1053            }
 1054        }
 1055    }
 1056
 1057    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 1058        if self
 1059            .undo_stack
 1060            .back()
 1061            .map_or(true, |e| e.selections != entry.selections)
 1062        {
 1063            self.undo_stack.push_back(entry);
 1064            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1065                self.undo_stack.pop_front();
 1066            }
 1067        }
 1068    }
 1069
 1070    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 1071        if self
 1072            .redo_stack
 1073            .back()
 1074            .map_or(true, |e| e.selections != entry.selections)
 1075        {
 1076            self.redo_stack.push_back(entry);
 1077            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 1078                self.redo_stack.pop_front();
 1079            }
 1080        }
 1081    }
 1082}
 1083
 1084struct RowHighlight {
 1085    index: usize,
 1086    range: Range<Anchor>,
 1087    color: Hsla,
 1088    should_autoscroll: bool,
 1089}
 1090
 1091#[derive(Clone, Debug)]
 1092struct AddSelectionsState {
 1093    above: bool,
 1094    stack: Vec<usize>,
 1095}
 1096
 1097#[derive(Clone)]
 1098struct SelectNextState {
 1099    query: AhoCorasick,
 1100    wordwise: bool,
 1101    done: bool,
 1102}
 1103
 1104impl std::fmt::Debug for SelectNextState {
 1105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1106        f.debug_struct(std::any::type_name::<Self>())
 1107            .field("wordwise", &self.wordwise)
 1108            .field("done", &self.done)
 1109            .finish()
 1110    }
 1111}
 1112
 1113#[derive(Debug)]
 1114struct AutocloseRegion {
 1115    selection_id: usize,
 1116    range: Range<Anchor>,
 1117    pair: BracketPair,
 1118}
 1119
 1120#[derive(Debug)]
 1121struct SnippetState {
 1122    ranges: Vec<Vec<Range<Anchor>>>,
 1123    active_index: usize,
 1124    choices: Vec<Option<Vec<String>>>,
 1125}
 1126
 1127#[doc(hidden)]
 1128pub struct RenameState {
 1129    pub range: Range<Anchor>,
 1130    pub old_name: Arc<str>,
 1131    pub editor: Entity<Editor>,
 1132    block_id: CustomBlockId,
 1133}
 1134
 1135struct InvalidationStack<T>(Vec<T>);
 1136
 1137struct RegisteredInlineCompletionProvider {
 1138    provider: Arc<dyn InlineCompletionProviderHandle>,
 1139    _subscription: Subscription,
 1140}
 1141
 1142#[derive(Debug, PartialEq, Eq)]
 1143pub struct ActiveDiagnosticGroup {
 1144    pub active_range: Range<Anchor>,
 1145    pub active_message: String,
 1146    pub group_id: usize,
 1147    pub blocks: HashSet<CustomBlockId>,
 1148}
 1149
 1150#[derive(Debug, PartialEq, Eq)]
 1151#[allow(clippy::large_enum_variant)]
 1152pub(crate) enum ActiveDiagnostic {
 1153    None,
 1154    All,
 1155    Group(ActiveDiagnosticGroup),
 1156}
 1157
 1158#[derive(Serialize, Deserialize, Clone, Debug)]
 1159pub struct ClipboardSelection {
 1160    /// The number of bytes in this selection.
 1161    pub len: usize,
 1162    /// Whether this was a full-line selection.
 1163    pub is_entire_line: bool,
 1164    /// The indentation of the first line when this content was originally copied.
 1165    pub first_line_indent: u32,
 1166}
 1167
 1168// selections, scroll behavior, was newest selection reversed
 1169type SelectSyntaxNodeHistoryState = (
 1170    Box<[Selection<usize>]>,
 1171    SelectSyntaxNodeScrollBehavior,
 1172    bool,
 1173);
 1174
 1175#[derive(Default)]
 1176struct SelectSyntaxNodeHistory {
 1177    stack: Vec<SelectSyntaxNodeHistoryState>,
 1178    // disable temporarily to allow changing selections without losing the stack
 1179    pub disable_clearing: bool,
 1180}
 1181
 1182impl SelectSyntaxNodeHistory {
 1183    pub fn try_clear(&mut self) {
 1184        if !self.disable_clearing {
 1185            self.stack.clear();
 1186        }
 1187    }
 1188
 1189    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1190        self.stack.push(selection);
 1191    }
 1192
 1193    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1194        self.stack.pop()
 1195    }
 1196}
 1197
 1198enum SelectSyntaxNodeScrollBehavior {
 1199    CursorTop,
 1200    FitSelection,
 1201    CursorBottom,
 1202}
 1203
 1204#[derive(Debug)]
 1205pub(crate) struct NavigationData {
 1206    cursor_anchor: Anchor,
 1207    cursor_position: Point,
 1208    scroll_anchor: ScrollAnchor,
 1209    scroll_top_row: u32,
 1210}
 1211
 1212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1213pub enum GotoDefinitionKind {
 1214    Symbol,
 1215    Declaration,
 1216    Type,
 1217    Implementation,
 1218}
 1219
 1220#[derive(Debug, Clone)]
 1221enum InlayHintRefreshReason {
 1222    ModifiersChanged(bool),
 1223    Toggle(bool),
 1224    SettingsChange(InlayHintSettings),
 1225    NewLinesShown,
 1226    BufferEdited(HashSet<Arc<Language>>),
 1227    RefreshRequested,
 1228    ExcerptsRemoved(Vec<ExcerptId>),
 1229}
 1230
 1231impl InlayHintRefreshReason {
 1232    fn description(&self) -> &'static str {
 1233        match self {
 1234            Self::ModifiersChanged(_) => "modifiers changed",
 1235            Self::Toggle(_) => "toggle",
 1236            Self::SettingsChange(_) => "settings change",
 1237            Self::NewLinesShown => "new lines shown",
 1238            Self::BufferEdited(_) => "buffer edited",
 1239            Self::RefreshRequested => "refresh requested",
 1240            Self::ExcerptsRemoved(_) => "excerpts removed",
 1241        }
 1242    }
 1243}
 1244
 1245pub enum FormatTarget {
 1246    Buffers,
 1247    Ranges(Vec<Range<MultiBufferPoint>>),
 1248}
 1249
 1250pub(crate) struct FocusedBlock {
 1251    id: BlockId,
 1252    focus_handle: WeakFocusHandle,
 1253}
 1254
 1255#[derive(Clone)]
 1256enum JumpData {
 1257    MultiBufferRow {
 1258        row: MultiBufferRow,
 1259        line_offset_from_top: u32,
 1260    },
 1261    MultiBufferPoint {
 1262        excerpt_id: ExcerptId,
 1263        position: Point,
 1264        anchor: text::Anchor,
 1265        line_offset_from_top: u32,
 1266    },
 1267}
 1268
 1269pub enum MultibufferSelectionMode {
 1270    First,
 1271    All,
 1272}
 1273
 1274#[derive(Clone, Copy, Debug, Default)]
 1275pub struct RewrapOptions {
 1276    pub override_language_settings: bool,
 1277    pub preserve_existing_whitespace: bool,
 1278}
 1279
 1280impl Editor {
 1281    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1282        let buffer = cx.new(|cx| Buffer::local("", cx));
 1283        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1284        Self::new(
 1285            EditorMode::SingleLine { auto_width: false },
 1286            buffer,
 1287            None,
 1288            window,
 1289            cx,
 1290        )
 1291    }
 1292
 1293    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1294        let buffer = cx.new(|cx| Buffer::local("", cx));
 1295        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1296        Self::new(EditorMode::full(), buffer, None, window, cx)
 1297    }
 1298
 1299    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1300        let buffer = cx.new(|cx| Buffer::local("", cx));
 1301        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1302        Self::new(
 1303            EditorMode::SingleLine { auto_width: true },
 1304            buffer,
 1305            None,
 1306            window,
 1307            cx,
 1308        )
 1309    }
 1310
 1311    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1312        let buffer = cx.new(|cx| Buffer::local("", cx));
 1313        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1314        Self::new(
 1315            EditorMode::AutoHeight { max_lines },
 1316            buffer,
 1317            None,
 1318            window,
 1319            cx,
 1320        )
 1321    }
 1322
 1323    pub fn for_buffer(
 1324        buffer: Entity<Buffer>,
 1325        project: Option<Entity<Project>>,
 1326        window: &mut Window,
 1327        cx: &mut Context<Self>,
 1328    ) -> Self {
 1329        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1330        Self::new(EditorMode::full(), buffer, project, window, cx)
 1331    }
 1332
 1333    pub fn for_multibuffer(
 1334        buffer: Entity<MultiBuffer>,
 1335        project: Option<Entity<Project>>,
 1336        window: &mut Window,
 1337        cx: &mut Context<Self>,
 1338    ) -> Self {
 1339        Self::new(EditorMode::full(), buffer, project, window, cx)
 1340    }
 1341
 1342    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1343        let mut clone = Self::new(
 1344            self.mode,
 1345            self.buffer.clone(),
 1346            self.project.clone(),
 1347            window,
 1348            cx,
 1349        );
 1350        self.display_map.update(cx, |display_map, cx| {
 1351            let snapshot = display_map.snapshot(cx);
 1352            clone.display_map.update(cx, |display_map, cx| {
 1353                display_map.set_state(&snapshot, cx);
 1354            });
 1355        });
 1356        clone.folds_did_change(cx);
 1357        clone.selections.clone_state(&self.selections);
 1358        clone.scroll_manager.clone_state(&self.scroll_manager);
 1359        clone.searchable = self.searchable;
 1360        clone.read_only = self.read_only;
 1361        clone
 1362    }
 1363
 1364    pub fn new(
 1365        mode: EditorMode,
 1366        buffer: Entity<MultiBuffer>,
 1367        project: Option<Entity<Project>>,
 1368        window: &mut Window,
 1369        cx: &mut Context<Self>,
 1370    ) -> Self {
 1371        let style = window.text_style();
 1372        let font_size = style.font_size.to_pixels(window.rem_size());
 1373        let editor = cx.entity().downgrade();
 1374        let fold_placeholder = FoldPlaceholder {
 1375            constrain_width: true,
 1376            render: Arc::new(move |fold_id, fold_range, cx| {
 1377                let editor = editor.clone();
 1378                div()
 1379                    .id(fold_id)
 1380                    .bg(cx.theme().colors().ghost_element_background)
 1381                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1382                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1383                    .rounded_xs()
 1384                    .size_full()
 1385                    .cursor_pointer()
 1386                    .child("")
 1387                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1388                    .on_click(move |_, _window, cx| {
 1389                        editor
 1390                            .update(cx, |editor, cx| {
 1391                                editor.unfold_ranges(
 1392                                    &[fold_range.start..fold_range.end],
 1393                                    true,
 1394                                    false,
 1395                                    cx,
 1396                                );
 1397                                cx.stop_propagation();
 1398                            })
 1399                            .ok();
 1400                    })
 1401                    .into_any()
 1402            }),
 1403            merge_adjacent: true,
 1404            ..Default::default()
 1405        };
 1406        let display_map = cx.new(|cx| {
 1407            DisplayMap::new(
 1408                buffer.clone(),
 1409                style.font(),
 1410                font_size,
 1411                None,
 1412                FILE_HEADER_HEIGHT,
 1413                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1414                fold_placeholder,
 1415                cx,
 1416            )
 1417        });
 1418
 1419        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1420
 1421        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1422
 1423        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1424            .then(|| language_settings::SoftWrap::None);
 1425
 1426        let mut project_subscriptions = Vec::new();
 1427        if mode.is_full() {
 1428            if let Some(project) = project.as_ref() {
 1429                project_subscriptions.push(cx.subscribe_in(
 1430                    project,
 1431                    window,
 1432                    |editor, _, event, window, cx| match event {
 1433                        project::Event::RefreshCodeLens => {
 1434                            // we always query lens with actions, without storing them, always refreshing them
 1435                        }
 1436                        project::Event::RefreshInlayHints => {
 1437                            editor
 1438                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1439                        }
 1440                        project::Event::SnippetEdit(id, snippet_edits) => {
 1441                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1442                                let focus_handle = editor.focus_handle(cx);
 1443                                if focus_handle.is_focused(window) {
 1444                                    let snapshot = buffer.read(cx).snapshot();
 1445                                    for (range, snippet) in snippet_edits {
 1446                                        let editor_range =
 1447                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1448                                        editor
 1449                                            .insert_snippet(
 1450                                                &[editor_range],
 1451                                                snippet.clone(),
 1452                                                window,
 1453                                                cx,
 1454                                            )
 1455                                            .ok();
 1456                                    }
 1457                                }
 1458                            }
 1459                        }
 1460                        _ => {}
 1461                    },
 1462                ));
 1463                if let Some(task_inventory) = project
 1464                    .read(cx)
 1465                    .task_store()
 1466                    .read(cx)
 1467                    .task_inventory()
 1468                    .cloned()
 1469                {
 1470                    project_subscriptions.push(cx.observe_in(
 1471                        &task_inventory,
 1472                        window,
 1473                        |editor, _, window, cx| {
 1474                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1475                        },
 1476                    ));
 1477                };
 1478
 1479                project_subscriptions.push(cx.subscribe_in(
 1480                    &project.read(cx).breakpoint_store(),
 1481                    window,
 1482                    |editor, _, event, window, cx| match event {
 1483                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1484                            if editor.go_to_active_debug_line(window, cx) {
 1485                                cx.stop_propagation();
 1486                            }
 1487                        }
 1488                        _ => {}
 1489                    },
 1490                ));
 1491            }
 1492        }
 1493
 1494        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1495
 1496        let inlay_hint_settings =
 1497            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1498        let focus_handle = cx.focus_handle();
 1499        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1500            .detach();
 1501        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1502            .detach();
 1503        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1504            .detach();
 1505        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1506            .detach();
 1507
 1508        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1509            Some(false)
 1510        } else {
 1511            None
 1512        };
 1513
 1514        let breakpoint_store = match (mode, project.as_ref()) {
 1515            (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1516            _ => None,
 1517        };
 1518
 1519        let mut code_action_providers = Vec::new();
 1520        let mut load_uncommitted_diff = None;
 1521        if let Some(project) = project.clone() {
 1522            load_uncommitted_diff = Some(
 1523                get_uncommitted_diff_for_buffer(
 1524                    &project,
 1525                    buffer.read(cx).all_buffers(),
 1526                    buffer.clone(),
 1527                    cx,
 1528                )
 1529                .shared(),
 1530            );
 1531            code_action_providers.push(Rc::new(project) as Rc<_>);
 1532        }
 1533
 1534        let mut this = Self {
 1535            focus_handle,
 1536            show_cursor_when_unfocused: false,
 1537            last_focused_descendant: None,
 1538            buffer: buffer.clone(),
 1539            display_map: display_map.clone(),
 1540            selections,
 1541            scroll_manager: ScrollManager::new(cx),
 1542            columnar_selection_tail: None,
 1543            add_selections_state: None,
 1544            select_next_state: None,
 1545            select_prev_state: None,
 1546            selection_history: Default::default(),
 1547            autoclose_regions: Default::default(),
 1548            snippet_stack: Default::default(),
 1549            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1550            ime_transaction: Default::default(),
 1551            active_diagnostics: ActiveDiagnostic::None,
 1552            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1553            inline_diagnostics_update: Task::ready(()),
 1554            inline_diagnostics: Vec::new(),
 1555            soft_wrap_mode_override,
 1556            hard_wrap: None,
 1557            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1558            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1559            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1560            project,
 1561            blink_manager: blink_manager.clone(),
 1562            show_local_selections: true,
 1563            show_scrollbars: true,
 1564            mode,
 1565            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1566            show_gutter: mode.is_full(),
 1567            show_line_numbers: None,
 1568            use_relative_line_numbers: None,
 1569            show_git_diff_gutter: None,
 1570            show_code_actions: None,
 1571            show_runnables: None,
 1572            show_breakpoints: None,
 1573            show_wrap_guides: None,
 1574            show_indent_guides,
 1575            placeholder_text: None,
 1576            highlight_order: 0,
 1577            highlighted_rows: HashMap::default(),
 1578            background_highlights: Default::default(),
 1579            gutter_highlights: TreeMap::default(),
 1580            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1581            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1582            nav_history: None,
 1583            context_menu: RefCell::new(None),
 1584            context_menu_options: None,
 1585            mouse_context_menu: None,
 1586            completion_tasks: Default::default(),
 1587            signature_help_state: SignatureHelpState::default(),
 1588            auto_signature_help: None,
 1589            find_all_references_task_sources: Vec::new(),
 1590            next_completion_id: 0,
 1591            next_inlay_id: 0,
 1592            code_action_providers,
 1593            available_code_actions: Default::default(),
 1594            code_actions_task: Default::default(),
 1595            quick_selection_highlight_task: Default::default(),
 1596            debounced_selection_highlight_task: Default::default(),
 1597            document_highlights_task: Default::default(),
 1598            linked_editing_range_task: Default::default(),
 1599            pending_rename: Default::default(),
 1600            searchable: true,
 1601            cursor_shape: EditorSettings::get_global(cx)
 1602                .cursor_shape
 1603                .unwrap_or_default(),
 1604            current_line_highlight: None,
 1605            autoindent_mode: Some(AutoindentMode::EachLine),
 1606            collapse_matches: false,
 1607            workspace: None,
 1608            input_enabled: true,
 1609            use_modal_editing: mode.is_full(),
 1610            read_only: false,
 1611            use_autoclose: true,
 1612            use_auto_surround: true,
 1613            auto_replace_emoji_shortcode: false,
 1614            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1615            leader_peer_id: None,
 1616            remote_id: None,
 1617            hover_state: Default::default(),
 1618            pending_mouse_down: None,
 1619            hovered_link_state: Default::default(),
 1620            edit_prediction_provider: None,
 1621            active_inline_completion: None,
 1622            stale_inline_completion_in_menu: None,
 1623            edit_prediction_preview: EditPredictionPreview::Inactive {
 1624                released_too_fast: false,
 1625            },
 1626            inline_diagnostics_enabled: mode.is_full(),
 1627            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1628
 1629            gutter_hovered: false,
 1630            pixel_position_of_newest_cursor: None,
 1631            last_bounds: None,
 1632            last_position_map: None,
 1633            expect_bounds_change: None,
 1634            gutter_dimensions: GutterDimensions::default(),
 1635            style: None,
 1636            show_cursor_names: false,
 1637            hovered_cursors: Default::default(),
 1638            next_editor_action_id: EditorActionId::default(),
 1639            editor_actions: Rc::default(),
 1640            inline_completions_hidden_for_vim_mode: false,
 1641            show_inline_completions_override: None,
 1642            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1643            edit_prediction_settings: EditPredictionSettings::Disabled,
 1644            edit_prediction_indent_conflict: false,
 1645            edit_prediction_requires_modifier_in_indent_conflict: true,
 1646            custom_context_menu: None,
 1647            show_git_blame_gutter: false,
 1648            show_git_blame_inline: false,
 1649            show_selection_menu: None,
 1650            show_git_blame_inline_delay_task: None,
 1651            git_blame_inline_tooltip: None,
 1652            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1653            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1654            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1655                .session
 1656                .restore_unsaved_buffers,
 1657            blame: None,
 1658            blame_subscription: None,
 1659            tasks: Default::default(),
 1660
 1661            breakpoint_store,
 1662            gutter_breakpoint_indicator: (None, None),
 1663            _subscriptions: vec![
 1664                cx.observe(&buffer, Self::on_buffer_changed),
 1665                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1666                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1667                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1668                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1669                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1670                cx.observe_window_activation(window, |editor, window, cx| {
 1671                    let active = window.is_window_active();
 1672                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1673                        if active {
 1674                            blink_manager.enable(cx);
 1675                        } else {
 1676                            blink_manager.disable(cx);
 1677                        }
 1678                    });
 1679                }),
 1680            ],
 1681            tasks_update_task: None,
 1682            linked_edit_ranges: Default::default(),
 1683            in_project_search: false,
 1684            previous_search_ranges: None,
 1685            breadcrumb_header: None,
 1686            focused_block: None,
 1687            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1688            addons: HashMap::default(),
 1689            registered_buffers: HashMap::default(),
 1690            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1691            selection_mark_mode: false,
 1692            toggle_fold_multiple_buffers: Task::ready(()),
 1693            serialize_selections: Task::ready(()),
 1694            serialize_folds: Task::ready(()),
 1695            text_style_refinement: None,
 1696            load_diff_task: load_uncommitted_diff,
 1697            mouse_cursor_hidden: false,
 1698            hide_mouse_mode: EditorSettings::get_global(cx)
 1699                .hide_mouse
 1700                .unwrap_or_default(),
 1701            change_list: ChangeList::new(),
 1702        };
 1703        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1704            this._subscriptions
 1705                .push(cx.observe(breakpoints, |_, _, cx| {
 1706                    cx.notify();
 1707                }));
 1708        }
 1709        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1710        this._subscriptions.extend(project_subscriptions);
 1711
 1712        this._subscriptions.push(cx.subscribe_in(
 1713            &cx.entity(),
 1714            window,
 1715            |editor, _, e: &EditorEvent, window, cx| match e {
 1716                EditorEvent::ScrollPositionChanged { local, .. } => {
 1717                    if *local {
 1718                        let new_anchor = editor.scroll_manager.anchor();
 1719                        let snapshot = editor.snapshot(window, cx);
 1720                        editor.update_restoration_data(cx, move |data| {
 1721                            data.scroll_position = (
 1722                                new_anchor.top_row(&snapshot.buffer_snapshot),
 1723                                new_anchor.offset,
 1724                            );
 1725                        });
 1726                        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 1727                    }
 1728                }
 1729                EditorEvent::Edited { .. } => {
 1730                    if !vim_enabled(cx) {
 1731                        let (map, selections) = editor.selections.all_adjusted_display(cx);
 1732                        let pop_state = editor
 1733                            .change_list
 1734                            .last()
 1735                            .map(|previous| {
 1736                                previous.len() == selections.len()
 1737                                    && previous.iter().enumerate().all(|(ix, p)| {
 1738                                        p.to_display_point(&map).row()
 1739                                            == selections[ix].head().row()
 1740                                    })
 1741                            })
 1742                            .unwrap_or(false);
 1743                        let new_positions = selections
 1744                            .into_iter()
 1745                            .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
 1746                            .collect();
 1747                        editor
 1748                            .change_list
 1749                            .push_to_change_list(pop_state, new_positions);
 1750                    }
 1751                }
 1752                _ => (),
 1753            },
 1754        ));
 1755
 1756        this.end_selection(window, cx);
 1757        this.scroll_manager.show_scrollbars(window, cx);
 1758        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1759
 1760        if mode.is_full() {
 1761            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1762            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1763
 1764            if this.git_blame_inline_enabled {
 1765                this.git_blame_inline_enabled = true;
 1766                this.start_git_blame_inline(false, window, cx);
 1767            }
 1768
 1769            this.go_to_active_debug_line(window, cx);
 1770
 1771            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1772                if let Some(project) = this.project.as_ref() {
 1773                    let handle = project.update(cx, |project, cx| {
 1774                        project.register_buffer_with_language_servers(&buffer, cx)
 1775                    });
 1776                    this.registered_buffers
 1777                        .insert(buffer.read(cx).remote_id(), handle);
 1778                }
 1779            }
 1780        }
 1781
 1782        this.report_editor_event("Editor Opened", None, cx);
 1783        this
 1784    }
 1785
 1786    pub fn deploy_mouse_context_menu(
 1787        &mut self,
 1788        position: gpui::Point<Pixels>,
 1789        context_menu: Entity<ContextMenu>,
 1790        window: &mut Window,
 1791        cx: &mut Context<Self>,
 1792    ) {
 1793        self.mouse_context_menu = Some(MouseContextMenu::new(
 1794            self,
 1795            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1796            context_menu,
 1797            window,
 1798            cx,
 1799        ));
 1800    }
 1801
 1802    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1803        self.mouse_context_menu
 1804            .as_ref()
 1805            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1806    }
 1807
 1808    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1809        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1810    }
 1811
 1812    fn key_context_internal(
 1813        &self,
 1814        has_active_edit_prediction: bool,
 1815        window: &Window,
 1816        cx: &App,
 1817    ) -> KeyContext {
 1818        let mut key_context = KeyContext::new_with_defaults();
 1819        key_context.add("Editor");
 1820        let mode = match self.mode {
 1821            EditorMode::SingleLine { .. } => "single_line",
 1822            EditorMode::AutoHeight { .. } => "auto_height",
 1823            EditorMode::Full { .. } => "full",
 1824        };
 1825
 1826        if EditorSettings::jupyter_enabled(cx) {
 1827            key_context.add("jupyter");
 1828        }
 1829
 1830        key_context.set("mode", mode);
 1831        if self.pending_rename.is_some() {
 1832            key_context.add("renaming");
 1833        }
 1834
 1835        match self.context_menu.borrow().as_ref() {
 1836            Some(CodeContextMenu::Completions(_)) => {
 1837                key_context.add("menu");
 1838                key_context.add("showing_completions");
 1839            }
 1840            Some(CodeContextMenu::CodeActions(_)) => {
 1841                key_context.add("menu");
 1842                key_context.add("showing_code_actions")
 1843            }
 1844            None => {}
 1845        }
 1846
 1847        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1848        if !self.focus_handle(cx).contains_focused(window, cx)
 1849            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1850        {
 1851            for addon in self.addons.values() {
 1852                addon.extend_key_context(&mut key_context, cx)
 1853            }
 1854        }
 1855
 1856        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1857            if let Some(extension) = singleton_buffer
 1858                .read(cx)
 1859                .file()
 1860                .and_then(|file| file.path().extension()?.to_str())
 1861            {
 1862                key_context.set("extension", extension.to_string());
 1863            }
 1864        } else {
 1865            key_context.add("multibuffer");
 1866        }
 1867
 1868        if has_active_edit_prediction {
 1869            if self.edit_prediction_in_conflict() {
 1870                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1871            } else {
 1872                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1873                key_context.add("copilot_suggestion");
 1874            }
 1875        }
 1876
 1877        if self.selection_mark_mode {
 1878            key_context.add("selection_mode");
 1879        }
 1880
 1881        key_context
 1882    }
 1883
 1884    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 1885        self.mouse_cursor_hidden = match origin {
 1886            HideMouseCursorOrigin::TypingAction => {
 1887                matches!(
 1888                    self.hide_mouse_mode,
 1889                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 1890                )
 1891            }
 1892            HideMouseCursorOrigin::MovementAction => {
 1893                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 1894            }
 1895        };
 1896    }
 1897
 1898    pub fn edit_prediction_in_conflict(&self) -> bool {
 1899        if !self.show_edit_predictions_in_menu() {
 1900            return false;
 1901        }
 1902
 1903        let showing_completions = self
 1904            .context_menu
 1905            .borrow()
 1906            .as_ref()
 1907            .map_or(false, |context| {
 1908                matches!(context, CodeContextMenu::Completions(_))
 1909            });
 1910
 1911        showing_completions
 1912            || self.edit_prediction_requires_modifier()
 1913            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1914            // bindings to insert tab characters.
 1915            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1916    }
 1917
 1918    pub fn accept_edit_prediction_keybind(
 1919        &self,
 1920        window: &Window,
 1921        cx: &App,
 1922    ) -> AcceptEditPredictionBinding {
 1923        let key_context = self.key_context_internal(true, window, cx);
 1924        let in_conflict = self.edit_prediction_in_conflict();
 1925
 1926        AcceptEditPredictionBinding(
 1927            window
 1928                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1929                .into_iter()
 1930                .filter(|binding| {
 1931                    !in_conflict
 1932                        || binding
 1933                            .keystrokes()
 1934                            .first()
 1935                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1936                })
 1937                .rev()
 1938                .min_by_key(|binding| {
 1939                    binding
 1940                        .keystrokes()
 1941                        .first()
 1942                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1943                }),
 1944        )
 1945    }
 1946
 1947    pub fn new_file(
 1948        workspace: &mut Workspace,
 1949        _: &workspace::NewFile,
 1950        window: &mut Window,
 1951        cx: &mut Context<Workspace>,
 1952    ) {
 1953        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1954            "Failed to create buffer",
 1955            window,
 1956            cx,
 1957            |e, _, _| match e.error_code() {
 1958                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1959                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1960                e.error_tag("required").unwrap_or("the latest version")
 1961            )),
 1962                _ => None,
 1963            },
 1964        );
 1965    }
 1966
 1967    pub fn new_in_workspace(
 1968        workspace: &mut Workspace,
 1969        window: &mut Window,
 1970        cx: &mut Context<Workspace>,
 1971    ) -> Task<Result<Entity<Editor>>> {
 1972        let project = workspace.project().clone();
 1973        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1974
 1975        cx.spawn_in(window, async move |workspace, cx| {
 1976            let buffer = create.await?;
 1977            workspace.update_in(cx, |workspace, window, cx| {
 1978                let editor =
 1979                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1980                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1981                editor
 1982            })
 1983        })
 1984    }
 1985
 1986    fn new_file_vertical(
 1987        workspace: &mut Workspace,
 1988        _: &workspace::NewFileSplitVertical,
 1989        window: &mut Window,
 1990        cx: &mut Context<Workspace>,
 1991    ) {
 1992        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1993    }
 1994
 1995    fn new_file_horizontal(
 1996        workspace: &mut Workspace,
 1997        _: &workspace::NewFileSplitHorizontal,
 1998        window: &mut Window,
 1999        cx: &mut Context<Workspace>,
 2000    ) {
 2001        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 2002    }
 2003
 2004    fn new_file_in_direction(
 2005        workspace: &mut Workspace,
 2006        direction: SplitDirection,
 2007        window: &mut Window,
 2008        cx: &mut Context<Workspace>,
 2009    ) {
 2010        let project = workspace.project().clone();
 2011        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2012
 2013        cx.spawn_in(window, async move |workspace, cx| {
 2014            let buffer = create.await?;
 2015            workspace.update_in(cx, move |workspace, window, cx| {
 2016                workspace.split_item(
 2017                    direction,
 2018                    Box::new(
 2019                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 2020                    ),
 2021                    window,
 2022                    cx,
 2023                )
 2024            })?;
 2025            anyhow::Ok(())
 2026        })
 2027        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 2028            match e.error_code() {
 2029                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2030                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2031                e.error_tag("required").unwrap_or("the latest version")
 2032            )),
 2033                _ => None,
 2034            }
 2035        });
 2036    }
 2037
 2038    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2039        self.leader_peer_id
 2040    }
 2041
 2042    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 2043        &self.buffer
 2044    }
 2045
 2046    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 2047        self.workspace.as_ref()?.0.upgrade()
 2048    }
 2049
 2050    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 2051        self.buffer().read(cx).title(cx)
 2052    }
 2053
 2054    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 2055        let git_blame_gutter_max_author_length = self
 2056            .render_git_blame_gutter(cx)
 2057            .then(|| {
 2058                if let Some(blame) = self.blame.as_ref() {
 2059                    let max_author_length =
 2060                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 2061                    Some(max_author_length)
 2062                } else {
 2063                    None
 2064                }
 2065            })
 2066            .flatten();
 2067
 2068        EditorSnapshot {
 2069            mode: self.mode,
 2070            show_gutter: self.show_gutter,
 2071            show_line_numbers: self.show_line_numbers,
 2072            show_git_diff_gutter: self.show_git_diff_gutter,
 2073            show_code_actions: self.show_code_actions,
 2074            show_runnables: self.show_runnables,
 2075            show_breakpoints: self.show_breakpoints,
 2076            git_blame_gutter_max_author_length,
 2077            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2078            scroll_anchor: self.scroll_manager.anchor(),
 2079            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2080            placeholder_text: self.placeholder_text.clone(),
 2081            is_focused: self.focus_handle.is_focused(window),
 2082            current_line_highlight: self
 2083                .current_line_highlight
 2084                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2085            gutter_hovered: self.gutter_hovered,
 2086        }
 2087    }
 2088
 2089    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 2090        self.buffer.read(cx).language_at(point, cx)
 2091    }
 2092
 2093    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 2094        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2095    }
 2096
 2097    pub fn active_excerpt(
 2098        &self,
 2099        cx: &App,
 2100    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 2101        self.buffer
 2102            .read(cx)
 2103            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2104    }
 2105
 2106    pub fn mode(&self) -> EditorMode {
 2107        self.mode
 2108    }
 2109
 2110    pub fn set_mode(&mut self, mode: EditorMode) {
 2111        self.mode = mode;
 2112    }
 2113
 2114    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2115        self.collaboration_hub.as_deref()
 2116    }
 2117
 2118    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2119        self.collaboration_hub = Some(hub);
 2120    }
 2121
 2122    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 2123        self.in_project_search = in_project_search;
 2124    }
 2125
 2126    pub fn set_custom_context_menu(
 2127        &mut self,
 2128        f: impl 'static
 2129        + Fn(
 2130            &mut Self,
 2131            DisplayPoint,
 2132            &mut Window,
 2133            &mut Context<Self>,
 2134        ) -> Option<Entity<ui::ContextMenu>>,
 2135    ) {
 2136        self.custom_context_menu = Some(Box::new(f))
 2137    }
 2138
 2139    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2140        self.completion_provider = provider;
 2141    }
 2142
 2143    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2144        self.semantics_provider.clone()
 2145    }
 2146
 2147    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2148        self.semantics_provider = provider;
 2149    }
 2150
 2151    pub fn set_edit_prediction_provider<T>(
 2152        &mut self,
 2153        provider: Option<Entity<T>>,
 2154        window: &mut Window,
 2155        cx: &mut Context<Self>,
 2156    ) where
 2157        T: EditPredictionProvider,
 2158    {
 2159        self.edit_prediction_provider =
 2160            provider.map(|provider| RegisteredInlineCompletionProvider {
 2161                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2162                    if this.focus_handle.is_focused(window) {
 2163                        this.update_visible_inline_completion(window, cx);
 2164                    }
 2165                }),
 2166                provider: Arc::new(provider),
 2167            });
 2168        self.update_edit_prediction_settings(cx);
 2169        self.refresh_inline_completion(false, false, window, cx);
 2170    }
 2171
 2172    pub fn placeholder_text(&self) -> Option<&str> {
 2173        self.placeholder_text.as_deref()
 2174    }
 2175
 2176    pub fn set_placeholder_text(
 2177        &mut self,
 2178        placeholder_text: impl Into<Arc<str>>,
 2179        cx: &mut Context<Self>,
 2180    ) {
 2181        let placeholder_text = Some(placeholder_text.into());
 2182        if self.placeholder_text != placeholder_text {
 2183            self.placeholder_text = placeholder_text;
 2184            cx.notify();
 2185        }
 2186    }
 2187
 2188    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2189        self.cursor_shape = cursor_shape;
 2190
 2191        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2192        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2193
 2194        cx.notify();
 2195    }
 2196
 2197    pub fn set_current_line_highlight(
 2198        &mut self,
 2199        current_line_highlight: Option<CurrentLineHighlight>,
 2200    ) {
 2201        self.current_line_highlight = current_line_highlight;
 2202    }
 2203
 2204    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2205        self.collapse_matches = collapse_matches;
 2206    }
 2207
 2208    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2209        let buffers = self.buffer.read(cx).all_buffers();
 2210        let Some(project) = self.project.as_ref() else {
 2211            return;
 2212        };
 2213        project.update(cx, |project, cx| {
 2214            for buffer in buffers {
 2215                self.registered_buffers
 2216                    .entry(buffer.read(cx).remote_id())
 2217                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2218            }
 2219        })
 2220    }
 2221
 2222    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2223        if self.collapse_matches {
 2224            return range.start..range.start;
 2225        }
 2226        range.clone()
 2227    }
 2228
 2229    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2230        if self.display_map.read(cx).clip_at_line_ends != clip {
 2231            self.display_map
 2232                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2233        }
 2234    }
 2235
 2236    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2237        self.input_enabled = input_enabled;
 2238    }
 2239
 2240    pub fn set_inline_completions_hidden_for_vim_mode(
 2241        &mut self,
 2242        hidden: bool,
 2243        window: &mut Window,
 2244        cx: &mut Context<Self>,
 2245    ) {
 2246        if hidden != self.inline_completions_hidden_for_vim_mode {
 2247            self.inline_completions_hidden_for_vim_mode = hidden;
 2248            if hidden {
 2249                self.update_visible_inline_completion(window, cx);
 2250            } else {
 2251                self.refresh_inline_completion(true, false, window, cx);
 2252            }
 2253        }
 2254    }
 2255
 2256    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2257        self.menu_inline_completions_policy = value;
 2258    }
 2259
 2260    pub fn set_autoindent(&mut self, autoindent: bool) {
 2261        if autoindent {
 2262            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2263        } else {
 2264            self.autoindent_mode = None;
 2265        }
 2266    }
 2267
 2268    pub fn read_only(&self, cx: &App) -> bool {
 2269        self.read_only || self.buffer.read(cx).read_only()
 2270    }
 2271
 2272    pub fn set_read_only(&mut self, read_only: bool) {
 2273        self.read_only = read_only;
 2274    }
 2275
 2276    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2277        self.use_autoclose = autoclose;
 2278    }
 2279
 2280    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2281        self.use_auto_surround = auto_surround;
 2282    }
 2283
 2284    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2285        self.auto_replace_emoji_shortcode = auto_replace;
 2286    }
 2287
 2288    pub fn toggle_edit_predictions(
 2289        &mut self,
 2290        _: &ToggleEditPrediction,
 2291        window: &mut Window,
 2292        cx: &mut Context<Self>,
 2293    ) {
 2294        if self.show_inline_completions_override.is_some() {
 2295            self.set_show_edit_predictions(None, window, cx);
 2296        } else {
 2297            let show_edit_predictions = !self.edit_predictions_enabled();
 2298            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2299        }
 2300    }
 2301
 2302    pub fn set_show_edit_predictions(
 2303        &mut self,
 2304        show_edit_predictions: Option<bool>,
 2305        window: &mut Window,
 2306        cx: &mut Context<Self>,
 2307    ) {
 2308        self.show_inline_completions_override = show_edit_predictions;
 2309        self.update_edit_prediction_settings(cx);
 2310
 2311        if let Some(false) = show_edit_predictions {
 2312            self.discard_inline_completion(false, cx);
 2313        } else {
 2314            self.refresh_inline_completion(false, true, window, cx);
 2315        }
 2316    }
 2317
 2318    fn inline_completions_disabled_in_scope(
 2319        &self,
 2320        buffer: &Entity<Buffer>,
 2321        buffer_position: language::Anchor,
 2322        cx: &App,
 2323    ) -> bool {
 2324        let snapshot = buffer.read(cx).snapshot();
 2325        let settings = snapshot.settings_at(buffer_position, cx);
 2326
 2327        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2328            return false;
 2329        };
 2330
 2331        scope.override_name().map_or(false, |scope_name| {
 2332            settings
 2333                .edit_predictions_disabled_in
 2334                .iter()
 2335                .any(|s| s == scope_name)
 2336        })
 2337    }
 2338
 2339    pub fn set_use_modal_editing(&mut self, to: bool) {
 2340        self.use_modal_editing = to;
 2341    }
 2342
 2343    pub fn use_modal_editing(&self) -> bool {
 2344        self.use_modal_editing
 2345    }
 2346
 2347    fn selections_did_change(
 2348        &mut self,
 2349        local: bool,
 2350        old_cursor_position: &Anchor,
 2351        show_completions: bool,
 2352        window: &mut Window,
 2353        cx: &mut Context<Self>,
 2354    ) {
 2355        window.invalidate_character_coordinates();
 2356
 2357        // Copy selections to primary selection buffer
 2358        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2359        if local {
 2360            let selections = self.selections.all::<usize>(cx);
 2361            let buffer_handle = self.buffer.read(cx).read(cx);
 2362
 2363            let mut text = String::new();
 2364            for (index, selection) in selections.iter().enumerate() {
 2365                let text_for_selection = buffer_handle
 2366                    .text_for_range(selection.start..selection.end)
 2367                    .collect::<String>();
 2368
 2369                text.push_str(&text_for_selection);
 2370                if index != selections.len() - 1 {
 2371                    text.push('\n');
 2372                }
 2373            }
 2374
 2375            if !text.is_empty() {
 2376                cx.write_to_primary(ClipboardItem::new_string(text));
 2377            }
 2378        }
 2379
 2380        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2381            self.buffer.update(cx, |buffer, cx| {
 2382                buffer.set_active_selections(
 2383                    &self.selections.disjoint_anchors(),
 2384                    self.selections.line_mode,
 2385                    self.cursor_shape,
 2386                    cx,
 2387                )
 2388            });
 2389        }
 2390        let display_map = self
 2391            .display_map
 2392            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2393        let buffer = &display_map.buffer_snapshot;
 2394        self.add_selections_state = None;
 2395        self.select_next_state = None;
 2396        self.select_prev_state = None;
 2397        self.select_syntax_node_history.try_clear();
 2398        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2399        self.snippet_stack
 2400            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2401        self.take_rename(false, window, cx);
 2402
 2403        let new_cursor_position = self.selections.newest_anchor().head();
 2404
 2405        self.push_to_nav_history(
 2406            *old_cursor_position,
 2407            Some(new_cursor_position.to_point(buffer)),
 2408            false,
 2409            cx,
 2410        );
 2411
 2412        if local {
 2413            let new_cursor_position = self.selections.newest_anchor().head();
 2414            let mut context_menu = self.context_menu.borrow_mut();
 2415            let completion_menu = match context_menu.as_ref() {
 2416                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2417                _ => {
 2418                    *context_menu = None;
 2419                    None
 2420                }
 2421            };
 2422            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2423                if !self.registered_buffers.contains_key(&buffer_id) {
 2424                    if let Some(project) = self.project.as_ref() {
 2425                        project.update(cx, |project, cx| {
 2426                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2427                                return;
 2428                            };
 2429                            self.registered_buffers.insert(
 2430                                buffer_id,
 2431                                project.register_buffer_with_language_servers(&buffer, cx),
 2432                            );
 2433                        })
 2434                    }
 2435                }
 2436            }
 2437
 2438            if let Some(completion_menu) = completion_menu {
 2439                let cursor_position = new_cursor_position.to_offset(buffer);
 2440                let (word_range, kind) =
 2441                    buffer.surrounding_word(completion_menu.initial_position, true);
 2442                if kind == Some(CharKind::Word)
 2443                    && word_range.to_inclusive().contains(&cursor_position)
 2444                {
 2445                    let mut completion_menu = completion_menu.clone();
 2446                    drop(context_menu);
 2447
 2448                    let query = Self::completion_query(buffer, cursor_position);
 2449                    cx.spawn(async move |this, cx| {
 2450                        completion_menu
 2451                            .filter(query.as_deref(), cx.background_executor().clone())
 2452                            .await;
 2453
 2454                        this.update(cx, |this, cx| {
 2455                            let mut context_menu = this.context_menu.borrow_mut();
 2456                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2457                            else {
 2458                                return;
 2459                            };
 2460
 2461                            if menu.id > completion_menu.id {
 2462                                return;
 2463                            }
 2464
 2465                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2466                            drop(context_menu);
 2467                            cx.notify();
 2468                        })
 2469                    })
 2470                    .detach();
 2471
 2472                    if show_completions {
 2473                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2474                    }
 2475                } else {
 2476                    drop(context_menu);
 2477                    self.hide_context_menu(window, cx);
 2478                }
 2479            } else {
 2480                drop(context_menu);
 2481            }
 2482
 2483            hide_hover(self, cx);
 2484
 2485            if old_cursor_position.to_display_point(&display_map).row()
 2486                != new_cursor_position.to_display_point(&display_map).row()
 2487            {
 2488                self.available_code_actions.take();
 2489            }
 2490            self.refresh_code_actions(window, cx);
 2491            self.refresh_document_highlights(cx);
 2492            self.refresh_selected_text_highlights(window, cx);
 2493            refresh_matching_bracket_highlights(self, window, cx);
 2494            self.update_visible_inline_completion(window, cx);
 2495            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2496            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2497            if self.git_blame_inline_enabled {
 2498                self.start_inline_blame_timer(window, cx);
 2499            }
 2500        }
 2501
 2502        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2503        cx.emit(EditorEvent::SelectionsChanged { local });
 2504
 2505        let selections = &self.selections.disjoint;
 2506        if selections.len() == 1 {
 2507            cx.emit(SearchEvent::ActiveMatchChanged)
 2508        }
 2509        if local {
 2510            if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
 2511                let inmemory_selections = selections
 2512                    .iter()
 2513                    .map(|s| {
 2514                        text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
 2515                            ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
 2516                    })
 2517                    .collect();
 2518                self.update_restoration_data(cx, |data| {
 2519                    data.selections = inmemory_selections;
 2520                });
 2521
 2522                if WorkspaceSettings::get(None, cx).restore_on_startup
 2523                    != RestoreOnStartupBehavior::None
 2524                {
 2525                    if let Some(workspace_id) =
 2526                        self.workspace.as_ref().and_then(|workspace| workspace.1)
 2527                    {
 2528                        let snapshot = self.buffer().read(cx).snapshot(cx);
 2529                        let selections = selections.clone();
 2530                        let background_executor = cx.background_executor().clone();
 2531                        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2532                        self.serialize_selections = cx.background_spawn(async move {
 2533                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2534                    let db_selections = selections
 2535                        .iter()
 2536                        .map(|selection| {
 2537                            (
 2538                                selection.start.to_offset(&snapshot),
 2539                                selection.end.to_offset(&snapshot),
 2540                            )
 2541                        })
 2542                        .collect();
 2543
 2544                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2545                        .await
 2546                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2547                        .log_err();
 2548                });
 2549                    }
 2550                }
 2551            }
 2552        }
 2553
 2554        cx.notify();
 2555    }
 2556
 2557    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2558        use text::ToOffset as _;
 2559        use text::ToPoint as _;
 2560
 2561        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
 2562            return;
 2563        }
 2564
 2565        let Some(singleton) = self.buffer().read(cx).as_singleton() else {
 2566            return;
 2567        };
 2568
 2569        let snapshot = singleton.read(cx).snapshot();
 2570        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2571            let display_snapshot = display_map.snapshot(cx);
 2572
 2573            display_snapshot
 2574                .folds_in_range(0..display_snapshot.buffer_snapshot.len())
 2575                .map(|fold| {
 2576                    fold.range.start.text_anchor.to_point(&snapshot)
 2577                        ..fold.range.end.text_anchor.to_point(&snapshot)
 2578                })
 2579                .collect()
 2580        });
 2581        self.update_restoration_data(cx, |data| {
 2582            data.folds = inmemory_folds;
 2583        });
 2584
 2585        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2586            return;
 2587        };
 2588        let background_executor = cx.background_executor().clone();
 2589        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2590        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2591            display_map
 2592                .snapshot(cx)
 2593                .folds_in_range(0..snapshot.len())
 2594                .map(|fold| {
 2595                    (
 2596                        fold.range.start.text_anchor.to_offset(&snapshot),
 2597                        fold.range.end.text_anchor.to_offset(&snapshot),
 2598                    )
 2599                })
 2600                .collect()
 2601        });
 2602        self.serialize_folds = cx.background_spawn(async move {
 2603            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2604            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2605                .await
 2606                .with_context(|| {
 2607                    format!(
 2608                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2609                    )
 2610                })
 2611                .log_err();
 2612        });
 2613    }
 2614
 2615    pub fn sync_selections(
 2616        &mut self,
 2617        other: Entity<Editor>,
 2618        cx: &mut Context<Self>,
 2619    ) -> gpui::Subscription {
 2620        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2621        self.selections.change_with(cx, |selections| {
 2622            selections.select_anchors(other_selections);
 2623        });
 2624
 2625        let other_subscription =
 2626            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2627                EditorEvent::SelectionsChanged { local: true } => {
 2628                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2629                    if other_selections.is_empty() {
 2630                        return;
 2631                    }
 2632                    this.selections.change_with(cx, |selections| {
 2633                        selections.select_anchors(other_selections);
 2634                    });
 2635                }
 2636                _ => {}
 2637            });
 2638
 2639        let this_subscription =
 2640            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2641                EditorEvent::SelectionsChanged { local: true } => {
 2642                    let these_selections = this.selections.disjoint.to_vec();
 2643                    if these_selections.is_empty() {
 2644                        return;
 2645                    }
 2646                    other.update(cx, |other_editor, cx| {
 2647                        other_editor.selections.change_with(cx, |selections| {
 2648                            selections.select_anchors(these_selections);
 2649                        })
 2650                    });
 2651                }
 2652                _ => {}
 2653            });
 2654
 2655        Subscription::join(other_subscription, this_subscription)
 2656    }
 2657
 2658    pub fn change_selections<R>(
 2659        &mut self,
 2660        autoscroll: Option<Autoscroll>,
 2661        window: &mut Window,
 2662        cx: &mut Context<Self>,
 2663        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2664    ) -> R {
 2665        self.change_selections_inner(autoscroll, true, window, cx, change)
 2666    }
 2667
 2668    fn change_selections_inner<R>(
 2669        &mut self,
 2670        autoscroll: Option<Autoscroll>,
 2671        request_completions: bool,
 2672        window: &mut Window,
 2673        cx: &mut Context<Self>,
 2674        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2675    ) -> R {
 2676        let old_cursor_position = self.selections.newest_anchor().head();
 2677        self.push_to_selection_history();
 2678
 2679        let (changed, result) = self.selections.change_with(cx, change);
 2680
 2681        if changed {
 2682            if let Some(autoscroll) = autoscroll {
 2683                self.request_autoscroll(autoscroll, cx);
 2684            }
 2685            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2686
 2687            if self.should_open_signature_help_automatically(
 2688                &old_cursor_position,
 2689                self.signature_help_state.backspace_pressed(),
 2690                cx,
 2691            ) {
 2692                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2693            }
 2694            self.signature_help_state.set_backspace_pressed(false);
 2695        }
 2696
 2697        result
 2698    }
 2699
 2700    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2701    where
 2702        I: IntoIterator<Item = (Range<S>, T)>,
 2703        S: ToOffset,
 2704        T: Into<Arc<str>>,
 2705    {
 2706        if self.read_only(cx) {
 2707            return;
 2708        }
 2709
 2710        self.buffer
 2711            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2712    }
 2713
 2714    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2715    where
 2716        I: IntoIterator<Item = (Range<S>, T)>,
 2717        S: ToOffset,
 2718        T: Into<Arc<str>>,
 2719    {
 2720        if self.read_only(cx) {
 2721            return;
 2722        }
 2723
 2724        self.buffer.update(cx, |buffer, cx| {
 2725            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2726        });
 2727    }
 2728
 2729    pub fn edit_with_block_indent<I, S, T>(
 2730        &mut self,
 2731        edits: I,
 2732        original_indent_columns: Vec<Option<u32>>,
 2733        cx: &mut Context<Self>,
 2734    ) where
 2735        I: IntoIterator<Item = (Range<S>, T)>,
 2736        S: ToOffset,
 2737        T: Into<Arc<str>>,
 2738    {
 2739        if self.read_only(cx) {
 2740            return;
 2741        }
 2742
 2743        self.buffer.update(cx, |buffer, cx| {
 2744            buffer.edit(
 2745                edits,
 2746                Some(AutoindentMode::Block {
 2747                    original_indent_columns,
 2748                }),
 2749                cx,
 2750            )
 2751        });
 2752    }
 2753
 2754    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2755        self.hide_context_menu(window, cx);
 2756
 2757        match phase {
 2758            SelectPhase::Begin {
 2759                position,
 2760                add,
 2761                click_count,
 2762            } => self.begin_selection(position, add, click_count, window, cx),
 2763            SelectPhase::BeginColumnar {
 2764                position,
 2765                goal_column,
 2766                reset,
 2767            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2768            SelectPhase::Extend {
 2769                position,
 2770                click_count,
 2771            } => self.extend_selection(position, click_count, window, cx),
 2772            SelectPhase::Update {
 2773                position,
 2774                goal_column,
 2775                scroll_delta,
 2776            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2777            SelectPhase::End => self.end_selection(window, cx),
 2778        }
 2779    }
 2780
 2781    fn extend_selection(
 2782        &mut self,
 2783        position: DisplayPoint,
 2784        click_count: usize,
 2785        window: &mut Window,
 2786        cx: &mut Context<Self>,
 2787    ) {
 2788        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2789        let tail = self.selections.newest::<usize>(cx).tail();
 2790        self.begin_selection(position, false, click_count, window, cx);
 2791
 2792        let position = position.to_offset(&display_map, Bias::Left);
 2793        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2794
 2795        let mut pending_selection = self
 2796            .selections
 2797            .pending_anchor()
 2798            .expect("extend_selection not called with pending selection");
 2799        if position >= tail {
 2800            pending_selection.start = tail_anchor;
 2801        } else {
 2802            pending_selection.end = tail_anchor;
 2803            pending_selection.reversed = true;
 2804        }
 2805
 2806        let mut pending_mode = self.selections.pending_mode().unwrap();
 2807        match &mut pending_mode {
 2808            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2809            _ => {}
 2810        }
 2811
 2812        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2813            s.set_pending(pending_selection, pending_mode)
 2814        });
 2815    }
 2816
 2817    fn begin_selection(
 2818        &mut self,
 2819        position: DisplayPoint,
 2820        add: bool,
 2821        click_count: usize,
 2822        window: &mut Window,
 2823        cx: &mut Context<Self>,
 2824    ) {
 2825        if !self.focus_handle.is_focused(window) {
 2826            self.last_focused_descendant = None;
 2827            window.focus(&self.focus_handle);
 2828        }
 2829
 2830        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2831        let buffer = &display_map.buffer_snapshot;
 2832        let newest_selection = self.selections.newest_anchor().clone();
 2833        let position = display_map.clip_point(position, Bias::Left);
 2834
 2835        let start;
 2836        let end;
 2837        let mode;
 2838        let mut auto_scroll;
 2839        match click_count {
 2840            1 => {
 2841                start = buffer.anchor_before(position.to_point(&display_map));
 2842                end = start;
 2843                mode = SelectMode::Character;
 2844                auto_scroll = true;
 2845            }
 2846            2 => {
 2847                let range = movement::surrounding_word(&display_map, position);
 2848                start = buffer.anchor_before(range.start.to_point(&display_map));
 2849                end = buffer.anchor_before(range.end.to_point(&display_map));
 2850                mode = SelectMode::Word(start..end);
 2851                auto_scroll = true;
 2852            }
 2853            3 => {
 2854                let position = display_map
 2855                    .clip_point(position, Bias::Left)
 2856                    .to_point(&display_map);
 2857                let line_start = display_map.prev_line_boundary(position).0;
 2858                let next_line_start = buffer.clip_point(
 2859                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2860                    Bias::Left,
 2861                );
 2862                start = buffer.anchor_before(line_start);
 2863                end = buffer.anchor_before(next_line_start);
 2864                mode = SelectMode::Line(start..end);
 2865                auto_scroll = true;
 2866            }
 2867            _ => {
 2868                start = buffer.anchor_before(0);
 2869                end = buffer.anchor_before(buffer.len());
 2870                mode = SelectMode::All;
 2871                auto_scroll = false;
 2872            }
 2873        }
 2874        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2875
 2876        let point_to_delete: Option<usize> = {
 2877            let selected_points: Vec<Selection<Point>> =
 2878                self.selections.disjoint_in_range(start..end, cx);
 2879
 2880            if !add || click_count > 1 {
 2881                None
 2882            } else if !selected_points.is_empty() {
 2883                Some(selected_points[0].id)
 2884            } else {
 2885                let clicked_point_already_selected =
 2886                    self.selections.disjoint.iter().find(|selection| {
 2887                        selection.start.to_point(buffer) == start.to_point(buffer)
 2888                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2889                    });
 2890
 2891                clicked_point_already_selected.map(|selection| selection.id)
 2892            }
 2893        };
 2894
 2895        let selections_count = self.selections.count();
 2896
 2897        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2898            if let Some(point_to_delete) = point_to_delete {
 2899                s.delete(point_to_delete);
 2900
 2901                if selections_count == 1 {
 2902                    s.set_pending_anchor_range(start..end, mode);
 2903                }
 2904            } else {
 2905                if !add {
 2906                    s.clear_disjoint();
 2907                } else if click_count > 1 {
 2908                    s.delete(newest_selection.id)
 2909                }
 2910
 2911                s.set_pending_anchor_range(start..end, mode);
 2912            }
 2913        });
 2914    }
 2915
 2916    fn begin_columnar_selection(
 2917        &mut self,
 2918        position: DisplayPoint,
 2919        goal_column: u32,
 2920        reset: bool,
 2921        window: &mut Window,
 2922        cx: &mut Context<Self>,
 2923    ) {
 2924        if !self.focus_handle.is_focused(window) {
 2925            self.last_focused_descendant = None;
 2926            window.focus(&self.focus_handle);
 2927        }
 2928
 2929        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2930
 2931        if reset {
 2932            let pointer_position = display_map
 2933                .buffer_snapshot
 2934                .anchor_before(position.to_point(&display_map));
 2935
 2936            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2937                s.clear_disjoint();
 2938                s.set_pending_anchor_range(
 2939                    pointer_position..pointer_position,
 2940                    SelectMode::Character,
 2941                );
 2942            });
 2943        }
 2944
 2945        let tail = self.selections.newest::<Point>(cx).tail();
 2946        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2947
 2948        if !reset {
 2949            self.select_columns(
 2950                tail.to_display_point(&display_map),
 2951                position,
 2952                goal_column,
 2953                &display_map,
 2954                window,
 2955                cx,
 2956            );
 2957        }
 2958    }
 2959
 2960    fn update_selection(
 2961        &mut self,
 2962        position: DisplayPoint,
 2963        goal_column: u32,
 2964        scroll_delta: gpui::Point<f32>,
 2965        window: &mut Window,
 2966        cx: &mut Context<Self>,
 2967    ) {
 2968        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2969
 2970        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2971            let tail = tail.to_display_point(&display_map);
 2972            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2973        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2974            let buffer = self.buffer.read(cx).snapshot(cx);
 2975            let head;
 2976            let tail;
 2977            let mode = self.selections.pending_mode().unwrap();
 2978            match &mode {
 2979                SelectMode::Character => {
 2980                    head = position.to_point(&display_map);
 2981                    tail = pending.tail().to_point(&buffer);
 2982                }
 2983                SelectMode::Word(original_range) => {
 2984                    let original_display_range = original_range.start.to_display_point(&display_map)
 2985                        ..original_range.end.to_display_point(&display_map);
 2986                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2987                        ..original_display_range.end.to_point(&display_map);
 2988                    if movement::is_inside_word(&display_map, position)
 2989                        || original_display_range.contains(&position)
 2990                    {
 2991                        let word_range = movement::surrounding_word(&display_map, position);
 2992                        if word_range.start < original_display_range.start {
 2993                            head = word_range.start.to_point(&display_map);
 2994                        } else {
 2995                            head = word_range.end.to_point(&display_map);
 2996                        }
 2997                    } else {
 2998                        head = position.to_point(&display_map);
 2999                    }
 3000
 3001                    if head <= original_buffer_range.start {
 3002                        tail = original_buffer_range.end;
 3003                    } else {
 3004                        tail = original_buffer_range.start;
 3005                    }
 3006                }
 3007                SelectMode::Line(original_range) => {
 3008                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 3009
 3010                    let position = display_map
 3011                        .clip_point(position, Bias::Left)
 3012                        .to_point(&display_map);
 3013                    let line_start = display_map.prev_line_boundary(position).0;
 3014                    let next_line_start = buffer.clip_point(
 3015                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 3016                        Bias::Left,
 3017                    );
 3018
 3019                    if line_start < original_range.start {
 3020                        head = line_start
 3021                    } else {
 3022                        head = next_line_start
 3023                    }
 3024
 3025                    if head <= original_range.start {
 3026                        tail = original_range.end;
 3027                    } else {
 3028                        tail = original_range.start;
 3029                    }
 3030                }
 3031                SelectMode::All => {
 3032                    return;
 3033                }
 3034            };
 3035
 3036            if head < tail {
 3037                pending.start = buffer.anchor_before(head);
 3038                pending.end = buffer.anchor_before(tail);
 3039                pending.reversed = true;
 3040            } else {
 3041                pending.start = buffer.anchor_before(tail);
 3042                pending.end = buffer.anchor_before(head);
 3043                pending.reversed = false;
 3044            }
 3045
 3046            self.change_selections(None, window, cx, |s| {
 3047                s.set_pending(pending, mode);
 3048            });
 3049        } else {
 3050            log::error!("update_selection dispatched with no pending selection");
 3051            return;
 3052        }
 3053
 3054        self.apply_scroll_delta(scroll_delta, window, cx);
 3055        cx.notify();
 3056    }
 3057
 3058    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3059        self.columnar_selection_tail.take();
 3060        if self.selections.pending_anchor().is_some() {
 3061            let selections = self.selections.all::<usize>(cx);
 3062            self.change_selections(None, window, cx, |s| {
 3063                s.select(selections);
 3064                s.clear_pending();
 3065            });
 3066        }
 3067    }
 3068
 3069    fn select_columns(
 3070        &mut self,
 3071        tail: DisplayPoint,
 3072        head: DisplayPoint,
 3073        goal_column: u32,
 3074        display_map: &DisplaySnapshot,
 3075        window: &mut Window,
 3076        cx: &mut Context<Self>,
 3077    ) {
 3078        let start_row = cmp::min(tail.row(), head.row());
 3079        let end_row = cmp::max(tail.row(), head.row());
 3080        let start_column = cmp::min(tail.column(), goal_column);
 3081        let end_column = cmp::max(tail.column(), goal_column);
 3082        let reversed = start_column < tail.column();
 3083
 3084        let selection_ranges = (start_row.0..=end_row.0)
 3085            .map(DisplayRow)
 3086            .filter_map(|row| {
 3087                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 3088                    let start = display_map
 3089                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 3090                        .to_point(display_map);
 3091                    let end = display_map
 3092                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 3093                        .to_point(display_map);
 3094                    if reversed {
 3095                        Some(end..start)
 3096                    } else {
 3097                        Some(start..end)
 3098                    }
 3099                } else {
 3100                    None
 3101                }
 3102            })
 3103            .collect::<Vec<_>>();
 3104
 3105        self.change_selections(None, window, cx, |s| {
 3106            s.select_ranges(selection_ranges);
 3107        });
 3108        cx.notify();
 3109    }
 3110
 3111    pub fn has_pending_nonempty_selection(&self) -> bool {
 3112        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3113            Some(Selection { start, end, .. }) => start != end,
 3114            None => false,
 3115        };
 3116
 3117        pending_nonempty_selection
 3118            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3119    }
 3120
 3121    pub fn has_pending_selection(&self) -> bool {
 3122        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3123    }
 3124
 3125    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3126        self.selection_mark_mode = false;
 3127
 3128        if self.clear_expanded_diff_hunks(cx) {
 3129            cx.notify();
 3130            return;
 3131        }
 3132        if self.dismiss_menus_and_popups(true, window, cx) {
 3133            return;
 3134        }
 3135
 3136        if self.mode.is_full()
 3137            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3138        {
 3139            return;
 3140        }
 3141
 3142        cx.propagate();
 3143    }
 3144
 3145    pub fn dismiss_menus_and_popups(
 3146        &mut self,
 3147        is_user_requested: bool,
 3148        window: &mut Window,
 3149        cx: &mut Context<Self>,
 3150    ) -> bool {
 3151        if self.take_rename(false, window, cx).is_some() {
 3152            return true;
 3153        }
 3154
 3155        if hide_hover(self, cx) {
 3156            return true;
 3157        }
 3158
 3159        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3160            return true;
 3161        }
 3162
 3163        if self.hide_context_menu(window, cx).is_some() {
 3164            return true;
 3165        }
 3166
 3167        if self.mouse_context_menu.take().is_some() {
 3168            return true;
 3169        }
 3170
 3171        if is_user_requested && self.discard_inline_completion(true, cx) {
 3172            return true;
 3173        }
 3174
 3175        if self.snippet_stack.pop().is_some() {
 3176            return true;
 3177        }
 3178
 3179        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3180            self.dismiss_diagnostics(cx);
 3181            return true;
 3182        }
 3183
 3184        false
 3185    }
 3186
 3187    fn linked_editing_ranges_for(
 3188        &self,
 3189        selection: Range<text::Anchor>,
 3190        cx: &App,
 3191    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3192        if self.linked_edit_ranges.is_empty() {
 3193            return None;
 3194        }
 3195        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3196            selection.end.buffer_id.and_then(|end_buffer_id| {
 3197                if selection.start.buffer_id != Some(end_buffer_id) {
 3198                    return None;
 3199                }
 3200                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3201                let snapshot = buffer.read(cx).snapshot();
 3202                self.linked_edit_ranges
 3203                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3204                    .map(|ranges| (ranges, snapshot, buffer))
 3205            })?;
 3206        use text::ToOffset as TO;
 3207        // find offset from the start of current range to current cursor position
 3208        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3209
 3210        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3211        let start_difference = start_offset - start_byte_offset;
 3212        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3213        let end_difference = end_offset - start_byte_offset;
 3214        // Current range has associated linked ranges.
 3215        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3216        for range in linked_ranges.iter() {
 3217            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3218            let end_offset = start_offset + end_difference;
 3219            let start_offset = start_offset + start_difference;
 3220            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3221                continue;
 3222            }
 3223            if self.selections.disjoint_anchor_ranges().any(|s| {
 3224                if s.start.buffer_id != selection.start.buffer_id
 3225                    || s.end.buffer_id != selection.end.buffer_id
 3226                {
 3227                    return false;
 3228                }
 3229                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3230                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3231            }) {
 3232                continue;
 3233            }
 3234            let start = buffer_snapshot.anchor_after(start_offset);
 3235            let end = buffer_snapshot.anchor_after(end_offset);
 3236            linked_edits
 3237                .entry(buffer.clone())
 3238                .or_default()
 3239                .push(start..end);
 3240        }
 3241        Some(linked_edits)
 3242    }
 3243
 3244    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3245        let text: Arc<str> = text.into();
 3246
 3247        if self.read_only(cx) {
 3248            return;
 3249        }
 3250
 3251        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3252
 3253        let selections = self.selections.all_adjusted(cx);
 3254        let mut bracket_inserted = false;
 3255        let mut edits = Vec::new();
 3256        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3257        let mut new_selections = Vec::with_capacity(selections.len());
 3258        let mut new_autoclose_regions = Vec::new();
 3259        let snapshot = self.buffer.read(cx).read(cx);
 3260        let mut clear_linked_edit_ranges = false;
 3261
 3262        for (selection, autoclose_region) in
 3263            self.selections_with_autoclose_regions(selections, &snapshot)
 3264        {
 3265            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3266                // Determine if the inserted text matches the opening or closing
 3267                // bracket of any of this language's bracket pairs.
 3268                let mut bracket_pair = None;
 3269                let mut is_bracket_pair_start = false;
 3270                let mut is_bracket_pair_end = false;
 3271                if !text.is_empty() {
 3272                    let mut bracket_pair_matching_end = None;
 3273                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3274                    //  and they are removing the character that triggered IME popup.
 3275                    for (pair, enabled) in scope.brackets() {
 3276                        if !pair.close && !pair.surround {
 3277                            continue;
 3278                        }
 3279
 3280                        if enabled && pair.start.ends_with(text.as_ref()) {
 3281                            let prefix_len = pair.start.len() - text.len();
 3282                            let preceding_text_matches_prefix = prefix_len == 0
 3283                                || (selection.start.column >= (prefix_len as u32)
 3284                                    && snapshot.contains_str_at(
 3285                                        Point::new(
 3286                                            selection.start.row,
 3287                                            selection.start.column - (prefix_len as u32),
 3288                                        ),
 3289                                        &pair.start[..prefix_len],
 3290                                    ));
 3291                            if preceding_text_matches_prefix {
 3292                                bracket_pair = Some(pair.clone());
 3293                                is_bracket_pair_start = true;
 3294                                break;
 3295                            }
 3296                        }
 3297                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3298                        {
 3299                            // take first bracket pair matching end, but don't break in case a later bracket
 3300                            // pair matches start
 3301                            bracket_pair_matching_end = Some(pair.clone());
 3302                        }
 3303                    }
 3304                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3305                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3306                        is_bracket_pair_end = true;
 3307                    }
 3308                }
 3309
 3310                if let Some(bracket_pair) = bracket_pair {
 3311                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3312                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3313                    let auto_surround =
 3314                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3315                    if selection.is_empty() {
 3316                        if is_bracket_pair_start {
 3317                            // If the inserted text is a suffix of an opening bracket and the
 3318                            // selection is preceded by the rest of the opening bracket, then
 3319                            // insert the closing bracket.
 3320                            let following_text_allows_autoclose = snapshot
 3321                                .chars_at(selection.start)
 3322                                .next()
 3323                                .map_or(true, |c| scope.should_autoclose_before(c));
 3324
 3325                            let preceding_text_allows_autoclose = selection.start.column == 0
 3326                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3327                                    true,
 3328                                    |c| {
 3329                                        bracket_pair.start != bracket_pair.end
 3330                                            || !snapshot
 3331                                                .char_classifier_at(selection.start)
 3332                                                .is_word(c)
 3333                                    },
 3334                                );
 3335
 3336                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3337                                && bracket_pair.start.len() == 1
 3338                            {
 3339                                let target = bracket_pair.start.chars().next().unwrap();
 3340                                let current_line_count = snapshot
 3341                                    .reversed_chars_at(selection.start)
 3342                                    .take_while(|&c| c != '\n')
 3343                                    .filter(|&c| c == target)
 3344                                    .count();
 3345                                current_line_count % 2 == 1
 3346                            } else {
 3347                                false
 3348                            };
 3349
 3350                            if autoclose
 3351                                && bracket_pair.close
 3352                                && following_text_allows_autoclose
 3353                                && preceding_text_allows_autoclose
 3354                                && !is_closing_quote
 3355                            {
 3356                                let anchor = snapshot.anchor_before(selection.end);
 3357                                new_selections.push((selection.map(|_| anchor), text.len()));
 3358                                new_autoclose_regions.push((
 3359                                    anchor,
 3360                                    text.len(),
 3361                                    selection.id,
 3362                                    bracket_pair.clone(),
 3363                                ));
 3364                                edits.push((
 3365                                    selection.range(),
 3366                                    format!("{}{}", text, bracket_pair.end).into(),
 3367                                ));
 3368                                bracket_inserted = true;
 3369                                continue;
 3370                            }
 3371                        }
 3372
 3373                        if let Some(region) = autoclose_region {
 3374                            // If the selection is followed by an auto-inserted closing bracket,
 3375                            // then don't insert that closing bracket again; just move the selection
 3376                            // past the closing bracket.
 3377                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3378                                && text.as_ref() == region.pair.end.as_str();
 3379                            if should_skip {
 3380                                let anchor = snapshot.anchor_after(selection.end);
 3381                                new_selections
 3382                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3383                                continue;
 3384                            }
 3385                        }
 3386
 3387                        let always_treat_brackets_as_autoclosed = snapshot
 3388                            .language_settings_at(selection.start, cx)
 3389                            .always_treat_brackets_as_autoclosed;
 3390                        if always_treat_brackets_as_autoclosed
 3391                            && is_bracket_pair_end
 3392                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3393                        {
 3394                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3395                            // and the inserted text is a closing bracket and the selection is followed
 3396                            // by the closing bracket then move the selection past the closing bracket.
 3397                            let anchor = snapshot.anchor_after(selection.end);
 3398                            new_selections.push((selection.map(|_| anchor), text.len()));
 3399                            continue;
 3400                        }
 3401                    }
 3402                    // If an opening bracket is 1 character long and is typed while
 3403                    // text is selected, then surround that text with the bracket pair.
 3404                    else if auto_surround
 3405                        && bracket_pair.surround
 3406                        && is_bracket_pair_start
 3407                        && bracket_pair.start.chars().count() == 1
 3408                    {
 3409                        edits.push((selection.start..selection.start, text.clone()));
 3410                        edits.push((
 3411                            selection.end..selection.end,
 3412                            bracket_pair.end.as_str().into(),
 3413                        ));
 3414                        bracket_inserted = true;
 3415                        new_selections.push((
 3416                            Selection {
 3417                                id: selection.id,
 3418                                start: snapshot.anchor_after(selection.start),
 3419                                end: snapshot.anchor_before(selection.end),
 3420                                reversed: selection.reversed,
 3421                                goal: selection.goal,
 3422                            },
 3423                            0,
 3424                        ));
 3425                        continue;
 3426                    }
 3427                }
 3428            }
 3429
 3430            if self.auto_replace_emoji_shortcode
 3431                && selection.is_empty()
 3432                && text.as_ref().ends_with(':')
 3433            {
 3434                if let Some(possible_emoji_short_code) =
 3435                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3436                {
 3437                    if !possible_emoji_short_code.is_empty() {
 3438                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3439                            let emoji_shortcode_start = Point::new(
 3440                                selection.start.row,
 3441                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3442                            );
 3443
 3444                            // Remove shortcode from buffer
 3445                            edits.push((
 3446                                emoji_shortcode_start..selection.start,
 3447                                "".to_string().into(),
 3448                            ));
 3449                            new_selections.push((
 3450                                Selection {
 3451                                    id: selection.id,
 3452                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3453                                    end: snapshot.anchor_before(selection.start),
 3454                                    reversed: selection.reversed,
 3455                                    goal: selection.goal,
 3456                                },
 3457                                0,
 3458                            ));
 3459
 3460                            // Insert emoji
 3461                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3462                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3463                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3464
 3465                            continue;
 3466                        }
 3467                    }
 3468                }
 3469            }
 3470
 3471            // If not handling any auto-close operation, then just replace the selected
 3472            // text with the given input and move the selection to the end of the
 3473            // newly inserted text.
 3474            let anchor = snapshot.anchor_after(selection.end);
 3475            if !self.linked_edit_ranges.is_empty() {
 3476                let start_anchor = snapshot.anchor_before(selection.start);
 3477
 3478                let is_word_char = text.chars().next().map_or(true, |char| {
 3479                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3480                    classifier.is_word(char)
 3481                });
 3482
 3483                if is_word_char {
 3484                    if let Some(ranges) = self
 3485                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3486                    {
 3487                        for (buffer, edits) in ranges {
 3488                            linked_edits
 3489                                .entry(buffer.clone())
 3490                                .or_default()
 3491                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3492                        }
 3493                    }
 3494                } else {
 3495                    clear_linked_edit_ranges = true;
 3496                }
 3497            }
 3498
 3499            new_selections.push((selection.map(|_| anchor), 0));
 3500            edits.push((selection.start..selection.end, text.clone()));
 3501        }
 3502
 3503        drop(snapshot);
 3504
 3505        self.transact(window, cx, |this, window, cx| {
 3506            if clear_linked_edit_ranges {
 3507                this.linked_edit_ranges.clear();
 3508            }
 3509            let initial_buffer_versions =
 3510                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3511
 3512            this.buffer.update(cx, |buffer, cx| {
 3513                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3514            });
 3515            for (buffer, edits) in linked_edits {
 3516                buffer.update(cx, |buffer, cx| {
 3517                    let snapshot = buffer.snapshot();
 3518                    let edits = edits
 3519                        .into_iter()
 3520                        .map(|(range, text)| {
 3521                            use text::ToPoint as TP;
 3522                            let end_point = TP::to_point(&range.end, &snapshot);
 3523                            let start_point = TP::to_point(&range.start, &snapshot);
 3524                            (start_point..end_point, text)
 3525                        })
 3526                        .sorted_by_key(|(range, _)| range.start);
 3527                    buffer.edit(edits, None, cx);
 3528                })
 3529            }
 3530            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3531            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3532            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3533            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3534                .zip(new_selection_deltas)
 3535                .map(|(selection, delta)| Selection {
 3536                    id: selection.id,
 3537                    start: selection.start + delta,
 3538                    end: selection.end + delta,
 3539                    reversed: selection.reversed,
 3540                    goal: SelectionGoal::None,
 3541                })
 3542                .collect::<Vec<_>>();
 3543
 3544            let mut i = 0;
 3545            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3546                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3547                let start = map.buffer_snapshot.anchor_before(position);
 3548                let end = map.buffer_snapshot.anchor_after(position);
 3549                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3550                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3551                        Ordering::Less => i += 1,
 3552                        Ordering::Greater => break,
 3553                        Ordering::Equal => {
 3554                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3555                                Ordering::Less => i += 1,
 3556                                Ordering::Equal => break,
 3557                                Ordering::Greater => break,
 3558                            }
 3559                        }
 3560                    }
 3561                }
 3562                this.autoclose_regions.insert(
 3563                    i,
 3564                    AutocloseRegion {
 3565                        selection_id,
 3566                        range: start..end,
 3567                        pair,
 3568                    },
 3569                );
 3570            }
 3571
 3572            let had_active_inline_completion = this.has_active_inline_completion();
 3573            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3574                s.select(new_selections)
 3575            });
 3576
 3577            if !bracket_inserted {
 3578                if let Some(on_type_format_task) =
 3579                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3580                {
 3581                    on_type_format_task.detach_and_log_err(cx);
 3582                }
 3583            }
 3584
 3585            let editor_settings = EditorSettings::get_global(cx);
 3586            if bracket_inserted
 3587                && (editor_settings.auto_signature_help
 3588                    || editor_settings.show_signature_help_after_edits)
 3589            {
 3590                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3591            }
 3592
 3593            let trigger_in_words =
 3594                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3595            if this.hard_wrap.is_some() {
 3596                let latest: Range<Point> = this.selections.newest(cx).range();
 3597                if latest.is_empty()
 3598                    && this
 3599                        .buffer()
 3600                        .read(cx)
 3601                        .snapshot(cx)
 3602                        .line_len(MultiBufferRow(latest.start.row))
 3603                        == latest.start.column
 3604                {
 3605                    this.rewrap_impl(
 3606                        RewrapOptions {
 3607                            override_language_settings: true,
 3608                            preserve_existing_whitespace: true,
 3609                        },
 3610                        cx,
 3611                    )
 3612                }
 3613            }
 3614            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3615            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3616            this.refresh_inline_completion(true, false, window, cx);
 3617            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3618        });
 3619    }
 3620
 3621    fn find_possible_emoji_shortcode_at_position(
 3622        snapshot: &MultiBufferSnapshot,
 3623        position: Point,
 3624    ) -> Option<String> {
 3625        let mut chars = Vec::new();
 3626        let mut found_colon = false;
 3627        for char in snapshot.reversed_chars_at(position).take(100) {
 3628            // Found a possible emoji shortcode in the middle of the buffer
 3629            if found_colon {
 3630                if char.is_whitespace() {
 3631                    chars.reverse();
 3632                    return Some(chars.iter().collect());
 3633                }
 3634                // If the previous character is not a whitespace, we are in the middle of a word
 3635                // and we only want to complete the shortcode if the word is made up of other emojis
 3636                let mut containing_word = String::new();
 3637                for ch in snapshot
 3638                    .reversed_chars_at(position)
 3639                    .skip(chars.len() + 1)
 3640                    .take(100)
 3641                {
 3642                    if ch.is_whitespace() {
 3643                        break;
 3644                    }
 3645                    containing_word.push(ch);
 3646                }
 3647                let containing_word = containing_word.chars().rev().collect::<String>();
 3648                if util::word_consists_of_emojis(containing_word.as_str()) {
 3649                    chars.reverse();
 3650                    return Some(chars.iter().collect());
 3651                }
 3652            }
 3653
 3654            if char.is_whitespace() || !char.is_ascii() {
 3655                return None;
 3656            }
 3657            if char == ':' {
 3658                found_colon = true;
 3659            } else {
 3660                chars.push(char);
 3661            }
 3662        }
 3663        // Found a possible emoji shortcode at the beginning of the buffer
 3664        chars.reverse();
 3665        Some(chars.iter().collect())
 3666    }
 3667
 3668    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3669        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3670        self.transact(window, cx, |this, window, cx| {
 3671            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3672                let selections = this.selections.all::<usize>(cx);
 3673                let multi_buffer = this.buffer.read(cx);
 3674                let buffer = multi_buffer.snapshot(cx);
 3675                selections
 3676                    .iter()
 3677                    .map(|selection| {
 3678                        let start_point = selection.start.to_point(&buffer);
 3679                        let mut indent =
 3680                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3681                        indent.len = cmp::min(indent.len, start_point.column);
 3682                        let start = selection.start;
 3683                        let end = selection.end;
 3684                        let selection_is_empty = start == end;
 3685                        let language_scope = buffer.language_scope_at(start);
 3686                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3687                            &language_scope
 3688                        {
 3689                            let insert_extra_newline =
 3690                                insert_extra_newline_brackets(&buffer, start..end, language)
 3691                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3692
 3693                            // Comment extension on newline is allowed only for cursor selections
 3694                            let comment_delimiter = maybe!({
 3695                                if !selection_is_empty {
 3696                                    return None;
 3697                                }
 3698
 3699                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3700                                    return None;
 3701                                }
 3702
 3703                                let delimiters = language.line_comment_prefixes();
 3704                                let max_len_of_delimiter =
 3705                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3706                                let (snapshot, range) =
 3707                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3708
 3709                                let mut index_of_first_non_whitespace = 0;
 3710                                let comment_candidate = snapshot
 3711                                    .chars_for_range(range)
 3712                                    .skip_while(|c| {
 3713                                        let should_skip = c.is_whitespace();
 3714                                        if should_skip {
 3715                                            index_of_first_non_whitespace += 1;
 3716                                        }
 3717                                        should_skip
 3718                                    })
 3719                                    .take(max_len_of_delimiter)
 3720                                    .collect::<String>();
 3721                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3722                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3723                                })?;
 3724                                let cursor_is_placed_after_comment_marker =
 3725                                    index_of_first_non_whitespace + comment_prefix.len()
 3726                                        <= start_point.column as usize;
 3727                                if cursor_is_placed_after_comment_marker {
 3728                                    Some(comment_prefix.clone())
 3729                                } else {
 3730                                    None
 3731                                }
 3732                            });
 3733                            (comment_delimiter, insert_extra_newline)
 3734                        } else {
 3735                            (None, false)
 3736                        };
 3737
 3738                        let capacity_for_delimiter = comment_delimiter
 3739                            .as_deref()
 3740                            .map(str::len)
 3741                            .unwrap_or_default();
 3742                        let mut new_text =
 3743                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3744                        new_text.push('\n');
 3745                        new_text.extend(indent.chars());
 3746                        if let Some(delimiter) = &comment_delimiter {
 3747                            new_text.push_str(delimiter);
 3748                        }
 3749                        if insert_extra_newline {
 3750                            new_text = new_text.repeat(2);
 3751                        }
 3752
 3753                        let anchor = buffer.anchor_after(end);
 3754                        let new_selection = selection.map(|_| anchor);
 3755                        (
 3756                            (start..end, new_text),
 3757                            (insert_extra_newline, new_selection),
 3758                        )
 3759                    })
 3760                    .unzip()
 3761            };
 3762
 3763            this.edit_with_autoindent(edits, cx);
 3764            let buffer = this.buffer.read(cx).snapshot(cx);
 3765            let new_selections = selection_fixup_info
 3766                .into_iter()
 3767                .map(|(extra_newline_inserted, new_selection)| {
 3768                    let mut cursor = new_selection.end.to_point(&buffer);
 3769                    if extra_newline_inserted {
 3770                        cursor.row -= 1;
 3771                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3772                    }
 3773                    new_selection.map(|_| cursor)
 3774                })
 3775                .collect();
 3776
 3777            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3778                s.select(new_selections)
 3779            });
 3780            this.refresh_inline_completion(true, false, window, cx);
 3781        });
 3782    }
 3783
 3784    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3785        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3786
 3787        let buffer = self.buffer.read(cx);
 3788        let snapshot = buffer.snapshot(cx);
 3789
 3790        let mut edits = Vec::new();
 3791        let mut rows = Vec::new();
 3792
 3793        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3794            let cursor = selection.head();
 3795            let row = cursor.row;
 3796
 3797            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3798
 3799            let newline = "\n".to_string();
 3800            edits.push((start_of_line..start_of_line, newline));
 3801
 3802            rows.push(row + rows_inserted as u32);
 3803        }
 3804
 3805        self.transact(window, cx, |editor, window, cx| {
 3806            editor.edit(edits, cx);
 3807
 3808            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3809                let mut index = 0;
 3810                s.move_cursors_with(|map, _, _| {
 3811                    let row = rows[index];
 3812                    index += 1;
 3813
 3814                    let point = Point::new(row, 0);
 3815                    let boundary = map.next_line_boundary(point).1;
 3816                    let clipped = map.clip_point(boundary, Bias::Left);
 3817
 3818                    (clipped, SelectionGoal::None)
 3819                });
 3820            });
 3821
 3822            let mut indent_edits = Vec::new();
 3823            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3824            for row in rows {
 3825                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3826                for (row, indent) in indents {
 3827                    if indent.len == 0 {
 3828                        continue;
 3829                    }
 3830
 3831                    let text = match indent.kind {
 3832                        IndentKind::Space => " ".repeat(indent.len as usize),
 3833                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3834                    };
 3835                    let point = Point::new(row.0, 0);
 3836                    indent_edits.push((point..point, text));
 3837                }
 3838            }
 3839            editor.edit(indent_edits, cx);
 3840        });
 3841    }
 3842
 3843    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3844        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3845
 3846        let buffer = self.buffer.read(cx);
 3847        let snapshot = buffer.snapshot(cx);
 3848
 3849        let mut edits = Vec::new();
 3850        let mut rows = Vec::new();
 3851        let mut rows_inserted = 0;
 3852
 3853        for selection in self.selections.all_adjusted(cx) {
 3854            let cursor = selection.head();
 3855            let row = cursor.row;
 3856
 3857            let point = Point::new(row + 1, 0);
 3858            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3859
 3860            let newline = "\n".to_string();
 3861            edits.push((start_of_line..start_of_line, newline));
 3862
 3863            rows_inserted += 1;
 3864            rows.push(row + rows_inserted);
 3865        }
 3866
 3867        self.transact(window, cx, |editor, window, cx| {
 3868            editor.edit(edits, cx);
 3869
 3870            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3871                let mut index = 0;
 3872                s.move_cursors_with(|map, _, _| {
 3873                    let row = rows[index];
 3874                    index += 1;
 3875
 3876                    let point = Point::new(row, 0);
 3877                    let boundary = map.next_line_boundary(point).1;
 3878                    let clipped = map.clip_point(boundary, Bias::Left);
 3879
 3880                    (clipped, SelectionGoal::None)
 3881                });
 3882            });
 3883
 3884            let mut indent_edits = Vec::new();
 3885            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3886            for row in rows {
 3887                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3888                for (row, indent) in indents {
 3889                    if indent.len == 0 {
 3890                        continue;
 3891                    }
 3892
 3893                    let text = match indent.kind {
 3894                        IndentKind::Space => " ".repeat(indent.len as usize),
 3895                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3896                    };
 3897                    let point = Point::new(row.0, 0);
 3898                    indent_edits.push((point..point, text));
 3899                }
 3900            }
 3901            editor.edit(indent_edits, cx);
 3902        });
 3903    }
 3904
 3905    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3906        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3907            original_indent_columns: Vec::new(),
 3908        });
 3909        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3910    }
 3911
 3912    fn insert_with_autoindent_mode(
 3913        &mut self,
 3914        text: &str,
 3915        autoindent_mode: Option<AutoindentMode>,
 3916        window: &mut Window,
 3917        cx: &mut Context<Self>,
 3918    ) {
 3919        if self.read_only(cx) {
 3920            return;
 3921        }
 3922
 3923        let text: Arc<str> = text.into();
 3924        self.transact(window, cx, |this, window, cx| {
 3925            let old_selections = this.selections.all_adjusted(cx);
 3926            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3927                let anchors = {
 3928                    let snapshot = buffer.read(cx);
 3929                    old_selections
 3930                        .iter()
 3931                        .map(|s| {
 3932                            let anchor = snapshot.anchor_after(s.head());
 3933                            s.map(|_| anchor)
 3934                        })
 3935                        .collect::<Vec<_>>()
 3936                };
 3937                buffer.edit(
 3938                    old_selections
 3939                        .iter()
 3940                        .map(|s| (s.start..s.end, text.clone())),
 3941                    autoindent_mode,
 3942                    cx,
 3943                );
 3944                anchors
 3945            });
 3946
 3947            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3948                s.select_anchors(selection_anchors);
 3949            });
 3950
 3951            cx.notify();
 3952        });
 3953    }
 3954
 3955    fn trigger_completion_on_input(
 3956        &mut self,
 3957        text: &str,
 3958        trigger_in_words: bool,
 3959        window: &mut Window,
 3960        cx: &mut Context<Self>,
 3961    ) {
 3962        let ignore_completion_provider = self
 3963            .context_menu
 3964            .borrow()
 3965            .as_ref()
 3966            .map(|menu| match menu {
 3967                CodeContextMenu::Completions(completions_menu) => {
 3968                    completions_menu.ignore_completion_provider
 3969                }
 3970                CodeContextMenu::CodeActions(_) => false,
 3971            })
 3972            .unwrap_or(false);
 3973
 3974        if ignore_completion_provider {
 3975            self.show_word_completions(&ShowWordCompletions, window, cx);
 3976        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3977            self.show_completions(
 3978                &ShowCompletions {
 3979                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3980                },
 3981                window,
 3982                cx,
 3983            );
 3984        } else {
 3985            self.hide_context_menu(window, cx);
 3986        }
 3987    }
 3988
 3989    fn is_completion_trigger(
 3990        &self,
 3991        text: &str,
 3992        trigger_in_words: bool,
 3993        cx: &mut Context<Self>,
 3994    ) -> bool {
 3995        let position = self.selections.newest_anchor().head();
 3996        let multibuffer = self.buffer.read(cx);
 3997        let Some(buffer) = position
 3998            .buffer_id
 3999            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4000        else {
 4001            return false;
 4002        };
 4003
 4004        if let Some(completion_provider) = &self.completion_provider {
 4005            completion_provider.is_completion_trigger(
 4006                &buffer,
 4007                position.text_anchor,
 4008                text,
 4009                trigger_in_words,
 4010                cx,
 4011            )
 4012        } else {
 4013            false
 4014        }
 4015    }
 4016
 4017    /// If any empty selections is touching the start of its innermost containing autoclose
 4018    /// region, expand it to select the brackets.
 4019    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4020        let selections = self.selections.all::<usize>(cx);
 4021        let buffer = self.buffer.read(cx).read(cx);
 4022        let new_selections = self
 4023            .selections_with_autoclose_regions(selections, &buffer)
 4024            .map(|(mut selection, region)| {
 4025                if !selection.is_empty() {
 4026                    return selection;
 4027                }
 4028
 4029                if let Some(region) = region {
 4030                    let mut range = region.range.to_offset(&buffer);
 4031                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4032                        range.start -= region.pair.start.len();
 4033                        if buffer.contains_str_at(range.start, &region.pair.start)
 4034                            && buffer.contains_str_at(range.end, &region.pair.end)
 4035                        {
 4036                            range.end += region.pair.end.len();
 4037                            selection.start = range.start;
 4038                            selection.end = range.end;
 4039
 4040                            return selection;
 4041                        }
 4042                    }
 4043                }
 4044
 4045                let always_treat_brackets_as_autoclosed = buffer
 4046                    .language_settings_at(selection.start, cx)
 4047                    .always_treat_brackets_as_autoclosed;
 4048
 4049                if !always_treat_brackets_as_autoclosed {
 4050                    return selection;
 4051                }
 4052
 4053                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4054                    for (pair, enabled) in scope.brackets() {
 4055                        if !enabled || !pair.close {
 4056                            continue;
 4057                        }
 4058
 4059                        if buffer.contains_str_at(selection.start, &pair.end) {
 4060                            let pair_start_len = pair.start.len();
 4061                            if buffer.contains_str_at(
 4062                                selection.start.saturating_sub(pair_start_len),
 4063                                &pair.start,
 4064                            ) {
 4065                                selection.start -= pair_start_len;
 4066                                selection.end += pair.end.len();
 4067
 4068                                return selection;
 4069                            }
 4070                        }
 4071                    }
 4072                }
 4073
 4074                selection
 4075            })
 4076            .collect();
 4077
 4078        drop(buffer);
 4079        self.change_selections(None, window, cx, |selections| {
 4080            selections.select(new_selections)
 4081        });
 4082    }
 4083
 4084    /// Iterate the given selections, and for each one, find the smallest surrounding
 4085    /// autoclose region. This uses the ordering of the selections and the autoclose
 4086    /// regions to avoid repeated comparisons.
 4087    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4088        &'a self,
 4089        selections: impl IntoIterator<Item = Selection<D>>,
 4090        buffer: &'a MultiBufferSnapshot,
 4091    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4092        let mut i = 0;
 4093        let mut regions = self.autoclose_regions.as_slice();
 4094        selections.into_iter().map(move |selection| {
 4095            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4096
 4097            let mut enclosing = None;
 4098            while let Some(pair_state) = regions.get(i) {
 4099                if pair_state.range.end.to_offset(buffer) < range.start {
 4100                    regions = &regions[i + 1..];
 4101                    i = 0;
 4102                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4103                    break;
 4104                } else {
 4105                    if pair_state.selection_id == selection.id {
 4106                        enclosing = Some(pair_state);
 4107                    }
 4108                    i += 1;
 4109                }
 4110            }
 4111
 4112            (selection, enclosing)
 4113        })
 4114    }
 4115
 4116    /// Remove any autoclose regions that no longer contain their selection.
 4117    fn invalidate_autoclose_regions(
 4118        &mut self,
 4119        mut selections: &[Selection<Anchor>],
 4120        buffer: &MultiBufferSnapshot,
 4121    ) {
 4122        self.autoclose_regions.retain(|state| {
 4123            let mut i = 0;
 4124            while let Some(selection) = selections.get(i) {
 4125                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4126                    selections = &selections[1..];
 4127                    continue;
 4128                }
 4129                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4130                    break;
 4131                }
 4132                if selection.id == state.selection_id {
 4133                    return true;
 4134                } else {
 4135                    i += 1;
 4136                }
 4137            }
 4138            false
 4139        });
 4140    }
 4141
 4142    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4143        let offset = position.to_offset(buffer);
 4144        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4145        if offset > word_range.start && kind == Some(CharKind::Word) {
 4146            Some(
 4147                buffer
 4148                    .text_for_range(word_range.start..offset)
 4149                    .collect::<String>(),
 4150            )
 4151        } else {
 4152            None
 4153        }
 4154    }
 4155
 4156    pub fn toggle_inlay_hints(
 4157        &mut self,
 4158        _: &ToggleInlayHints,
 4159        _: &mut Window,
 4160        cx: &mut Context<Self>,
 4161    ) {
 4162        self.refresh_inlay_hints(
 4163            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4164            cx,
 4165        );
 4166    }
 4167
 4168    pub fn inlay_hints_enabled(&self) -> bool {
 4169        self.inlay_hint_cache.enabled
 4170    }
 4171
 4172    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4173        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4174            return;
 4175        }
 4176
 4177        let reason_description = reason.description();
 4178        let ignore_debounce = matches!(
 4179            reason,
 4180            InlayHintRefreshReason::SettingsChange(_)
 4181                | InlayHintRefreshReason::Toggle(_)
 4182                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4183                | InlayHintRefreshReason::ModifiersChanged(_)
 4184        );
 4185        let (invalidate_cache, required_languages) = match reason {
 4186            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4187                match self.inlay_hint_cache.modifiers_override(enabled) {
 4188                    Some(enabled) => {
 4189                        if enabled {
 4190                            (InvalidationStrategy::RefreshRequested, None)
 4191                        } else {
 4192                            self.splice_inlays(
 4193                                &self
 4194                                    .visible_inlay_hints(cx)
 4195                                    .iter()
 4196                                    .map(|inlay| inlay.id)
 4197                                    .collect::<Vec<InlayId>>(),
 4198                                Vec::new(),
 4199                                cx,
 4200                            );
 4201                            return;
 4202                        }
 4203                    }
 4204                    None => return,
 4205                }
 4206            }
 4207            InlayHintRefreshReason::Toggle(enabled) => {
 4208                if self.inlay_hint_cache.toggle(enabled) {
 4209                    if enabled {
 4210                        (InvalidationStrategy::RefreshRequested, None)
 4211                    } else {
 4212                        self.splice_inlays(
 4213                            &self
 4214                                .visible_inlay_hints(cx)
 4215                                .iter()
 4216                                .map(|inlay| inlay.id)
 4217                                .collect::<Vec<InlayId>>(),
 4218                            Vec::new(),
 4219                            cx,
 4220                        );
 4221                        return;
 4222                    }
 4223                } else {
 4224                    return;
 4225                }
 4226            }
 4227            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4228                match self.inlay_hint_cache.update_settings(
 4229                    &self.buffer,
 4230                    new_settings,
 4231                    self.visible_inlay_hints(cx),
 4232                    cx,
 4233                ) {
 4234                    ControlFlow::Break(Some(InlaySplice {
 4235                        to_remove,
 4236                        to_insert,
 4237                    })) => {
 4238                        self.splice_inlays(&to_remove, to_insert, cx);
 4239                        return;
 4240                    }
 4241                    ControlFlow::Break(None) => return,
 4242                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4243                }
 4244            }
 4245            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4246                if let Some(InlaySplice {
 4247                    to_remove,
 4248                    to_insert,
 4249                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4250                {
 4251                    self.splice_inlays(&to_remove, to_insert, cx);
 4252                }
 4253                self.display_map.update(cx, |display_map, _| {
 4254                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4255                });
 4256                return;
 4257            }
 4258            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4259            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4260                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4261            }
 4262            InlayHintRefreshReason::RefreshRequested => {
 4263                (InvalidationStrategy::RefreshRequested, None)
 4264            }
 4265        };
 4266
 4267        if let Some(InlaySplice {
 4268            to_remove,
 4269            to_insert,
 4270        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4271            reason_description,
 4272            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4273            invalidate_cache,
 4274            ignore_debounce,
 4275            cx,
 4276        ) {
 4277            self.splice_inlays(&to_remove, to_insert, cx);
 4278        }
 4279    }
 4280
 4281    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4282        self.display_map
 4283            .read(cx)
 4284            .current_inlays()
 4285            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4286            .cloned()
 4287            .collect()
 4288    }
 4289
 4290    pub fn excerpts_for_inlay_hints_query(
 4291        &self,
 4292        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4293        cx: &mut Context<Editor>,
 4294    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4295        let Some(project) = self.project.as_ref() else {
 4296            return HashMap::default();
 4297        };
 4298        let project = project.read(cx);
 4299        let multi_buffer = self.buffer().read(cx);
 4300        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4301        let multi_buffer_visible_start = self
 4302            .scroll_manager
 4303            .anchor()
 4304            .anchor
 4305            .to_point(&multi_buffer_snapshot);
 4306        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4307            multi_buffer_visible_start
 4308                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4309            Bias::Left,
 4310        );
 4311        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4312        multi_buffer_snapshot
 4313            .range_to_buffer_ranges(multi_buffer_visible_range)
 4314            .into_iter()
 4315            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4316            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4317                let buffer_file = project::File::from_dyn(buffer.file())?;
 4318                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4319                let worktree_entry = buffer_worktree
 4320                    .read(cx)
 4321                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4322                if worktree_entry.is_ignored {
 4323                    return None;
 4324                }
 4325
 4326                let language = buffer.language()?;
 4327                if let Some(restrict_to_languages) = restrict_to_languages {
 4328                    if !restrict_to_languages.contains(language) {
 4329                        return None;
 4330                    }
 4331                }
 4332                Some((
 4333                    excerpt_id,
 4334                    (
 4335                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4336                        buffer.version().clone(),
 4337                        excerpt_visible_range,
 4338                    ),
 4339                ))
 4340            })
 4341            .collect()
 4342    }
 4343
 4344    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4345        TextLayoutDetails {
 4346            text_system: window.text_system().clone(),
 4347            editor_style: self.style.clone().unwrap(),
 4348            rem_size: window.rem_size(),
 4349            scroll_anchor: self.scroll_manager.anchor(),
 4350            visible_rows: self.visible_line_count(),
 4351            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4352        }
 4353    }
 4354
 4355    pub fn splice_inlays(
 4356        &self,
 4357        to_remove: &[InlayId],
 4358        to_insert: Vec<Inlay>,
 4359        cx: &mut Context<Self>,
 4360    ) {
 4361        self.display_map.update(cx, |display_map, cx| {
 4362            display_map.splice_inlays(to_remove, to_insert, cx)
 4363        });
 4364        cx.notify();
 4365    }
 4366
 4367    fn trigger_on_type_formatting(
 4368        &self,
 4369        input: String,
 4370        window: &mut Window,
 4371        cx: &mut Context<Self>,
 4372    ) -> Option<Task<Result<()>>> {
 4373        if input.len() != 1 {
 4374            return None;
 4375        }
 4376
 4377        let project = self.project.as_ref()?;
 4378        let position = self.selections.newest_anchor().head();
 4379        let (buffer, buffer_position) = self
 4380            .buffer
 4381            .read(cx)
 4382            .text_anchor_for_position(position, cx)?;
 4383
 4384        let settings = language_settings::language_settings(
 4385            buffer
 4386                .read(cx)
 4387                .language_at(buffer_position)
 4388                .map(|l| l.name()),
 4389            buffer.read(cx).file(),
 4390            cx,
 4391        );
 4392        if !settings.use_on_type_format {
 4393            return None;
 4394        }
 4395
 4396        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4397        // hence we do LSP request & edit on host side only — add formats to host's history.
 4398        let push_to_lsp_host_history = true;
 4399        // If this is not the host, append its history with new edits.
 4400        let push_to_client_history = project.read(cx).is_via_collab();
 4401
 4402        let on_type_formatting = project.update(cx, |project, cx| {
 4403            project.on_type_format(
 4404                buffer.clone(),
 4405                buffer_position,
 4406                input,
 4407                push_to_lsp_host_history,
 4408                cx,
 4409            )
 4410        });
 4411        Some(cx.spawn_in(window, async move |editor, cx| {
 4412            if let Some(transaction) = on_type_formatting.await? {
 4413                if push_to_client_history {
 4414                    buffer
 4415                        .update(cx, |buffer, _| {
 4416                            buffer.push_transaction(transaction, Instant::now());
 4417                            buffer.finalize_last_transaction();
 4418                        })
 4419                        .ok();
 4420                }
 4421                editor.update(cx, |editor, cx| {
 4422                    editor.refresh_document_highlights(cx);
 4423                })?;
 4424            }
 4425            Ok(())
 4426        }))
 4427    }
 4428
 4429    pub fn show_word_completions(
 4430        &mut self,
 4431        _: &ShowWordCompletions,
 4432        window: &mut Window,
 4433        cx: &mut Context<Self>,
 4434    ) {
 4435        self.open_completions_menu(true, None, window, cx);
 4436    }
 4437
 4438    pub fn show_completions(
 4439        &mut self,
 4440        options: &ShowCompletions,
 4441        window: &mut Window,
 4442        cx: &mut Context<Self>,
 4443    ) {
 4444        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4445    }
 4446
 4447    fn open_completions_menu(
 4448        &mut self,
 4449        ignore_completion_provider: bool,
 4450        trigger: Option<&str>,
 4451        window: &mut Window,
 4452        cx: &mut Context<Self>,
 4453    ) {
 4454        if self.pending_rename.is_some() {
 4455            return;
 4456        }
 4457        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4458            return;
 4459        }
 4460
 4461        let position = self.selections.newest_anchor().head();
 4462        if position.diff_base_anchor.is_some() {
 4463            return;
 4464        }
 4465        let (buffer, buffer_position) =
 4466            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4467                output
 4468            } else {
 4469                return;
 4470            };
 4471        let buffer_snapshot = buffer.read(cx).snapshot();
 4472        let show_completion_documentation = buffer_snapshot
 4473            .settings_at(buffer_position, cx)
 4474            .show_completion_documentation;
 4475
 4476        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4477
 4478        let trigger_kind = match trigger {
 4479            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4480                CompletionTriggerKind::TRIGGER_CHARACTER
 4481            }
 4482            _ => CompletionTriggerKind::INVOKED,
 4483        };
 4484        let completion_context = CompletionContext {
 4485            trigger_character: trigger.and_then(|trigger| {
 4486                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4487                    Some(String::from(trigger))
 4488                } else {
 4489                    None
 4490                }
 4491            }),
 4492            trigger_kind,
 4493        };
 4494
 4495        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4496        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4497            let word_to_exclude = buffer_snapshot
 4498                .text_for_range(old_range.clone())
 4499                .collect::<String>();
 4500            (
 4501                buffer_snapshot.anchor_before(old_range.start)
 4502                    ..buffer_snapshot.anchor_after(old_range.end),
 4503                Some(word_to_exclude),
 4504            )
 4505        } else {
 4506            (buffer_position..buffer_position, None)
 4507        };
 4508
 4509        let completion_settings = language_settings(
 4510            buffer_snapshot
 4511                .language_at(buffer_position)
 4512                .map(|language| language.name()),
 4513            buffer_snapshot.file(),
 4514            cx,
 4515        )
 4516        .completions;
 4517
 4518        // The document can be large, so stay in reasonable bounds when searching for words,
 4519        // otherwise completion pop-up might be slow to appear.
 4520        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4521        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4522        let min_word_search = buffer_snapshot.clip_point(
 4523            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4524            Bias::Left,
 4525        );
 4526        let max_word_search = buffer_snapshot.clip_point(
 4527            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4528            Bias::Right,
 4529        );
 4530        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4531            ..buffer_snapshot.point_to_offset(max_word_search);
 4532
 4533        let provider = self
 4534            .completion_provider
 4535            .as_ref()
 4536            .filter(|_| !ignore_completion_provider);
 4537        let skip_digits = query
 4538            .as_ref()
 4539            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4540
 4541        let (mut words, provided_completions) = match provider {
 4542            Some(provider) => {
 4543                let completions = provider.completions(
 4544                    position.excerpt_id,
 4545                    &buffer,
 4546                    buffer_position,
 4547                    completion_context,
 4548                    window,
 4549                    cx,
 4550                );
 4551
 4552                let words = match completion_settings.words {
 4553                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4554                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4555                        .background_spawn(async move {
 4556                            buffer_snapshot.words_in_range(WordsQuery {
 4557                                fuzzy_contents: None,
 4558                                range: word_search_range,
 4559                                skip_digits,
 4560                            })
 4561                        }),
 4562                };
 4563
 4564                (words, completions)
 4565            }
 4566            None => (
 4567                cx.background_spawn(async move {
 4568                    buffer_snapshot.words_in_range(WordsQuery {
 4569                        fuzzy_contents: None,
 4570                        range: word_search_range,
 4571                        skip_digits,
 4572                    })
 4573                }),
 4574                Task::ready(Ok(None)),
 4575            ),
 4576        };
 4577
 4578        let sort_completions = provider
 4579            .as_ref()
 4580            .map_or(false, |provider| provider.sort_completions());
 4581
 4582        let filter_completions = provider
 4583            .as_ref()
 4584            .map_or(true, |provider| provider.filter_completions());
 4585
 4586        let id = post_inc(&mut self.next_completion_id);
 4587        let task = cx.spawn_in(window, async move |editor, cx| {
 4588            async move {
 4589                editor.update(cx, |this, _| {
 4590                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4591                })?;
 4592
 4593                let mut completions = Vec::new();
 4594                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4595                    completions.extend(provided_completions);
 4596                    if completion_settings.words == WordsCompletionMode::Fallback {
 4597                        words = Task::ready(BTreeMap::default());
 4598                    }
 4599                }
 4600
 4601                let mut words = words.await;
 4602                if let Some(word_to_exclude) = &word_to_exclude {
 4603                    words.remove(word_to_exclude);
 4604                }
 4605                for lsp_completion in &completions {
 4606                    words.remove(&lsp_completion.new_text);
 4607                }
 4608                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4609                    replace_range: old_range.clone(),
 4610                    new_text: word.clone(),
 4611                    label: CodeLabel::plain(word, None),
 4612                    icon_path: None,
 4613                    documentation: None,
 4614                    source: CompletionSource::BufferWord {
 4615                        word_range,
 4616                        resolved: false,
 4617                    },
 4618                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4619                    confirm: None,
 4620                }));
 4621
 4622                let menu = if completions.is_empty() {
 4623                    None
 4624                } else {
 4625                    let mut menu = CompletionsMenu::new(
 4626                        id,
 4627                        sort_completions,
 4628                        show_completion_documentation,
 4629                        ignore_completion_provider,
 4630                        position,
 4631                        buffer.clone(),
 4632                        completions.into(),
 4633                    );
 4634
 4635                    menu.filter(
 4636                        if filter_completions {
 4637                            query.as_deref()
 4638                        } else {
 4639                            None
 4640                        },
 4641                        cx.background_executor().clone(),
 4642                    )
 4643                    .await;
 4644
 4645                    menu.visible().then_some(menu)
 4646                };
 4647
 4648                editor.update_in(cx, |editor, window, cx| {
 4649                    match editor.context_menu.borrow().as_ref() {
 4650                        None => {}
 4651                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4652                            if prev_menu.id > id {
 4653                                return;
 4654                            }
 4655                        }
 4656                        _ => return,
 4657                    }
 4658
 4659                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4660                        let mut menu = menu.unwrap();
 4661                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4662
 4663                        *editor.context_menu.borrow_mut() =
 4664                            Some(CodeContextMenu::Completions(menu));
 4665
 4666                        if editor.show_edit_predictions_in_menu() {
 4667                            editor.update_visible_inline_completion(window, cx);
 4668                        } else {
 4669                            editor.discard_inline_completion(false, cx);
 4670                        }
 4671
 4672                        cx.notify();
 4673                    } else if editor.completion_tasks.len() <= 1 {
 4674                        // If there are no more completion tasks and the last menu was
 4675                        // empty, we should hide it.
 4676                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4677                        // If it was already hidden and we don't show inline
 4678                        // completions in the menu, we should also show the
 4679                        // inline-completion when available.
 4680                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4681                            editor.update_visible_inline_completion(window, cx);
 4682                        }
 4683                    }
 4684                })?;
 4685
 4686                anyhow::Ok(())
 4687            }
 4688            .log_err()
 4689            .await
 4690        });
 4691
 4692        self.completion_tasks.push((id, task));
 4693    }
 4694
 4695    #[cfg(feature = "test-support")]
 4696    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4697        let menu = self.context_menu.borrow();
 4698        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4699            let completions = menu.completions.borrow();
 4700            Some(completions.to_vec())
 4701        } else {
 4702            None
 4703        }
 4704    }
 4705
 4706    pub fn confirm_completion(
 4707        &mut self,
 4708        action: &ConfirmCompletion,
 4709        window: &mut Window,
 4710        cx: &mut Context<Self>,
 4711    ) -> Option<Task<Result<()>>> {
 4712        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4713        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4714    }
 4715
 4716    pub fn confirm_completion_insert(
 4717        &mut self,
 4718        _: &ConfirmCompletionInsert,
 4719        window: &mut Window,
 4720        cx: &mut Context<Self>,
 4721    ) -> Option<Task<Result<()>>> {
 4722        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4723        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4724    }
 4725
 4726    pub fn confirm_completion_replace(
 4727        &mut self,
 4728        _: &ConfirmCompletionReplace,
 4729        window: &mut Window,
 4730        cx: &mut Context<Self>,
 4731    ) -> Option<Task<Result<()>>> {
 4732        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4733        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4734    }
 4735
 4736    pub fn compose_completion(
 4737        &mut self,
 4738        action: &ComposeCompletion,
 4739        window: &mut Window,
 4740        cx: &mut Context<Self>,
 4741    ) -> Option<Task<Result<()>>> {
 4742        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4743        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4744    }
 4745
 4746    fn do_completion(
 4747        &mut self,
 4748        item_ix: Option<usize>,
 4749        intent: CompletionIntent,
 4750        window: &mut Window,
 4751        cx: &mut Context<Editor>,
 4752    ) -> Option<Task<Result<()>>> {
 4753        use language::ToOffset as _;
 4754
 4755        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4756        else {
 4757            return None;
 4758        };
 4759
 4760        let candidate_id = {
 4761            let entries = completions_menu.entries.borrow();
 4762            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4763            if self.show_edit_predictions_in_menu() {
 4764                self.discard_inline_completion(true, cx);
 4765            }
 4766            mat.candidate_id
 4767        };
 4768
 4769        let buffer_handle = completions_menu.buffer;
 4770        let completion = completions_menu
 4771            .completions
 4772            .borrow()
 4773            .get(candidate_id)?
 4774            .clone();
 4775        cx.stop_propagation();
 4776
 4777        let snippet;
 4778        let new_text;
 4779        if completion.is_snippet() {
 4780            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4781            new_text = snippet.as_ref().unwrap().text.clone();
 4782        } else {
 4783            snippet = None;
 4784            new_text = completion.new_text.clone();
 4785        };
 4786
 4787        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4788        let buffer = buffer_handle.read(cx);
 4789        let snapshot = self.buffer.read(cx).snapshot(cx);
 4790        let replace_range_multibuffer = {
 4791            let excerpt = snapshot
 4792                .excerpt_containing(self.selections.newest_anchor().range())
 4793                .unwrap();
 4794            let multibuffer_anchor = snapshot
 4795                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4796                .unwrap()
 4797                ..snapshot
 4798                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4799                    .unwrap();
 4800            multibuffer_anchor.start.to_offset(&snapshot)
 4801                ..multibuffer_anchor.end.to_offset(&snapshot)
 4802        };
 4803        let newest_anchor = self.selections.newest_anchor();
 4804        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4805            return None;
 4806        }
 4807
 4808        let old_text = buffer
 4809            .text_for_range(replace_range.clone())
 4810            .collect::<String>();
 4811        let lookbehind = newest_anchor
 4812            .start
 4813            .text_anchor
 4814            .to_offset(buffer)
 4815            .saturating_sub(replace_range.start);
 4816        let lookahead = replace_range
 4817            .end
 4818            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4819        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4820        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4821
 4822        let selections = self.selections.all::<usize>(cx);
 4823        let mut ranges = Vec::new();
 4824        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4825
 4826        for selection in &selections {
 4827            let range = if selection.id == newest_anchor.id {
 4828                replace_range_multibuffer.clone()
 4829            } else {
 4830                let mut range = selection.range();
 4831
 4832                // if prefix is present, don't duplicate it
 4833                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 4834                    range.start = range.start.saturating_sub(lookbehind);
 4835
 4836                    // if suffix is also present, mimic the newest cursor and replace it
 4837                    if selection.id != newest_anchor.id
 4838                        && snapshot.contains_str_at(range.end, suffix)
 4839                    {
 4840                        range.end += lookahead;
 4841                    }
 4842                }
 4843                range
 4844            };
 4845
 4846            ranges.push(range);
 4847
 4848            if !self.linked_edit_ranges.is_empty() {
 4849                let start_anchor = snapshot.anchor_before(selection.head());
 4850                let end_anchor = snapshot.anchor_after(selection.tail());
 4851                if let Some(ranges) = self
 4852                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4853                {
 4854                    for (buffer, edits) in ranges {
 4855                        linked_edits
 4856                            .entry(buffer.clone())
 4857                            .or_default()
 4858                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 4859                    }
 4860                }
 4861            }
 4862        }
 4863
 4864        cx.emit(EditorEvent::InputHandled {
 4865            utf16_range_to_replace: None,
 4866            text: new_text.clone().into(),
 4867        });
 4868
 4869        self.transact(window, cx, |this, window, cx| {
 4870            if let Some(mut snippet) = snippet {
 4871                snippet.text = new_text.to_string();
 4872                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4873            } else {
 4874                this.buffer.update(cx, |buffer, cx| {
 4875                    let auto_indent = match completion.insert_text_mode {
 4876                        Some(InsertTextMode::AS_IS) => None,
 4877                        _ => this.autoindent_mode.clone(),
 4878                    };
 4879                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 4880                    buffer.edit(edits, auto_indent, cx);
 4881                });
 4882            }
 4883            for (buffer, edits) in linked_edits {
 4884                buffer.update(cx, |buffer, cx| {
 4885                    let snapshot = buffer.snapshot();
 4886                    let edits = edits
 4887                        .into_iter()
 4888                        .map(|(range, text)| {
 4889                            use text::ToPoint as TP;
 4890                            let end_point = TP::to_point(&range.end, &snapshot);
 4891                            let start_point = TP::to_point(&range.start, &snapshot);
 4892                            (start_point..end_point, text)
 4893                        })
 4894                        .sorted_by_key(|(range, _)| range.start);
 4895                    buffer.edit(edits, None, cx);
 4896                })
 4897            }
 4898
 4899            this.refresh_inline_completion(true, false, window, cx);
 4900        });
 4901
 4902        let show_new_completions_on_confirm = completion
 4903            .confirm
 4904            .as_ref()
 4905            .map_or(false, |confirm| confirm(intent, window, cx));
 4906        if show_new_completions_on_confirm {
 4907            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4908        }
 4909
 4910        let provider = self.completion_provider.as_ref()?;
 4911        drop(completion);
 4912        let apply_edits = provider.apply_additional_edits_for_completion(
 4913            buffer_handle,
 4914            completions_menu.completions.clone(),
 4915            candidate_id,
 4916            true,
 4917            cx,
 4918        );
 4919
 4920        let editor_settings = EditorSettings::get_global(cx);
 4921        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4922            // After the code completion is finished, users often want to know what signatures are needed.
 4923            // so we should automatically call signature_help
 4924            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4925        }
 4926
 4927        Some(cx.foreground_executor().spawn(async move {
 4928            apply_edits.await?;
 4929            Ok(())
 4930        }))
 4931    }
 4932
 4933    pub fn toggle_code_actions(
 4934        &mut self,
 4935        action: &ToggleCodeActions,
 4936        window: &mut Window,
 4937        cx: &mut Context<Self>,
 4938    ) {
 4939        let mut context_menu = self.context_menu.borrow_mut();
 4940        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4941            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4942                // Toggle if we're selecting the same one
 4943                *context_menu = None;
 4944                cx.notify();
 4945                return;
 4946            } else {
 4947                // Otherwise, clear it and start a new one
 4948                *context_menu = None;
 4949                cx.notify();
 4950            }
 4951        }
 4952        drop(context_menu);
 4953        let snapshot = self.snapshot(window, cx);
 4954        let deployed_from_indicator = action.deployed_from_indicator;
 4955        let mut task = self.code_actions_task.take();
 4956        let action = action.clone();
 4957        cx.spawn_in(window, async move |editor, cx| {
 4958            while let Some(prev_task) = task {
 4959                prev_task.await.log_err();
 4960                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4961            }
 4962
 4963            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4964                if editor.focus_handle.is_focused(window) {
 4965                    let multibuffer_point = action
 4966                        .deployed_from_indicator
 4967                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4968                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4969                    let (buffer, buffer_row) = snapshot
 4970                        .buffer_snapshot
 4971                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4972                        .and_then(|(buffer_snapshot, range)| {
 4973                            editor
 4974                                .buffer
 4975                                .read(cx)
 4976                                .buffer(buffer_snapshot.remote_id())
 4977                                .map(|buffer| (buffer, range.start.row))
 4978                        })?;
 4979                    let (_, code_actions) = editor
 4980                        .available_code_actions
 4981                        .clone()
 4982                        .and_then(|(location, code_actions)| {
 4983                            let snapshot = location.buffer.read(cx).snapshot();
 4984                            let point_range = location.range.to_point(&snapshot);
 4985                            let point_range = point_range.start.row..=point_range.end.row;
 4986                            if point_range.contains(&buffer_row) {
 4987                                Some((location, code_actions))
 4988                            } else {
 4989                                None
 4990                            }
 4991                        })
 4992                        .unzip();
 4993                    let buffer_id = buffer.read(cx).remote_id();
 4994                    let tasks = editor
 4995                        .tasks
 4996                        .get(&(buffer_id, buffer_row))
 4997                        .map(|t| Arc::new(t.to_owned()));
 4998                    if tasks.is_none() && code_actions.is_none() {
 4999                        return None;
 5000                    }
 5001
 5002                    editor.completion_tasks.clear();
 5003                    editor.discard_inline_completion(false, cx);
 5004                    let task_context =
 5005                        tasks
 5006                            .as_ref()
 5007                            .zip(editor.project.clone())
 5008                            .map(|(tasks, project)| {
 5009                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5010                            });
 5011
 5012                    let debugger_flag = cx.has_flag::<Debugger>();
 5013
 5014                    Some(cx.spawn_in(window, async move |editor, cx| {
 5015                        let task_context = match task_context {
 5016                            Some(task_context) => task_context.await,
 5017                            None => None,
 5018                        };
 5019                        let resolved_tasks =
 5020                            tasks
 5021                                .zip(task_context)
 5022                                .map(|(tasks, task_context)| ResolvedTasks {
 5023                                    templates: tasks.resolve(&task_context).collect(),
 5024                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5025                                        multibuffer_point.row,
 5026                                        tasks.column,
 5027                                    )),
 5028                                });
 5029                        let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
 5030                            tasks
 5031                                .templates
 5032                                .iter()
 5033                                .filter(|task| {
 5034                                    if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 5035                                        debugger_flag
 5036                                    } else {
 5037                                        true
 5038                                    }
 5039                                })
 5040                                .count()
 5041                                == 1
 5042                        }) && code_actions
 5043                            .as_ref()
 5044                            .map_or(true, |actions| actions.is_empty());
 5045                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5046                            *editor.context_menu.borrow_mut() =
 5047                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5048                                    buffer,
 5049                                    actions: CodeActionContents::new(
 5050                                        resolved_tasks,
 5051                                        code_actions,
 5052                                        cx,
 5053                                    ),
 5054                                    selected_item: Default::default(),
 5055                                    scroll_handle: UniformListScrollHandle::default(),
 5056                                    deployed_from_indicator,
 5057                                }));
 5058                            if spawn_straight_away {
 5059                                if let Some(task) = editor.confirm_code_action(
 5060                                    &ConfirmCodeAction { item_ix: Some(0) },
 5061                                    window,
 5062                                    cx,
 5063                                ) {
 5064                                    cx.notify();
 5065                                    return task;
 5066                                }
 5067                            }
 5068                            cx.notify();
 5069                            Task::ready(Ok(()))
 5070                        }) {
 5071                            task.await
 5072                        } else {
 5073                            Ok(())
 5074                        }
 5075                    }))
 5076                } else {
 5077                    Some(Task::ready(Ok(())))
 5078                }
 5079            })?;
 5080            if let Some(task) = spawned_test_task {
 5081                task.await?;
 5082            }
 5083
 5084            Ok::<_, anyhow::Error>(())
 5085        })
 5086        .detach_and_log_err(cx);
 5087    }
 5088
 5089    pub fn confirm_code_action(
 5090        &mut self,
 5091        action: &ConfirmCodeAction,
 5092        window: &mut Window,
 5093        cx: &mut Context<Self>,
 5094    ) -> Option<Task<Result<()>>> {
 5095        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5096
 5097        let actions_menu =
 5098            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5099                menu
 5100            } else {
 5101                return None;
 5102            };
 5103
 5104        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5105        let action = actions_menu.actions.get(action_ix)?;
 5106        let title = action.label();
 5107        let buffer = actions_menu.buffer;
 5108        let workspace = self.workspace()?;
 5109
 5110        match action {
 5111            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5112                match resolved_task.task_type() {
 5113                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5114                        workspace.schedule_resolved_task(
 5115                            task_source_kind,
 5116                            resolved_task,
 5117                            false,
 5118                            window,
 5119                            cx,
 5120                        );
 5121
 5122                        Some(Task::ready(Ok(())))
 5123                    }),
 5124                    task::TaskType::Debug(_) => {
 5125                        workspace.update(cx, |workspace, cx| {
 5126                            workspace.schedule_debug_task(resolved_task, window, cx);
 5127                        });
 5128                        Some(Task::ready(Ok(())))
 5129                    }
 5130                }
 5131            }
 5132            CodeActionsItem::CodeAction {
 5133                excerpt_id,
 5134                action,
 5135                provider,
 5136            } => {
 5137                let apply_code_action =
 5138                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5139                let workspace = workspace.downgrade();
 5140                Some(cx.spawn_in(window, async move |editor, cx| {
 5141                    let project_transaction = apply_code_action.await?;
 5142                    Self::open_project_transaction(
 5143                        &editor,
 5144                        workspace,
 5145                        project_transaction,
 5146                        title,
 5147                        cx,
 5148                    )
 5149                    .await
 5150                }))
 5151            }
 5152        }
 5153    }
 5154
 5155    pub async fn open_project_transaction(
 5156        this: &WeakEntity<Editor>,
 5157        workspace: WeakEntity<Workspace>,
 5158        transaction: ProjectTransaction,
 5159        title: String,
 5160        cx: &mut AsyncWindowContext,
 5161    ) -> Result<()> {
 5162        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5163        cx.update(|_, cx| {
 5164            entries.sort_unstable_by_key(|(buffer, _)| {
 5165                buffer.read(cx).file().map(|f| f.path().clone())
 5166            });
 5167        })?;
 5168
 5169        // If the project transaction's edits are all contained within this editor, then
 5170        // avoid opening a new editor to display them.
 5171
 5172        if let Some((buffer, transaction)) = entries.first() {
 5173            if entries.len() == 1 {
 5174                let excerpt = this.update(cx, |editor, cx| {
 5175                    editor
 5176                        .buffer()
 5177                        .read(cx)
 5178                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5179                })?;
 5180                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5181                    if excerpted_buffer == *buffer {
 5182                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5183                            let excerpt_range = excerpt_range.to_offset(buffer);
 5184                            buffer
 5185                                .edited_ranges_for_transaction::<usize>(transaction)
 5186                                .all(|range| {
 5187                                    excerpt_range.start <= range.start
 5188                                        && excerpt_range.end >= range.end
 5189                                })
 5190                        })?;
 5191
 5192                        if all_edits_within_excerpt {
 5193                            return Ok(());
 5194                        }
 5195                    }
 5196                }
 5197            }
 5198        } else {
 5199            return Ok(());
 5200        }
 5201
 5202        let mut ranges_to_highlight = Vec::new();
 5203        let excerpt_buffer = cx.new(|cx| {
 5204            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5205            for (buffer_handle, transaction) in &entries {
 5206                let edited_ranges = buffer_handle
 5207                    .read(cx)
 5208                    .edited_ranges_for_transaction::<Point>(transaction)
 5209                    .collect::<Vec<_>>();
 5210                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5211                    PathKey::for_buffer(buffer_handle, cx),
 5212                    buffer_handle.clone(),
 5213                    edited_ranges,
 5214                    DEFAULT_MULTIBUFFER_CONTEXT,
 5215                    cx,
 5216                );
 5217
 5218                ranges_to_highlight.extend(ranges);
 5219            }
 5220            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5221            multibuffer
 5222        })?;
 5223
 5224        workspace.update_in(cx, |workspace, window, cx| {
 5225            let project = workspace.project().clone();
 5226            let editor =
 5227                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5228            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5229            editor.update(cx, |editor, cx| {
 5230                editor.highlight_background::<Self>(
 5231                    &ranges_to_highlight,
 5232                    |theme| theme.editor_highlighted_line_background,
 5233                    cx,
 5234                );
 5235            });
 5236        })?;
 5237
 5238        Ok(())
 5239    }
 5240
 5241    pub fn clear_code_action_providers(&mut self) {
 5242        self.code_action_providers.clear();
 5243        self.available_code_actions.take();
 5244    }
 5245
 5246    pub fn add_code_action_provider(
 5247        &mut self,
 5248        provider: Rc<dyn CodeActionProvider>,
 5249        window: &mut Window,
 5250        cx: &mut Context<Self>,
 5251    ) {
 5252        if self
 5253            .code_action_providers
 5254            .iter()
 5255            .any(|existing_provider| existing_provider.id() == provider.id())
 5256        {
 5257            return;
 5258        }
 5259
 5260        self.code_action_providers.push(provider);
 5261        self.refresh_code_actions(window, cx);
 5262    }
 5263
 5264    pub fn remove_code_action_provider(
 5265        &mut self,
 5266        id: Arc<str>,
 5267        window: &mut Window,
 5268        cx: &mut Context<Self>,
 5269    ) {
 5270        self.code_action_providers
 5271            .retain(|provider| provider.id() != id);
 5272        self.refresh_code_actions(window, cx);
 5273    }
 5274
 5275    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5276        let newest_selection = self.selections.newest_anchor().clone();
 5277        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5278        let buffer = self.buffer.read(cx);
 5279        if newest_selection.head().diff_base_anchor.is_some() {
 5280            return None;
 5281        }
 5282        let (start_buffer, start) =
 5283            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5284        let (end_buffer, end) =
 5285            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5286        if start_buffer != end_buffer {
 5287            return None;
 5288        }
 5289
 5290        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5291            cx.background_executor()
 5292                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5293                .await;
 5294
 5295            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5296                let providers = this.code_action_providers.clone();
 5297                let tasks = this
 5298                    .code_action_providers
 5299                    .iter()
 5300                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5301                    .collect::<Vec<_>>();
 5302                (providers, tasks)
 5303            })?;
 5304
 5305            let mut actions = Vec::new();
 5306            for (provider, provider_actions) in
 5307                providers.into_iter().zip(future::join_all(tasks).await)
 5308            {
 5309                if let Some(provider_actions) = provider_actions.log_err() {
 5310                    actions.extend(provider_actions.into_iter().map(|action| {
 5311                        AvailableCodeAction {
 5312                            excerpt_id: newest_selection.start.excerpt_id,
 5313                            action,
 5314                            provider: provider.clone(),
 5315                        }
 5316                    }));
 5317                }
 5318            }
 5319
 5320            this.update(cx, |this, cx| {
 5321                this.available_code_actions = if actions.is_empty() {
 5322                    None
 5323                } else {
 5324                    Some((
 5325                        Location {
 5326                            buffer: start_buffer,
 5327                            range: start..end,
 5328                        },
 5329                        actions.into(),
 5330                    ))
 5331                };
 5332                cx.notify();
 5333            })
 5334        }));
 5335        None
 5336    }
 5337
 5338    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5339        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5340            self.show_git_blame_inline = false;
 5341
 5342            self.show_git_blame_inline_delay_task =
 5343                Some(cx.spawn_in(window, async move |this, cx| {
 5344                    cx.background_executor().timer(delay).await;
 5345
 5346                    this.update(cx, |this, cx| {
 5347                        this.show_git_blame_inline = true;
 5348                        cx.notify();
 5349                    })
 5350                    .log_err();
 5351                }));
 5352        }
 5353    }
 5354
 5355    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5356        if self.pending_rename.is_some() {
 5357            return None;
 5358        }
 5359
 5360        let provider = self.semantics_provider.clone()?;
 5361        let buffer = self.buffer.read(cx);
 5362        let newest_selection = self.selections.newest_anchor().clone();
 5363        let cursor_position = newest_selection.head();
 5364        let (cursor_buffer, cursor_buffer_position) =
 5365            buffer.text_anchor_for_position(cursor_position, cx)?;
 5366        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5367        if cursor_buffer != tail_buffer {
 5368            return None;
 5369        }
 5370        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5371        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5372            cx.background_executor()
 5373                .timer(Duration::from_millis(debounce))
 5374                .await;
 5375
 5376            let highlights = if let Some(highlights) = cx
 5377                .update(|cx| {
 5378                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5379                })
 5380                .ok()
 5381                .flatten()
 5382            {
 5383                highlights.await.log_err()
 5384            } else {
 5385                None
 5386            };
 5387
 5388            if let Some(highlights) = highlights {
 5389                this.update(cx, |this, cx| {
 5390                    if this.pending_rename.is_some() {
 5391                        return;
 5392                    }
 5393
 5394                    let buffer_id = cursor_position.buffer_id;
 5395                    let buffer = this.buffer.read(cx);
 5396                    if !buffer
 5397                        .text_anchor_for_position(cursor_position, cx)
 5398                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5399                    {
 5400                        return;
 5401                    }
 5402
 5403                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5404                    let mut write_ranges = Vec::new();
 5405                    let mut read_ranges = Vec::new();
 5406                    for highlight in highlights {
 5407                        for (excerpt_id, excerpt_range) in
 5408                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5409                        {
 5410                            let start = highlight
 5411                                .range
 5412                                .start
 5413                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5414                            let end = highlight
 5415                                .range
 5416                                .end
 5417                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5418                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5419                                continue;
 5420                            }
 5421
 5422                            let range = Anchor {
 5423                                buffer_id,
 5424                                excerpt_id,
 5425                                text_anchor: start,
 5426                                diff_base_anchor: None,
 5427                            }..Anchor {
 5428                                buffer_id,
 5429                                excerpt_id,
 5430                                text_anchor: end,
 5431                                diff_base_anchor: None,
 5432                            };
 5433                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5434                                write_ranges.push(range);
 5435                            } else {
 5436                                read_ranges.push(range);
 5437                            }
 5438                        }
 5439                    }
 5440
 5441                    this.highlight_background::<DocumentHighlightRead>(
 5442                        &read_ranges,
 5443                        |theme| theme.editor_document_highlight_read_background,
 5444                        cx,
 5445                    );
 5446                    this.highlight_background::<DocumentHighlightWrite>(
 5447                        &write_ranges,
 5448                        |theme| theme.editor_document_highlight_write_background,
 5449                        cx,
 5450                    );
 5451                    cx.notify();
 5452                })
 5453                .log_err();
 5454            }
 5455        }));
 5456        None
 5457    }
 5458
 5459    fn prepare_highlight_query_from_selection(
 5460        &mut self,
 5461        cx: &mut Context<Editor>,
 5462    ) -> Option<(String, Range<Anchor>)> {
 5463        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5464            return None;
 5465        }
 5466        if !EditorSettings::get_global(cx).selection_highlight {
 5467            return None;
 5468        }
 5469        if self.selections.count() != 1 || self.selections.line_mode {
 5470            return None;
 5471        }
 5472        let selection = self.selections.newest::<Point>(cx);
 5473        if selection.is_empty() || selection.start.row != selection.end.row {
 5474            return None;
 5475        }
 5476        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5477        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5478        let query = multi_buffer_snapshot
 5479            .text_for_range(selection_anchor_range.clone())
 5480            .collect::<String>();
 5481        if query.trim().is_empty() {
 5482            return None;
 5483        }
 5484        Some((query, selection_anchor_range))
 5485    }
 5486
 5487    fn update_selection_occurrence_highlights(
 5488        &mut self,
 5489        query_text: String,
 5490        query_range: Range<Anchor>,
 5491        multi_buffer_range_to_query: Range<Point>,
 5492        use_debounce: bool,
 5493        window: &mut Window,
 5494        cx: &mut Context<Editor>,
 5495    ) -> Task<()> {
 5496        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5497        cx.spawn_in(window, async move |editor, cx| {
 5498            if use_debounce {
 5499                cx.background_executor()
 5500                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5501                    .await;
 5502            }
 5503            let match_task = cx.background_spawn(async move {
 5504                let buffer_ranges = multi_buffer_snapshot
 5505                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5506                    .into_iter()
 5507                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5508                let mut match_ranges = Vec::new();
 5509                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5510                    match_ranges.extend(
 5511                        project::search::SearchQuery::text(
 5512                            query_text.clone(),
 5513                            false,
 5514                            false,
 5515                            false,
 5516                            Default::default(),
 5517                            Default::default(),
 5518                            false,
 5519                            None,
 5520                        )
 5521                        .unwrap()
 5522                        .search(&buffer_snapshot, Some(search_range.clone()))
 5523                        .await
 5524                        .into_iter()
 5525                        .filter_map(|match_range| {
 5526                            let match_start = buffer_snapshot
 5527                                .anchor_after(search_range.start + match_range.start);
 5528                            let match_end =
 5529                                buffer_snapshot.anchor_before(search_range.start + match_range.end);
 5530                            let match_anchor_range = Anchor::range_in_buffer(
 5531                                excerpt_id,
 5532                                buffer_snapshot.remote_id(),
 5533                                match_start..match_end,
 5534                            );
 5535                            (match_anchor_range != query_range).then_some(match_anchor_range)
 5536                        }),
 5537                    );
 5538                }
 5539                match_ranges
 5540            });
 5541            let match_ranges = match_task.await;
 5542            editor
 5543                .update_in(cx, |editor, _, cx| {
 5544                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5545                    if !match_ranges.is_empty() {
 5546                        editor.highlight_background::<SelectedTextHighlight>(
 5547                            &match_ranges,
 5548                            |theme| theme.editor_document_highlight_bracket_background,
 5549                            cx,
 5550                        )
 5551                    }
 5552                })
 5553                .log_err();
 5554        })
 5555    }
 5556
 5557    fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
 5558        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5559        else {
 5560            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5561            self.quick_selection_highlight_task.take();
 5562            self.debounced_selection_highlight_task.take();
 5563            return;
 5564        };
 5565        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5566        if self
 5567            .quick_selection_highlight_task
 5568            .as_ref()
 5569            .map_or(true, |(prev_anchor_range, _)| {
 5570                prev_anchor_range != &query_range
 5571            })
 5572        {
 5573            let multi_buffer_visible_start = self
 5574                .scroll_manager
 5575                .anchor()
 5576                .anchor
 5577                .to_point(&multi_buffer_snapshot);
 5578            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5579                multi_buffer_visible_start
 5580                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5581                Bias::Left,
 5582            );
 5583            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5584            self.quick_selection_highlight_task = Some((
 5585                query_range.clone(),
 5586                self.update_selection_occurrence_highlights(
 5587                    query_text.clone(),
 5588                    query_range.clone(),
 5589                    multi_buffer_visible_range,
 5590                    false,
 5591                    window,
 5592                    cx,
 5593                ),
 5594            ));
 5595        }
 5596        if self
 5597            .debounced_selection_highlight_task
 5598            .as_ref()
 5599            .map_or(true, |(prev_anchor_range, _)| {
 5600                prev_anchor_range != &query_range
 5601            })
 5602        {
 5603            let multi_buffer_start = multi_buffer_snapshot
 5604                .anchor_before(0)
 5605                .to_point(&multi_buffer_snapshot);
 5606            let multi_buffer_end = multi_buffer_snapshot
 5607                .anchor_after(multi_buffer_snapshot.len())
 5608                .to_point(&multi_buffer_snapshot);
 5609            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5610            self.debounced_selection_highlight_task = Some((
 5611                query_range.clone(),
 5612                self.update_selection_occurrence_highlights(
 5613                    query_text,
 5614                    query_range,
 5615                    multi_buffer_full_range,
 5616                    true,
 5617                    window,
 5618                    cx,
 5619                ),
 5620            ));
 5621        }
 5622    }
 5623
 5624    pub fn refresh_inline_completion(
 5625        &mut self,
 5626        debounce: bool,
 5627        user_requested: bool,
 5628        window: &mut Window,
 5629        cx: &mut Context<Self>,
 5630    ) -> Option<()> {
 5631        let provider = self.edit_prediction_provider()?;
 5632        let cursor = self.selections.newest_anchor().head();
 5633        let (buffer, cursor_buffer_position) =
 5634            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5635
 5636        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5637            self.discard_inline_completion(false, cx);
 5638            return None;
 5639        }
 5640
 5641        if !user_requested
 5642            && (!self.should_show_edit_predictions()
 5643                || !self.is_focused(window)
 5644                || buffer.read(cx).is_empty())
 5645        {
 5646            self.discard_inline_completion(false, cx);
 5647            return None;
 5648        }
 5649
 5650        self.update_visible_inline_completion(window, cx);
 5651        provider.refresh(
 5652            self.project.clone(),
 5653            buffer,
 5654            cursor_buffer_position,
 5655            debounce,
 5656            cx,
 5657        );
 5658        Some(())
 5659    }
 5660
 5661    fn show_edit_predictions_in_menu(&self) -> bool {
 5662        match self.edit_prediction_settings {
 5663            EditPredictionSettings::Disabled => false,
 5664            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5665        }
 5666    }
 5667
 5668    pub fn edit_predictions_enabled(&self) -> bool {
 5669        match self.edit_prediction_settings {
 5670            EditPredictionSettings::Disabled => false,
 5671            EditPredictionSettings::Enabled { .. } => true,
 5672        }
 5673    }
 5674
 5675    fn edit_prediction_requires_modifier(&self) -> bool {
 5676        match self.edit_prediction_settings {
 5677            EditPredictionSettings::Disabled => false,
 5678            EditPredictionSettings::Enabled {
 5679                preview_requires_modifier,
 5680                ..
 5681            } => preview_requires_modifier,
 5682        }
 5683    }
 5684
 5685    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5686        if self.edit_prediction_provider.is_none() {
 5687            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5688        } else {
 5689            let selection = self.selections.newest_anchor();
 5690            let cursor = selection.head();
 5691
 5692            if let Some((buffer, cursor_buffer_position)) =
 5693                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5694            {
 5695                self.edit_prediction_settings =
 5696                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5697            }
 5698        }
 5699    }
 5700
 5701    fn edit_prediction_settings_at_position(
 5702        &self,
 5703        buffer: &Entity<Buffer>,
 5704        buffer_position: language::Anchor,
 5705        cx: &App,
 5706    ) -> EditPredictionSettings {
 5707        if !self.mode.is_full()
 5708            || !self.show_inline_completions_override.unwrap_or(true)
 5709            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5710        {
 5711            return EditPredictionSettings::Disabled;
 5712        }
 5713
 5714        let buffer = buffer.read(cx);
 5715
 5716        let file = buffer.file();
 5717
 5718        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5719            return EditPredictionSettings::Disabled;
 5720        };
 5721
 5722        let by_provider = matches!(
 5723            self.menu_inline_completions_policy,
 5724            MenuInlineCompletionsPolicy::ByProvider
 5725        );
 5726
 5727        let show_in_menu = by_provider
 5728            && self
 5729                .edit_prediction_provider
 5730                .as_ref()
 5731                .map_or(false, |provider| {
 5732                    provider.provider.show_completions_in_menu()
 5733                });
 5734
 5735        let preview_requires_modifier =
 5736            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5737
 5738        EditPredictionSettings::Enabled {
 5739            show_in_menu,
 5740            preview_requires_modifier,
 5741        }
 5742    }
 5743
 5744    fn should_show_edit_predictions(&self) -> bool {
 5745        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5746    }
 5747
 5748    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5749        matches!(
 5750            self.edit_prediction_preview,
 5751            EditPredictionPreview::Active { .. }
 5752        )
 5753    }
 5754
 5755    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5756        let cursor = self.selections.newest_anchor().head();
 5757        if let Some((buffer, cursor_position)) =
 5758            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5759        {
 5760            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5761        } else {
 5762            false
 5763        }
 5764    }
 5765
 5766    fn edit_predictions_enabled_in_buffer(
 5767        &self,
 5768        buffer: &Entity<Buffer>,
 5769        buffer_position: language::Anchor,
 5770        cx: &App,
 5771    ) -> bool {
 5772        maybe!({
 5773            if self.read_only(cx) {
 5774                return Some(false);
 5775            }
 5776            let provider = self.edit_prediction_provider()?;
 5777            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5778                return Some(false);
 5779            }
 5780            let buffer = buffer.read(cx);
 5781            let Some(file) = buffer.file() else {
 5782                return Some(true);
 5783            };
 5784            let settings = all_language_settings(Some(file), cx);
 5785            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5786        })
 5787        .unwrap_or(false)
 5788    }
 5789
 5790    fn cycle_inline_completion(
 5791        &mut self,
 5792        direction: Direction,
 5793        window: &mut Window,
 5794        cx: &mut Context<Self>,
 5795    ) -> Option<()> {
 5796        let provider = self.edit_prediction_provider()?;
 5797        let cursor = self.selections.newest_anchor().head();
 5798        let (buffer, cursor_buffer_position) =
 5799            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5800        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5801            return None;
 5802        }
 5803
 5804        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5805        self.update_visible_inline_completion(window, cx);
 5806
 5807        Some(())
 5808    }
 5809
 5810    pub fn show_inline_completion(
 5811        &mut self,
 5812        _: &ShowEditPrediction,
 5813        window: &mut Window,
 5814        cx: &mut Context<Self>,
 5815    ) {
 5816        if !self.has_active_inline_completion() {
 5817            self.refresh_inline_completion(false, true, window, cx);
 5818            return;
 5819        }
 5820
 5821        self.update_visible_inline_completion(window, cx);
 5822    }
 5823
 5824    pub fn display_cursor_names(
 5825        &mut self,
 5826        _: &DisplayCursorNames,
 5827        window: &mut Window,
 5828        cx: &mut Context<Self>,
 5829    ) {
 5830        self.show_cursor_names(window, cx);
 5831    }
 5832
 5833    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5834        self.show_cursor_names = true;
 5835        cx.notify();
 5836        cx.spawn_in(window, async move |this, cx| {
 5837            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5838            this.update(cx, |this, cx| {
 5839                this.show_cursor_names = false;
 5840                cx.notify()
 5841            })
 5842            .ok()
 5843        })
 5844        .detach();
 5845    }
 5846
 5847    pub fn next_edit_prediction(
 5848        &mut self,
 5849        _: &NextEditPrediction,
 5850        window: &mut Window,
 5851        cx: &mut Context<Self>,
 5852    ) {
 5853        if self.has_active_inline_completion() {
 5854            self.cycle_inline_completion(Direction::Next, window, cx);
 5855        } else {
 5856            let is_copilot_disabled = self
 5857                .refresh_inline_completion(false, true, window, cx)
 5858                .is_none();
 5859            if is_copilot_disabled {
 5860                cx.propagate();
 5861            }
 5862        }
 5863    }
 5864
 5865    pub fn previous_edit_prediction(
 5866        &mut self,
 5867        _: &PreviousEditPrediction,
 5868        window: &mut Window,
 5869        cx: &mut Context<Self>,
 5870    ) {
 5871        if self.has_active_inline_completion() {
 5872            self.cycle_inline_completion(Direction::Prev, window, cx);
 5873        } else {
 5874            let is_copilot_disabled = self
 5875                .refresh_inline_completion(false, true, window, cx)
 5876                .is_none();
 5877            if is_copilot_disabled {
 5878                cx.propagate();
 5879            }
 5880        }
 5881    }
 5882
 5883    pub fn accept_edit_prediction(
 5884        &mut self,
 5885        _: &AcceptEditPrediction,
 5886        window: &mut Window,
 5887        cx: &mut Context<Self>,
 5888    ) {
 5889        if self.show_edit_predictions_in_menu() {
 5890            self.hide_context_menu(window, cx);
 5891        }
 5892
 5893        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5894            return;
 5895        };
 5896
 5897        self.report_inline_completion_event(
 5898            active_inline_completion.completion_id.clone(),
 5899            true,
 5900            cx,
 5901        );
 5902
 5903        match &active_inline_completion.completion {
 5904            InlineCompletion::Move { target, .. } => {
 5905                let target = *target;
 5906
 5907                if let Some(position_map) = &self.last_position_map {
 5908                    if position_map
 5909                        .visible_row_range
 5910                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5911                        || !self.edit_prediction_requires_modifier()
 5912                    {
 5913                        self.unfold_ranges(&[target..target], true, false, cx);
 5914                        // Note that this is also done in vim's handler of the Tab action.
 5915                        self.change_selections(
 5916                            Some(Autoscroll::newest()),
 5917                            window,
 5918                            cx,
 5919                            |selections| {
 5920                                selections.select_anchor_ranges([target..target]);
 5921                            },
 5922                        );
 5923                        self.clear_row_highlights::<EditPredictionPreview>();
 5924
 5925                        self.edit_prediction_preview
 5926                            .set_previous_scroll_position(None);
 5927                    } else {
 5928                        self.edit_prediction_preview
 5929                            .set_previous_scroll_position(Some(
 5930                                position_map.snapshot.scroll_anchor,
 5931                            ));
 5932
 5933                        self.highlight_rows::<EditPredictionPreview>(
 5934                            target..target,
 5935                            cx.theme().colors().editor_highlighted_line_background,
 5936                            true,
 5937                            cx,
 5938                        );
 5939                        self.request_autoscroll(Autoscroll::fit(), cx);
 5940                    }
 5941                }
 5942            }
 5943            InlineCompletion::Edit { edits, .. } => {
 5944                if let Some(provider) = self.edit_prediction_provider() {
 5945                    provider.accept(cx);
 5946                }
 5947
 5948                let snapshot = self.buffer.read(cx).snapshot(cx);
 5949                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5950
 5951                self.buffer.update(cx, |buffer, cx| {
 5952                    buffer.edit(edits.iter().cloned(), None, cx)
 5953                });
 5954
 5955                self.change_selections(None, window, cx, |s| {
 5956                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5957                });
 5958
 5959                self.update_visible_inline_completion(window, cx);
 5960                if self.active_inline_completion.is_none() {
 5961                    self.refresh_inline_completion(true, true, window, cx);
 5962                }
 5963
 5964                cx.notify();
 5965            }
 5966        }
 5967
 5968        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5969    }
 5970
 5971    pub fn accept_partial_inline_completion(
 5972        &mut self,
 5973        _: &AcceptPartialEditPrediction,
 5974        window: &mut Window,
 5975        cx: &mut Context<Self>,
 5976    ) {
 5977        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5978            return;
 5979        };
 5980        if self.selections.count() != 1 {
 5981            return;
 5982        }
 5983
 5984        self.report_inline_completion_event(
 5985            active_inline_completion.completion_id.clone(),
 5986            true,
 5987            cx,
 5988        );
 5989
 5990        match &active_inline_completion.completion {
 5991            InlineCompletion::Move { target, .. } => {
 5992                let target = *target;
 5993                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5994                    selections.select_anchor_ranges([target..target]);
 5995                });
 5996            }
 5997            InlineCompletion::Edit { edits, .. } => {
 5998                // Find an insertion that starts at the cursor position.
 5999                let snapshot = self.buffer.read(cx).snapshot(cx);
 6000                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6001                let insertion = edits.iter().find_map(|(range, text)| {
 6002                    let range = range.to_offset(&snapshot);
 6003                    if range.is_empty() && range.start == cursor_offset {
 6004                        Some(text)
 6005                    } else {
 6006                        None
 6007                    }
 6008                });
 6009
 6010                if let Some(text) = insertion {
 6011                    let mut partial_completion = text
 6012                        .chars()
 6013                        .by_ref()
 6014                        .take_while(|c| c.is_alphabetic())
 6015                        .collect::<String>();
 6016                    if partial_completion.is_empty() {
 6017                        partial_completion = text
 6018                            .chars()
 6019                            .by_ref()
 6020                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6021                            .collect::<String>();
 6022                    }
 6023
 6024                    cx.emit(EditorEvent::InputHandled {
 6025                        utf16_range_to_replace: None,
 6026                        text: partial_completion.clone().into(),
 6027                    });
 6028
 6029                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6030
 6031                    self.refresh_inline_completion(true, true, window, cx);
 6032                    cx.notify();
 6033                } else {
 6034                    self.accept_edit_prediction(&Default::default(), window, cx);
 6035                }
 6036            }
 6037        }
 6038    }
 6039
 6040    fn discard_inline_completion(
 6041        &mut self,
 6042        should_report_inline_completion_event: bool,
 6043        cx: &mut Context<Self>,
 6044    ) -> bool {
 6045        if should_report_inline_completion_event {
 6046            let completion_id = self
 6047                .active_inline_completion
 6048                .as_ref()
 6049                .and_then(|active_completion| active_completion.completion_id.clone());
 6050
 6051            self.report_inline_completion_event(completion_id, false, cx);
 6052        }
 6053
 6054        if let Some(provider) = self.edit_prediction_provider() {
 6055            provider.discard(cx);
 6056        }
 6057
 6058        self.take_active_inline_completion(cx)
 6059    }
 6060
 6061    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6062        let Some(provider) = self.edit_prediction_provider() else {
 6063            return;
 6064        };
 6065
 6066        let Some((_, buffer, _)) = self
 6067            .buffer
 6068            .read(cx)
 6069            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6070        else {
 6071            return;
 6072        };
 6073
 6074        let extension = buffer
 6075            .read(cx)
 6076            .file()
 6077            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6078
 6079        let event_type = match accepted {
 6080            true => "Edit Prediction Accepted",
 6081            false => "Edit Prediction Discarded",
 6082        };
 6083        telemetry::event!(
 6084            event_type,
 6085            provider = provider.name(),
 6086            prediction_id = id,
 6087            suggestion_accepted = accepted,
 6088            file_extension = extension,
 6089        );
 6090    }
 6091
 6092    pub fn has_active_inline_completion(&self) -> bool {
 6093        self.active_inline_completion.is_some()
 6094    }
 6095
 6096    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6097        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6098            return false;
 6099        };
 6100
 6101        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6102        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6103        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6104        true
 6105    }
 6106
 6107    /// Returns true when we're displaying the edit prediction popover below the cursor
 6108    /// like we are not previewing and the LSP autocomplete menu is visible
 6109    /// or we are in `when_holding_modifier` mode.
 6110    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6111        if self.edit_prediction_preview_is_active()
 6112            || !self.show_edit_predictions_in_menu()
 6113            || !self.edit_predictions_enabled()
 6114        {
 6115            return false;
 6116        }
 6117
 6118        if self.has_visible_completions_menu() {
 6119            return true;
 6120        }
 6121
 6122        has_completion && self.edit_prediction_requires_modifier()
 6123    }
 6124
 6125    fn handle_modifiers_changed(
 6126        &mut self,
 6127        modifiers: Modifiers,
 6128        position_map: &PositionMap,
 6129        window: &mut Window,
 6130        cx: &mut Context<Self>,
 6131    ) {
 6132        if self.show_edit_predictions_in_menu() {
 6133            self.update_edit_prediction_preview(&modifiers, window, cx);
 6134        }
 6135
 6136        self.update_selection_mode(&modifiers, position_map, window, cx);
 6137
 6138        let mouse_position = window.mouse_position();
 6139        if !position_map.text_hitbox.is_hovered(window) {
 6140            return;
 6141        }
 6142
 6143        self.update_hovered_link(
 6144            position_map.point_for_position(mouse_position),
 6145            &position_map.snapshot,
 6146            modifiers,
 6147            window,
 6148            cx,
 6149        )
 6150    }
 6151
 6152    fn update_selection_mode(
 6153        &mut self,
 6154        modifiers: &Modifiers,
 6155        position_map: &PositionMap,
 6156        window: &mut Window,
 6157        cx: &mut Context<Self>,
 6158    ) {
 6159        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6160            return;
 6161        }
 6162
 6163        let mouse_position = window.mouse_position();
 6164        let point_for_position = position_map.point_for_position(mouse_position);
 6165        let position = point_for_position.previous_valid;
 6166
 6167        self.select(
 6168            SelectPhase::BeginColumnar {
 6169                position,
 6170                reset: false,
 6171                goal_column: point_for_position.exact_unclipped.column(),
 6172            },
 6173            window,
 6174            cx,
 6175        );
 6176    }
 6177
 6178    fn update_edit_prediction_preview(
 6179        &mut self,
 6180        modifiers: &Modifiers,
 6181        window: &mut Window,
 6182        cx: &mut Context<Self>,
 6183    ) {
 6184        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6185        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6186            return;
 6187        };
 6188
 6189        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6190            if matches!(
 6191                self.edit_prediction_preview,
 6192                EditPredictionPreview::Inactive { .. }
 6193            ) {
 6194                self.edit_prediction_preview = EditPredictionPreview::Active {
 6195                    previous_scroll_position: None,
 6196                    since: Instant::now(),
 6197                };
 6198
 6199                self.update_visible_inline_completion(window, cx);
 6200                cx.notify();
 6201            }
 6202        } else if let EditPredictionPreview::Active {
 6203            previous_scroll_position,
 6204            since,
 6205        } = self.edit_prediction_preview
 6206        {
 6207            if let (Some(previous_scroll_position), Some(position_map)) =
 6208                (previous_scroll_position, self.last_position_map.as_ref())
 6209            {
 6210                self.set_scroll_position(
 6211                    previous_scroll_position
 6212                        .scroll_position(&position_map.snapshot.display_snapshot),
 6213                    window,
 6214                    cx,
 6215                );
 6216            }
 6217
 6218            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6219                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6220            };
 6221            self.clear_row_highlights::<EditPredictionPreview>();
 6222            self.update_visible_inline_completion(window, cx);
 6223            cx.notify();
 6224        }
 6225    }
 6226
 6227    fn update_visible_inline_completion(
 6228        &mut self,
 6229        _window: &mut Window,
 6230        cx: &mut Context<Self>,
 6231    ) -> Option<()> {
 6232        let selection = self.selections.newest_anchor();
 6233        let cursor = selection.head();
 6234        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6235        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6236        let excerpt_id = cursor.excerpt_id;
 6237
 6238        let show_in_menu = self.show_edit_predictions_in_menu();
 6239        let completions_menu_has_precedence = !show_in_menu
 6240            && (self.context_menu.borrow().is_some()
 6241                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6242
 6243        if completions_menu_has_precedence
 6244            || !offset_selection.is_empty()
 6245            || self
 6246                .active_inline_completion
 6247                .as_ref()
 6248                .map_or(false, |completion| {
 6249                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6250                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6251                    !invalidation_range.contains(&offset_selection.head())
 6252                })
 6253        {
 6254            self.discard_inline_completion(false, cx);
 6255            return None;
 6256        }
 6257
 6258        self.take_active_inline_completion(cx);
 6259        let Some(provider) = self.edit_prediction_provider() else {
 6260            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6261            return None;
 6262        };
 6263
 6264        let (buffer, cursor_buffer_position) =
 6265            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6266
 6267        self.edit_prediction_settings =
 6268            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6269
 6270        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6271
 6272        if self.edit_prediction_indent_conflict {
 6273            let cursor_point = cursor.to_point(&multibuffer);
 6274
 6275            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6276
 6277            if let Some((_, indent)) = indents.iter().next() {
 6278                if indent.len == cursor_point.column {
 6279                    self.edit_prediction_indent_conflict = false;
 6280                }
 6281            }
 6282        }
 6283
 6284        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6285        let edits = inline_completion
 6286            .edits
 6287            .into_iter()
 6288            .flat_map(|(range, new_text)| {
 6289                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6290                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6291                Some((start..end, new_text))
 6292            })
 6293            .collect::<Vec<_>>();
 6294        if edits.is_empty() {
 6295            return None;
 6296        }
 6297
 6298        let first_edit_start = edits.first().unwrap().0.start;
 6299        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6300        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6301
 6302        let last_edit_end = edits.last().unwrap().0.end;
 6303        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6304        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6305
 6306        let cursor_row = cursor.to_point(&multibuffer).row;
 6307
 6308        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6309
 6310        let mut inlay_ids = Vec::new();
 6311        let invalidation_row_range;
 6312        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6313            Some(cursor_row..edit_end_row)
 6314        } else if cursor_row > edit_end_row {
 6315            Some(edit_start_row..cursor_row)
 6316        } else {
 6317            None
 6318        };
 6319        let is_move =
 6320            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6321        let completion = if is_move {
 6322            invalidation_row_range =
 6323                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6324            let target = first_edit_start;
 6325            InlineCompletion::Move { target, snapshot }
 6326        } else {
 6327            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6328                && !self.inline_completions_hidden_for_vim_mode;
 6329
 6330            if show_completions_in_buffer {
 6331                if edits
 6332                    .iter()
 6333                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6334                {
 6335                    let mut inlays = Vec::new();
 6336                    for (range, new_text) in &edits {
 6337                        let inlay = Inlay::inline_completion(
 6338                            post_inc(&mut self.next_inlay_id),
 6339                            range.start,
 6340                            new_text.as_str(),
 6341                        );
 6342                        inlay_ids.push(inlay.id);
 6343                        inlays.push(inlay);
 6344                    }
 6345
 6346                    self.splice_inlays(&[], inlays, cx);
 6347                } else {
 6348                    let background_color = cx.theme().status().deleted_background;
 6349                    self.highlight_text::<InlineCompletionHighlight>(
 6350                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6351                        HighlightStyle {
 6352                            background_color: Some(background_color),
 6353                            ..Default::default()
 6354                        },
 6355                        cx,
 6356                    );
 6357                }
 6358            }
 6359
 6360            invalidation_row_range = edit_start_row..edit_end_row;
 6361
 6362            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6363                if provider.show_tab_accept_marker() {
 6364                    EditDisplayMode::TabAccept
 6365                } else {
 6366                    EditDisplayMode::Inline
 6367                }
 6368            } else {
 6369                EditDisplayMode::DiffPopover
 6370            };
 6371
 6372            InlineCompletion::Edit {
 6373                edits,
 6374                edit_preview: inline_completion.edit_preview,
 6375                display_mode,
 6376                snapshot,
 6377            }
 6378        };
 6379
 6380        let invalidation_range = multibuffer
 6381            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6382            ..multibuffer.anchor_after(Point::new(
 6383                invalidation_row_range.end,
 6384                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6385            ));
 6386
 6387        self.stale_inline_completion_in_menu = None;
 6388        self.active_inline_completion = Some(InlineCompletionState {
 6389            inlay_ids,
 6390            completion,
 6391            completion_id: inline_completion.id,
 6392            invalidation_range,
 6393        });
 6394
 6395        cx.notify();
 6396
 6397        Some(())
 6398    }
 6399
 6400    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6401        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6402    }
 6403
 6404    fn render_code_actions_indicator(
 6405        &self,
 6406        _style: &EditorStyle,
 6407        row: DisplayRow,
 6408        is_active: bool,
 6409        breakpoint: Option<&(Anchor, Breakpoint)>,
 6410        cx: &mut Context<Self>,
 6411    ) -> Option<IconButton> {
 6412        let color = Color::Muted;
 6413        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6414        let show_tooltip = !self.context_menu_visible();
 6415
 6416        if self.available_code_actions.is_some() {
 6417            Some(
 6418                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6419                    .shape(ui::IconButtonShape::Square)
 6420                    .icon_size(IconSize::XSmall)
 6421                    .icon_color(color)
 6422                    .toggle_state(is_active)
 6423                    .when(show_tooltip, |this| {
 6424                        this.tooltip({
 6425                            let focus_handle = self.focus_handle.clone();
 6426                            move |window, cx| {
 6427                                Tooltip::for_action_in(
 6428                                    "Toggle Code Actions",
 6429                                    &ToggleCodeActions {
 6430                                        deployed_from_indicator: None,
 6431                                    },
 6432                                    &focus_handle,
 6433                                    window,
 6434                                    cx,
 6435                                )
 6436                            }
 6437                        })
 6438                    })
 6439                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6440                        window.focus(&editor.focus_handle(cx));
 6441                        editor.toggle_code_actions(
 6442                            &ToggleCodeActions {
 6443                                deployed_from_indicator: Some(row),
 6444                            },
 6445                            window,
 6446                            cx,
 6447                        );
 6448                    }))
 6449                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6450                        editor.set_breakpoint_context_menu(
 6451                            row,
 6452                            position,
 6453                            event.down.position,
 6454                            window,
 6455                            cx,
 6456                        );
 6457                    })),
 6458            )
 6459        } else {
 6460            None
 6461        }
 6462    }
 6463
 6464    fn clear_tasks(&mut self) {
 6465        self.tasks.clear()
 6466    }
 6467
 6468    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6469        if self.tasks.insert(key, value).is_some() {
 6470            // This case should hopefully be rare, but just in case...
 6471            log::error!(
 6472                "multiple different run targets found on a single line, only the last target will be rendered"
 6473            )
 6474        }
 6475    }
 6476
 6477    /// Get all display points of breakpoints that will be rendered within editor
 6478    ///
 6479    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6480    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6481    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6482    fn active_breakpoints(
 6483        &self,
 6484        range: Range<DisplayRow>,
 6485        window: &mut Window,
 6486        cx: &mut Context<Self>,
 6487    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6488        let mut breakpoint_display_points = HashMap::default();
 6489
 6490        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6491            return breakpoint_display_points;
 6492        };
 6493
 6494        let snapshot = self.snapshot(window, cx);
 6495
 6496        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6497        let Some(project) = self.project.as_ref() else {
 6498            return breakpoint_display_points;
 6499        };
 6500
 6501        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6502            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6503
 6504        for (buffer_snapshot, range, excerpt_id) in
 6505            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6506        {
 6507            let Some(buffer) = project.read_with(cx, |this, cx| {
 6508                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6509            }) else {
 6510                continue;
 6511            };
 6512            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6513                &buffer,
 6514                Some(
 6515                    buffer_snapshot.anchor_before(range.start)
 6516                        ..buffer_snapshot.anchor_after(range.end),
 6517                ),
 6518                buffer_snapshot,
 6519                cx,
 6520            );
 6521            for (anchor, breakpoint) in breakpoints {
 6522                let multi_buffer_anchor =
 6523                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6524                let position = multi_buffer_anchor
 6525                    .to_point(&multi_buffer_snapshot)
 6526                    .to_display_point(&snapshot);
 6527
 6528                breakpoint_display_points
 6529                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6530            }
 6531        }
 6532
 6533        breakpoint_display_points
 6534    }
 6535
 6536    fn breakpoint_context_menu(
 6537        &self,
 6538        anchor: Anchor,
 6539        window: &mut Window,
 6540        cx: &mut Context<Self>,
 6541    ) -> Entity<ui::ContextMenu> {
 6542        let weak_editor = cx.weak_entity();
 6543        let focus_handle = self.focus_handle(cx);
 6544
 6545        let row = self
 6546            .buffer
 6547            .read(cx)
 6548            .snapshot(cx)
 6549            .summary_for_anchor::<Point>(&anchor)
 6550            .row;
 6551
 6552        let breakpoint = self
 6553            .breakpoint_at_row(row, window, cx)
 6554            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6555
 6556        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6557            "Edit Log Breakpoint"
 6558        } else {
 6559            "Set Log Breakpoint"
 6560        };
 6561
 6562        let condition_breakpoint_msg = if breakpoint
 6563            .as_ref()
 6564            .is_some_and(|bp| bp.1.condition.is_some())
 6565        {
 6566            "Edit Condition Breakpoint"
 6567        } else {
 6568            "Set Condition Breakpoint"
 6569        };
 6570
 6571        let hit_condition_breakpoint_msg = if breakpoint
 6572            .as_ref()
 6573            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6574        {
 6575            "Edit Hit Condition Breakpoint"
 6576        } else {
 6577            "Set Hit Condition Breakpoint"
 6578        };
 6579
 6580        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6581            "Unset Breakpoint"
 6582        } else {
 6583            "Set Breakpoint"
 6584        };
 6585
 6586        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6587            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6588
 6589        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6590            BreakpointState::Enabled => Some("Disable"),
 6591            BreakpointState::Disabled => Some("Enable"),
 6592        });
 6593
 6594        let (anchor, breakpoint) =
 6595            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6596
 6597        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6598            menu.on_blur_subscription(Subscription::new(|| {}))
 6599                .context(focus_handle)
 6600                .when(run_to_cursor, |this| {
 6601                    let weak_editor = weak_editor.clone();
 6602                    this.entry("Run to cursor", None, move |window, cx| {
 6603                        weak_editor
 6604                            .update(cx, |editor, cx| {
 6605                                editor.change_selections(None, window, cx, |s| {
 6606                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6607                                });
 6608                            })
 6609                            .ok();
 6610
 6611                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6612                    })
 6613                    .separator()
 6614                })
 6615                .when_some(toggle_state_msg, |this, msg| {
 6616                    this.entry(msg, None, {
 6617                        let weak_editor = weak_editor.clone();
 6618                        let breakpoint = breakpoint.clone();
 6619                        move |_window, cx| {
 6620                            weak_editor
 6621                                .update(cx, |this, cx| {
 6622                                    this.edit_breakpoint_at_anchor(
 6623                                        anchor,
 6624                                        breakpoint.as_ref().clone(),
 6625                                        BreakpointEditAction::InvertState,
 6626                                        cx,
 6627                                    );
 6628                                })
 6629                                .log_err();
 6630                        }
 6631                    })
 6632                })
 6633                .entry(set_breakpoint_msg, None, {
 6634                    let weak_editor = weak_editor.clone();
 6635                    let breakpoint = breakpoint.clone();
 6636                    move |_window, cx| {
 6637                        weak_editor
 6638                            .update(cx, |this, cx| {
 6639                                this.edit_breakpoint_at_anchor(
 6640                                    anchor,
 6641                                    breakpoint.as_ref().clone(),
 6642                                    BreakpointEditAction::Toggle,
 6643                                    cx,
 6644                                );
 6645                            })
 6646                            .log_err();
 6647                    }
 6648                })
 6649                .entry(log_breakpoint_msg, None, {
 6650                    let breakpoint = breakpoint.clone();
 6651                    let weak_editor = weak_editor.clone();
 6652                    move |window, cx| {
 6653                        weak_editor
 6654                            .update(cx, |this, cx| {
 6655                                this.add_edit_breakpoint_block(
 6656                                    anchor,
 6657                                    breakpoint.as_ref(),
 6658                                    BreakpointPromptEditAction::Log,
 6659                                    window,
 6660                                    cx,
 6661                                );
 6662                            })
 6663                            .log_err();
 6664                    }
 6665                })
 6666                .entry(condition_breakpoint_msg, None, {
 6667                    let breakpoint = breakpoint.clone();
 6668                    let weak_editor = weak_editor.clone();
 6669                    move |window, cx| {
 6670                        weak_editor
 6671                            .update(cx, |this, cx| {
 6672                                this.add_edit_breakpoint_block(
 6673                                    anchor,
 6674                                    breakpoint.as_ref(),
 6675                                    BreakpointPromptEditAction::Condition,
 6676                                    window,
 6677                                    cx,
 6678                                );
 6679                            })
 6680                            .log_err();
 6681                    }
 6682                })
 6683                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6684                    weak_editor
 6685                        .update(cx, |this, cx| {
 6686                            this.add_edit_breakpoint_block(
 6687                                anchor,
 6688                                breakpoint.as_ref(),
 6689                                BreakpointPromptEditAction::HitCondition,
 6690                                window,
 6691                                cx,
 6692                            );
 6693                        })
 6694                        .log_err();
 6695                })
 6696        })
 6697    }
 6698
 6699    fn render_breakpoint(
 6700        &self,
 6701        position: Anchor,
 6702        row: DisplayRow,
 6703        breakpoint: &Breakpoint,
 6704        cx: &mut Context<Self>,
 6705    ) -> IconButton {
 6706        let (color, icon) = {
 6707            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6708                (false, false) => ui::IconName::DebugBreakpoint,
 6709                (true, false) => ui::IconName::DebugLogBreakpoint,
 6710                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6711                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6712            };
 6713
 6714            let color = if self
 6715                .gutter_breakpoint_indicator
 6716                .0
 6717                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6718            {
 6719                Color::Hint
 6720            } else {
 6721                Color::Debugger
 6722            };
 6723
 6724            (color, icon)
 6725        };
 6726
 6727        let breakpoint = Arc::from(breakpoint.clone());
 6728
 6729        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6730            .icon_size(IconSize::XSmall)
 6731            .size(ui::ButtonSize::None)
 6732            .icon_color(color)
 6733            .style(ButtonStyle::Transparent)
 6734            .on_click(cx.listener({
 6735                let breakpoint = breakpoint.clone();
 6736
 6737                move |editor, event: &ClickEvent, window, cx| {
 6738                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6739                        BreakpointEditAction::InvertState
 6740                    } else {
 6741                        BreakpointEditAction::Toggle
 6742                    };
 6743
 6744                    window.focus(&editor.focus_handle(cx));
 6745                    editor.edit_breakpoint_at_anchor(
 6746                        position,
 6747                        breakpoint.as_ref().clone(),
 6748                        edit_action,
 6749                        cx,
 6750                    );
 6751                }
 6752            }))
 6753            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6754                editor.set_breakpoint_context_menu(
 6755                    row,
 6756                    Some(position),
 6757                    event.down.position,
 6758                    window,
 6759                    cx,
 6760                );
 6761            }))
 6762    }
 6763
 6764    fn build_tasks_context(
 6765        project: &Entity<Project>,
 6766        buffer: &Entity<Buffer>,
 6767        buffer_row: u32,
 6768        tasks: &Arc<RunnableTasks>,
 6769        cx: &mut Context<Self>,
 6770    ) -> Task<Option<task::TaskContext>> {
 6771        let position = Point::new(buffer_row, tasks.column);
 6772        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6773        let location = Location {
 6774            buffer: buffer.clone(),
 6775            range: range_start..range_start,
 6776        };
 6777        // Fill in the environmental variables from the tree-sitter captures
 6778        let mut captured_task_variables = TaskVariables::default();
 6779        for (capture_name, value) in tasks.extra_variables.clone() {
 6780            captured_task_variables.insert(
 6781                task::VariableName::Custom(capture_name.into()),
 6782                value.clone(),
 6783            );
 6784        }
 6785        project.update(cx, |project, cx| {
 6786            project.task_store().update(cx, |task_store, cx| {
 6787                task_store.task_context_for_location(captured_task_variables, location, cx)
 6788            })
 6789        })
 6790    }
 6791
 6792    pub fn spawn_nearest_task(
 6793        &mut self,
 6794        action: &SpawnNearestTask,
 6795        window: &mut Window,
 6796        cx: &mut Context<Self>,
 6797    ) {
 6798        let Some((workspace, _)) = self.workspace.clone() else {
 6799            return;
 6800        };
 6801        let Some(project) = self.project.clone() else {
 6802            return;
 6803        };
 6804
 6805        // Try to find a closest, enclosing node using tree-sitter that has a
 6806        // task
 6807        let Some((buffer, buffer_row, tasks)) = self
 6808            .find_enclosing_node_task(cx)
 6809            // Or find the task that's closest in row-distance.
 6810            .or_else(|| self.find_closest_task(cx))
 6811        else {
 6812            return;
 6813        };
 6814
 6815        let reveal_strategy = action.reveal;
 6816        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6817        cx.spawn_in(window, async move |_, cx| {
 6818            let context = task_context.await?;
 6819            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6820
 6821            let resolved = resolved_task.resolved.as_mut()?;
 6822            resolved.reveal = reveal_strategy;
 6823
 6824            workspace
 6825                .update_in(cx, |workspace, window, cx| {
 6826                    workspace.schedule_resolved_task(
 6827                        task_source_kind,
 6828                        resolved_task,
 6829                        false,
 6830                        window,
 6831                        cx,
 6832                    );
 6833                })
 6834                .ok()
 6835        })
 6836        .detach();
 6837    }
 6838
 6839    fn find_closest_task(
 6840        &mut self,
 6841        cx: &mut Context<Self>,
 6842    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6843        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6844
 6845        let ((buffer_id, row), tasks) = self
 6846            .tasks
 6847            .iter()
 6848            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6849
 6850        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6851        let tasks = Arc::new(tasks.to_owned());
 6852        Some((buffer, *row, tasks))
 6853    }
 6854
 6855    fn find_enclosing_node_task(
 6856        &mut self,
 6857        cx: &mut Context<Self>,
 6858    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6859        let snapshot = self.buffer.read(cx).snapshot(cx);
 6860        let offset = self.selections.newest::<usize>(cx).head();
 6861        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6862        let buffer_id = excerpt.buffer().remote_id();
 6863
 6864        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6865        let mut cursor = layer.node().walk();
 6866
 6867        while cursor.goto_first_child_for_byte(offset).is_some() {
 6868            if cursor.node().end_byte() == offset {
 6869                cursor.goto_next_sibling();
 6870            }
 6871        }
 6872
 6873        // Ascend to the smallest ancestor that contains the range and has a task.
 6874        loop {
 6875            let node = cursor.node();
 6876            let node_range = node.byte_range();
 6877            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6878
 6879            // Check if this node contains our offset
 6880            if node_range.start <= offset && node_range.end >= offset {
 6881                // If it contains offset, check for task
 6882                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6883                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6884                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6885                }
 6886            }
 6887
 6888            if !cursor.goto_parent() {
 6889                break;
 6890            }
 6891        }
 6892        None
 6893    }
 6894
 6895    fn render_run_indicator(
 6896        &self,
 6897        _style: &EditorStyle,
 6898        is_active: bool,
 6899        row: DisplayRow,
 6900        breakpoint: Option<(Anchor, Breakpoint)>,
 6901        cx: &mut Context<Self>,
 6902    ) -> IconButton {
 6903        let color = Color::Muted;
 6904        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6905
 6906        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6907            .shape(ui::IconButtonShape::Square)
 6908            .icon_size(IconSize::XSmall)
 6909            .icon_color(color)
 6910            .toggle_state(is_active)
 6911            .on_click(cx.listener(move |editor, _e, window, cx| {
 6912                window.focus(&editor.focus_handle(cx));
 6913                editor.toggle_code_actions(
 6914                    &ToggleCodeActions {
 6915                        deployed_from_indicator: Some(row),
 6916                    },
 6917                    window,
 6918                    cx,
 6919                );
 6920            }))
 6921            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6922                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6923            }))
 6924    }
 6925
 6926    pub fn context_menu_visible(&self) -> bool {
 6927        !self.edit_prediction_preview_is_active()
 6928            && self
 6929                .context_menu
 6930                .borrow()
 6931                .as_ref()
 6932                .map_or(false, |menu| menu.visible())
 6933    }
 6934
 6935    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6936        self.context_menu
 6937            .borrow()
 6938            .as_ref()
 6939            .map(|menu| menu.origin())
 6940    }
 6941
 6942    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6943        self.context_menu_options = Some(options);
 6944    }
 6945
 6946    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6947    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6948
 6949    fn render_edit_prediction_popover(
 6950        &mut self,
 6951        text_bounds: &Bounds<Pixels>,
 6952        content_origin: gpui::Point<Pixels>,
 6953        editor_snapshot: &EditorSnapshot,
 6954        visible_row_range: Range<DisplayRow>,
 6955        scroll_top: f32,
 6956        scroll_bottom: f32,
 6957        line_layouts: &[LineWithInvisibles],
 6958        line_height: Pixels,
 6959        scroll_pixel_position: gpui::Point<Pixels>,
 6960        newest_selection_head: Option<DisplayPoint>,
 6961        editor_width: Pixels,
 6962        style: &EditorStyle,
 6963        window: &mut Window,
 6964        cx: &mut App,
 6965    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6966        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6967
 6968        if self.edit_prediction_visible_in_cursor_popover(true) {
 6969            return None;
 6970        }
 6971
 6972        match &active_inline_completion.completion {
 6973            InlineCompletion::Move { target, .. } => {
 6974                let target_display_point = target.to_display_point(editor_snapshot);
 6975
 6976                if self.edit_prediction_requires_modifier() {
 6977                    if !self.edit_prediction_preview_is_active() {
 6978                        return None;
 6979                    }
 6980
 6981                    self.render_edit_prediction_modifier_jump_popover(
 6982                        text_bounds,
 6983                        content_origin,
 6984                        visible_row_range,
 6985                        line_layouts,
 6986                        line_height,
 6987                        scroll_pixel_position,
 6988                        newest_selection_head,
 6989                        target_display_point,
 6990                        window,
 6991                        cx,
 6992                    )
 6993                } else {
 6994                    self.render_edit_prediction_eager_jump_popover(
 6995                        text_bounds,
 6996                        content_origin,
 6997                        editor_snapshot,
 6998                        visible_row_range,
 6999                        scroll_top,
 7000                        scroll_bottom,
 7001                        line_height,
 7002                        scroll_pixel_position,
 7003                        target_display_point,
 7004                        editor_width,
 7005                        window,
 7006                        cx,
 7007                    )
 7008                }
 7009            }
 7010            InlineCompletion::Edit {
 7011                display_mode: EditDisplayMode::Inline,
 7012                ..
 7013            } => None,
 7014            InlineCompletion::Edit {
 7015                display_mode: EditDisplayMode::TabAccept,
 7016                edits,
 7017                ..
 7018            } => {
 7019                let range = &edits.first()?.0;
 7020                let target_display_point = range.end.to_display_point(editor_snapshot);
 7021
 7022                self.render_edit_prediction_end_of_line_popover(
 7023                    "Accept",
 7024                    editor_snapshot,
 7025                    visible_row_range,
 7026                    target_display_point,
 7027                    line_height,
 7028                    scroll_pixel_position,
 7029                    content_origin,
 7030                    editor_width,
 7031                    window,
 7032                    cx,
 7033                )
 7034            }
 7035            InlineCompletion::Edit {
 7036                edits,
 7037                edit_preview,
 7038                display_mode: EditDisplayMode::DiffPopover,
 7039                snapshot,
 7040            } => self.render_edit_prediction_diff_popover(
 7041                text_bounds,
 7042                content_origin,
 7043                editor_snapshot,
 7044                visible_row_range,
 7045                line_layouts,
 7046                line_height,
 7047                scroll_pixel_position,
 7048                newest_selection_head,
 7049                editor_width,
 7050                style,
 7051                edits,
 7052                edit_preview,
 7053                snapshot,
 7054                window,
 7055                cx,
 7056            ),
 7057        }
 7058    }
 7059
 7060    fn render_edit_prediction_modifier_jump_popover(
 7061        &mut self,
 7062        text_bounds: &Bounds<Pixels>,
 7063        content_origin: gpui::Point<Pixels>,
 7064        visible_row_range: Range<DisplayRow>,
 7065        line_layouts: &[LineWithInvisibles],
 7066        line_height: Pixels,
 7067        scroll_pixel_position: gpui::Point<Pixels>,
 7068        newest_selection_head: Option<DisplayPoint>,
 7069        target_display_point: DisplayPoint,
 7070        window: &mut Window,
 7071        cx: &mut App,
 7072    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7073        let scrolled_content_origin =
 7074            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7075
 7076        const SCROLL_PADDING_Y: Pixels = px(12.);
 7077
 7078        if target_display_point.row() < visible_row_range.start {
 7079            return self.render_edit_prediction_scroll_popover(
 7080                |_| SCROLL_PADDING_Y,
 7081                IconName::ArrowUp,
 7082                visible_row_range,
 7083                line_layouts,
 7084                newest_selection_head,
 7085                scrolled_content_origin,
 7086                window,
 7087                cx,
 7088            );
 7089        } else if target_display_point.row() >= visible_row_range.end {
 7090            return self.render_edit_prediction_scroll_popover(
 7091                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7092                IconName::ArrowDown,
 7093                visible_row_range,
 7094                line_layouts,
 7095                newest_selection_head,
 7096                scrolled_content_origin,
 7097                window,
 7098                cx,
 7099            );
 7100        }
 7101
 7102        const POLE_WIDTH: Pixels = px(2.);
 7103
 7104        let line_layout =
 7105            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7106        let target_column = target_display_point.column() as usize;
 7107
 7108        let target_x = line_layout.x_for_index(target_column);
 7109        let target_y =
 7110            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7111
 7112        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7113
 7114        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7115        border_color.l += 0.001;
 7116
 7117        let mut element = v_flex()
 7118            .items_end()
 7119            .when(flag_on_right, |el| el.items_start())
 7120            .child(if flag_on_right {
 7121                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7122                    .rounded_bl(px(0.))
 7123                    .rounded_tl(px(0.))
 7124                    .border_l_2()
 7125                    .border_color(border_color)
 7126            } else {
 7127                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7128                    .rounded_br(px(0.))
 7129                    .rounded_tr(px(0.))
 7130                    .border_r_2()
 7131                    .border_color(border_color)
 7132            })
 7133            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7134            .into_any();
 7135
 7136        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7137
 7138        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7139            - point(
 7140                if flag_on_right {
 7141                    POLE_WIDTH
 7142                } else {
 7143                    size.width - POLE_WIDTH
 7144                },
 7145                size.height - line_height,
 7146            );
 7147
 7148        origin.x = origin.x.max(content_origin.x);
 7149
 7150        element.prepaint_at(origin, window, cx);
 7151
 7152        Some((element, origin))
 7153    }
 7154
 7155    fn render_edit_prediction_scroll_popover(
 7156        &mut self,
 7157        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7158        scroll_icon: IconName,
 7159        visible_row_range: Range<DisplayRow>,
 7160        line_layouts: &[LineWithInvisibles],
 7161        newest_selection_head: Option<DisplayPoint>,
 7162        scrolled_content_origin: gpui::Point<Pixels>,
 7163        window: &mut Window,
 7164        cx: &mut App,
 7165    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7166        let mut element = self
 7167            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7168            .into_any();
 7169
 7170        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7171
 7172        let cursor = newest_selection_head?;
 7173        let cursor_row_layout =
 7174            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7175        let cursor_column = cursor.column() as usize;
 7176
 7177        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7178
 7179        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7180
 7181        element.prepaint_at(origin, window, cx);
 7182        Some((element, origin))
 7183    }
 7184
 7185    fn render_edit_prediction_eager_jump_popover(
 7186        &mut self,
 7187        text_bounds: &Bounds<Pixels>,
 7188        content_origin: gpui::Point<Pixels>,
 7189        editor_snapshot: &EditorSnapshot,
 7190        visible_row_range: Range<DisplayRow>,
 7191        scroll_top: f32,
 7192        scroll_bottom: f32,
 7193        line_height: Pixels,
 7194        scroll_pixel_position: gpui::Point<Pixels>,
 7195        target_display_point: DisplayPoint,
 7196        editor_width: Pixels,
 7197        window: &mut Window,
 7198        cx: &mut App,
 7199    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7200        if target_display_point.row().as_f32() < scroll_top {
 7201            let mut element = self
 7202                .render_edit_prediction_line_popover(
 7203                    "Jump to Edit",
 7204                    Some(IconName::ArrowUp),
 7205                    window,
 7206                    cx,
 7207                )?
 7208                .into_any();
 7209
 7210            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7211            let offset = point(
 7212                (text_bounds.size.width - size.width) / 2.,
 7213                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7214            );
 7215
 7216            let origin = text_bounds.origin + offset;
 7217            element.prepaint_at(origin, window, cx);
 7218            Some((element, origin))
 7219        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7220            let mut element = self
 7221                .render_edit_prediction_line_popover(
 7222                    "Jump to Edit",
 7223                    Some(IconName::ArrowDown),
 7224                    window,
 7225                    cx,
 7226                )?
 7227                .into_any();
 7228
 7229            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7230            let offset = point(
 7231                (text_bounds.size.width - size.width) / 2.,
 7232                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7233            );
 7234
 7235            let origin = text_bounds.origin + offset;
 7236            element.prepaint_at(origin, window, cx);
 7237            Some((element, origin))
 7238        } else {
 7239            self.render_edit_prediction_end_of_line_popover(
 7240                "Jump to Edit",
 7241                editor_snapshot,
 7242                visible_row_range,
 7243                target_display_point,
 7244                line_height,
 7245                scroll_pixel_position,
 7246                content_origin,
 7247                editor_width,
 7248                window,
 7249                cx,
 7250            )
 7251        }
 7252    }
 7253
 7254    fn render_edit_prediction_end_of_line_popover(
 7255        self: &mut Editor,
 7256        label: &'static str,
 7257        editor_snapshot: &EditorSnapshot,
 7258        visible_row_range: Range<DisplayRow>,
 7259        target_display_point: DisplayPoint,
 7260        line_height: Pixels,
 7261        scroll_pixel_position: gpui::Point<Pixels>,
 7262        content_origin: gpui::Point<Pixels>,
 7263        editor_width: Pixels,
 7264        window: &mut Window,
 7265        cx: &mut App,
 7266    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7267        let target_line_end = DisplayPoint::new(
 7268            target_display_point.row(),
 7269            editor_snapshot.line_len(target_display_point.row()),
 7270        );
 7271
 7272        let mut element = self
 7273            .render_edit_prediction_line_popover(label, None, window, cx)?
 7274            .into_any();
 7275
 7276        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7277
 7278        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7279
 7280        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7281        let mut origin = start_point
 7282            + line_origin
 7283            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7284        origin.x = origin.x.max(content_origin.x);
 7285
 7286        let max_x = content_origin.x + editor_width - size.width;
 7287
 7288        if origin.x > max_x {
 7289            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7290
 7291            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7292                origin.y += offset;
 7293                IconName::ArrowUp
 7294            } else {
 7295                origin.y -= offset;
 7296                IconName::ArrowDown
 7297            };
 7298
 7299            element = self
 7300                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7301                .into_any();
 7302
 7303            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7304
 7305            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7306        }
 7307
 7308        element.prepaint_at(origin, window, cx);
 7309        Some((element, origin))
 7310    }
 7311
 7312    fn render_edit_prediction_diff_popover(
 7313        self: &Editor,
 7314        text_bounds: &Bounds<Pixels>,
 7315        content_origin: gpui::Point<Pixels>,
 7316        editor_snapshot: &EditorSnapshot,
 7317        visible_row_range: Range<DisplayRow>,
 7318        line_layouts: &[LineWithInvisibles],
 7319        line_height: Pixels,
 7320        scroll_pixel_position: gpui::Point<Pixels>,
 7321        newest_selection_head: Option<DisplayPoint>,
 7322        editor_width: Pixels,
 7323        style: &EditorStyle,
 7324        edits: &Vec<(Range<Anchor>, String)>,
 7325        edit_preview: &Option<language::EditPreview>,
 7326        snapshot: &language::BufferSnapshot,
 7327        window: &mut Window,
 7328        cx: &mut App,
 7329    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7330        let edit_start = edits
 7331            .first()
 7332            .unwrap()
 7333            .0
 7334            .start
 7335            .to_display_point(editor_snapshot);
 7336        let edit_end = edits
 7337            .last()
 7338            .unwrap()
 7339            .0
 7340            .end
 7341            .to_display_point(editor_snapshot);
 7342
 7343        let is_visible = visible_row_range.contains(&edit_start.row())
 7344            || visible_row_range.contains(&edit_end.row());
 7345        if !is_visible {
 7346            return None;
 7347        }
 7348
 7349        let highlighted_edits =
 7350            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7351
 7352        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7353        let line_count = highlighted_edits.text.lines().count();
 7354
 7355        const BORDER_WIDTH: Pixels = px(1.);
 7356
 7357        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7358        let has_keybind = keybind.is_some();
 7359
 7360        let mut element = h_flex()
 7361            .items_start()
 7362            .child(
 7363                h_flex()
 7364                    .bg(cx.theme().colors().editor_background)
 7365                    .border(BORDER_WIDTH)
 7366                    .shadow_sm()
 7367                    .border_color(cx.theme().colors().border)
 7368                    .rounded_l_lg()
 7369                    .when(line_count > 1, |el| el.rounded_br_lg())
 7370                    .pr_1()
 7371                    .child(styled_text),
 7372            )
 7373            .child(
 7374                h_flex()
 7375                    .h(line_height + BORDER_WIDTH * 2.)
 7376                    .px_1p5()
 7377                    .gap_1()
 7378                    // Workaround: For some reason, there's a gap if we don't do this
 7379                    .ml(-BORDER_WIDTH)
 7380                    .shadow(smallvec![gpui::BoxShadow {
 7381                        color: gpui::black().opacity(0.05),
 7382                        offset: point(px(1.), px(1.)),
 7383                        blur_radius: px(2.),
 7384                        spread_radius: px(0.),
 7385                    }])
 7386                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7387                    .border(BORDER_WIDTH)
 7388                    .border_color(cx.theme().colors().border)
 7389                    .rounded_r_lg()
 7390                    .id("edit_prediction_diff_popover_keybind")
 7391                    .when(!has_keybind, |el| {
 7392                        let status_colors = cx.theme().status();
 7393
 7394                        el.bg(status_colors.error_background)
 7395                            .border_color(status_colors.error.opacity(0.6))
 7396                            .child(Icon::new(IconName::Info).color(Color::Error))
 7397                            .cursor_default()
 7398                            .hoverable_tooltip(move |_window, cx| {
 7399                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7400                            })
 7401                    })
 7402                    .children(keybind),
 7403            )
 7404            .into_any();
 7405
 7406        let longest_row =
 7407            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7408        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7409            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7410        } else {
 7411            layout_line(
 7412                longest_row,
 7413                editor_snapshot,
 7414                style,
 7415                editor_width,
 7416                |_| false,
 7417                window,
 7418                cx,
 7419            )
 7420            .width
 7421        };
 7422
 7423        let viewport_bounds =
 7424            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7425                right: -EditorElement::SCROLLBAR_WIDTH,
 7426                ..Default::default()
 7427            });
 7428
 7429        let x_after_longest =
 7430            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7431                - scroll_pixel_position.x;
 7432
 7433        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7434
 7435        // Fully visible if it can be displayed within the window (allow overlapping other
 7436        // panes). However, this is only allowed if the popover starts within text_bounds.
 7437        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7438            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7439
 7440        let mut origin = if can_position_to_the_right {
 7441            point(
 7442                x_after_longest,
 7443                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7444                    - scroll_pixel_position.y,
 7445            )
 7446        } else {
 7447            let cursor_row = newest_selection_head.map(|head| head.row());
 7448            let above_edit = edit_start
 7449                .row()
 7450                .0
 7451                .checked_sub(line_count as u32)
 7452                .map(DisplayRow);
 7453            let below_edit = Some(edit_end.row() + 1);
 7454            let above_cursor =
 7455                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7456            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7457
 7458            // Place the edit popover adjacent to the edit if there is a location
 7459            // available that is onscreen and does not obscure the cursor. Otherwise,
 7460            // place it adjacent to the cursor.
 7461            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7462                .into_iter()
 7463                .flatten()
 7464                .find(|&start_row| {
 7465                    let end_row = start_row + line_count as u32;
 7466                    visible_row_range.contains(&start_row)
 7467                        && visible_row_range.contains(&end_row)
 7468                        && cursor_row.map_or(true, |cursor_row| {
 7469                            !((start_row..end_row).contains(&cursor_row))
 7470                        })
 7471                })?;
 7472
 7473            content_origin
 7474                + point(
 7475                    -scroll_pixel_position.x,
 7476                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7477                )
 7478        };
 7479
 7480        origin.x -= BORDER_WIDTH;
 7481
 7482        window.defer_draw(element, origin, 1);
 7483
 7484        // Do not return an element, since it will already be drawn due to defer_draw.
 7485        None
 7486    }
 7487
 7488    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7489        px(30.)
 7490    }
 7491
 7492    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7493        if self.read_only(cx) {
 7494            cx.theme().players().read_only()
 7495        } else {
 7496            self.style.as_ref().unwrap().local_player
 7497        }
 7498    }
 7499
 7500    fn render_edit_prediction_accept_keybind(
 7501        &self,
 7502        window: &mut Window,
 7503        cx: &App,
 7504    ) -> Option<AnyElement> {
 7505        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7506        let accept_keystroke = accept_binding.keystroke()?;
 7507
 7508        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7509
 7510        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7511            Color::Accent
 7512        } else {
 7513            Color::Muted
 7514        };
 7515
 7516        h_flex()
 7517            .px_0p5()
 7518            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7519            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7520            .text_size(TextSize::XSmall.rems(cx))
 7521            .child(h_flex().children(ui::render_modifiers(
 7522                &accept_keystroke.modifiers,
 7523                PlatformStyle::platform(),
 7524                Some(modifiers_color),
 7525                Some(IconSize::XSmall.rems().into()),
 7526                true,
 7527            )))
 7528            .when(is_platform_style_mac, |parent| {
 7529                parent.child(accept_keystroke.key.clone())
 7530            })
 7531            .when(!is_platform_style_mac, |parent| {
 7532                parent.child(
 7533                    Key::new(
 7534                        util::capitalize(&accept_keystroke.key),
 7535                        Some(Color::Default),
 7536                    )
 7537                    .size(Some(IconSize::XSmall.rems().into())),
 7538                )
 7539            })
 7540            .into_any()
 7541            .into()
 7542    }
 7543
 7544    fn render_edit_prediction_line_popover(
 7545        &self,
 7546        label: impl Into<SharedString>,
 7547        icon: Option<IconName>,
 7548        window: &mut Window,
 7549        cx: &App,
 7550    ) -> Option<Stateful<Div>> {
 7551        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7552
 7553        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7554        let has_keybind = keybind.is_some();
 7555
 7556        let result = h_flex()
 7557            .id("ep-line-popover")
 7558            .py_0p5()
 7559            .pl_1()
 7560            .pr(padding_right)
 7561            .gap_1()
 7562            .rounded_md()
 7563            .border_1()
 7564            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7565            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7566            .shadow_sm()
 7567            .when(!has_keybind, |el| {
 7568                let status_colors = cx.theme().status();
 7569
 7570                el.bg(status_colors.error_background)
 7571                    .border_color(status_colors.error.opacity(0.6))
 7572                    .pl_2()
 7573                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7574                    .cursor_default()
 7575                    .hoverable_tooltip(move |_window, cx| {
 7576                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7577                    })
 7578            })
 7579            .children(keybind)
 7580            .child(
 7581                Label::new(label)
 7582                    .size(LabelSize::Small)
 7583                    .when(!has_keybind, |el| {
 7584                        el.color(cx.theme().status().error.into()).strikethrough()
 7585                    }),
 7586            )
 7587            .when(!has_keybind, |el| {
 7588                el.child(
 7589                    h_flex().ml_1().child(
 7590                        Icon::new(IconName::Info)
 7591                            .size(IconSize::Small)
 7592                            .color(cx.theme().status().error.into()),
 7593                    ),
 7594                )
 7595            })
 7596            .when_some(icon, |element, icon| {
 7597                element.child(
 7598                    div()
 7599                        .mt(px(1.5))
 7600                        .child(Icon::new(icon).size(IconSize::Small)),
 7601                )
 7602            });
 7603
 7604        Some(result)
 7605    }
 7606
 7607    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7608        let accent_color = cx.theme().colors().text_accent;
 7609        let editor_bg_color = cx.theme().colors().editor_background;
 7610        editor_bg_color.blend(accent_color.opacity(0.1))
 7611    }
 7612
 7613    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7614        let accent_color = cx.theme().colors().text_accent;
 7615        let editor_bg_color = cx.theme().colors().editor_background;
 7616        editor_bg_color.blend(accent_color.opacity(0.6))
 7617    }
 7618
 7619    fn render_edit_prediction_cursor_popover(
 7620        &self,
 7621        min_width: Pixels,
 7622        max_width: Pixels,
 7623        cursor_point: Point,
 7624        style: &EditorStyle,
 7625        accept_keystroke: Option<&gpui::Keystroke>,
 7626        _window: &Window,
 7627        cx: &mut Context<Editor>,
 7628    ) -> Option<AnyElement> {
 7629        let provider = self.edit_prediction_provider.as_ref()?;
 7630
 7631        if provider.provider.needs_terms_acceptance(cx) {
 7632            return Some(
 7633                h_flex()
 7634                    .min_w(min_width)
 7635                    .flex_1()
 7636                    .px_2()
 7637                    .py_1()
 7638                    .gap_3()
 7639                    .elevation_2(cx)
 7640                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7641                    .id("accept-terms")
 7642                    .cursor_pointer()
 7643                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7644                    .on_click(cx.listener(|this, _event, window, cx| {
 7645                        cx.stop_propagation();
 7646                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7647                        window.dispatch_action(
 7648                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7649                            cx,
 7650                        );
 7651                    }))
 7652                    .child(
 7653                        h_flex()
 7654                            .flex_1()
 7655                            .gap_2()
 7656                            .child(Icon::new(IconName::ZedPredict))
 7657                            .child(Label::new("Accept Terms of Service"))
 7658                            .child(div().w_full())
 7659                            .child(
 7660                                Icon::new(IconName::ArrowUpRight)
 7661                                    .color(Color::Muted)
 7662                                    .size(IconSize::Small),
 7663                            )
 7664                            .into_any_element(),
 7665                    )
 7666                    .into_any(),
 7667            );
 7668        }
 7669
 7670        let is_refreshing = provider.provider.is_refreshing(cx);
 7671
 7672        fn pending_completion_container() -> Div {
 7673            h_flex()
 7674                .h_full()
 7675                .flex_1()
 7676                .gap_2()
 7677                .child(Icon::new(IconName::ZedPredict))
 7678        }
 7679
 7680        let completion = match &self.active_inline_completion {
 7681            Some(prediction) => {
 7682                if !self.has_visible_completions_menu() {
 7683                    const RADIUS: Pixels = px(6.);
 7684                    const BORDER_WIDTH: Pixels = px(1.);
 7685
 7686                    return Some(
 7687                        h_flex()
 7688                            .elevation_2(cx)
 7689                            .border(BORDER_WIDTH)
 7690                            .border_color(cx.theme().colors().border)
 7691                            .when(accept_keystroke.is_none(), |el| {
 7692                                el.border_color(cx.theme().status().error)
 7693                            })
 7694                            .rounded(RADIUS)
 7695                            .rounded_tl(px(0.))
 7696                            .overflow_hidden()
 7697                            .child(div().px_1p5().child(match &prediction.completion {
 7698                                InlineCompletion::Move { target, snapshot } => {
 7699                                    use text::ToPoint as _;
 7700                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7701                                    {
 7702                                        Icon::new(IconName::ZedPredictDown)
 7703                                    } else {
 7704                                        Icon::new(IconName::ZedPredictUp)
 7705                                    }
 7706                                }
 7707                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7708                            }))
 7709                            .child(
 7710                                h_flex()
 7711                                    .gap_1()
 7712                                    .py_1()
 7713                                    .px_2()
 7714                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7715                                    .border_l_1()
 7716                                    .border_color(cx.theme().colors().border)
 7717                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7718                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7719                                        el.child(
 7720                                            Label::new("Hold")
 7721                                                .size(LabelSize::Small)
 7722                                                .when(accept_keystroke.is_none(), |el| {
 7723                                                    el.strikethrough()
 7724                                                })
 7725                                                .line_height_style(LineHeightStyle::UiLabel),
 7726                                        )
 7727                                    })
 7728                                    .id("edit_prediction_cursor_popover_keybind")
 7729                                    .when(accept_keystroke.is_none(), |el| {
 7730                                        let status_colors = cx.theme().status();
 7731
 7732                                        el.bg(status_colors.error_background)
 7733                                            .border_color(status_colors.error.opacity(0.6))
 7734                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7735                                            .cursor_default()
 7736                                            .hoverable_tooltip(move |_window, cx| {
 7737                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7738                                                    .into()
 7739                                            })
 7740                                    })
 7741                                    .when_some(
 7742                                        accept_keystroke.as_ref(),
 7743                                        |el, accept_keystroke| {
 7744                                            el.child(h_flex().children(ui::render_modifiers(
 7745                                                &accept_keystroke.modifiers,
 7746                                                PlatformStyle::platform(),
 7747                                                Some(Color::Default),
 7748                                                Some(IconSize::XSmall.rems().into()),
 7749                                                false,
 7750                                            )))
 7751                                        },
 7752                                    ),
 7753                            )
 7754                            .into_any(),
 7755                    );
 7756                }
 7757
 7758                self.render_edit_prediction_cursor_popover_preview(
 7759                    prediction,
 7760                    cursor_point,
 7761                    style,
 7762                    cx,
 7763                )?
 7764            }
 7765
 7766            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7767                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7768                    stale_completion,
 7769                    cursor_point,
 7770                    style,
 7771                    cx,
 7772                )?,
 7773
 7774                None => {
 7775                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7776                }
 7777            },
 7778
 7779            None => pending_completion_container().child(Label::new("No Prediction")),
 7780        };
 7781
 7782        let completion = if is_refreshing {
 7783            completion
 7784                .with_animation(
 7785                    "loading-completion",
 7786                    Animation::new(Duration::from_secs(2))
 7787                        .repeat()
 7788                        .with_easing(pulsating_between(0.4, 0.8)),
 7789                    |label, delta| label.opacity(delta),
 7790                )
 7791                .into_any_element()
 7792        } else {
 7793            completion.into_any_element()
 7794        };
 7795
 7796        let has_completion = self.active_inline_completion.is_some();
 7797
 7798        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7799        Some(
 7800            h_flex()
 7801                .min_w(min_width)
 7802                .max_w(max_width)
 7803                .flex_1()
 7804                .elevation_2(cx)
 7805                .border_color(cx.theme().colors().border)
 7806                .child(
 7807                    div()
 7808                        .flex_1()
 7809                        .py_1()
 7810                        .px_2()
 7811                        .overflow_hidden()
 7812                        .child(completion),
 7813                )
 7814                .when_some(accept_keystroke, |el, accept_keystroke| {
 7815                    if !accept_keystroke.modifiers.modified() {
 7816                        return el;
 7817                    }
 7818
 7819                    el.child(
 7820                        h_flex()
 7821                            .h_full()
 7822                            .border_l_1()
 7823                            .rounded_r_lg()
 7824                            .border_color(cx.theme().colors().border)
 7825                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7826                            .gap_1()
 7827                            .py_1()
 7828                            .px_2()
 7829                            .child(
 7830                                h_flex()
 7831                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7832                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7833                                    .child(h_flex().children(ui::render_modifiers(
 7834                                        &accept_keystroke.modifiers,
 7835                                        PlatformStyle::platform(),
 7836                                        Some(if !has_completion {
 7837                                            Color::Muted
 7838                                        } else {
 7839                                            Color::Default
 7840                                        }),
 7841                                        None,
 7842                                        false,
 7843                                    ))),
 7844                            )
 7845                            .child(Label::new("Preview").into_any_element())
 7846                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7847                    )
 7848                })
 7849                .into_any(),
 7850        )
 7851    }
 7852
 7853    fn render_edit_prediction_cursor_popover_preview(
 7854        &self,
 7855        completion: &InlineCompletionState,
 7856        cursor_point: Point,
 7857        style: &EditorStyle,
 7858        cx: &mut Context<Editor>,
 7859    ) -> Option<Div> {
 7860        use text::ToPoint as _;
 7861
 7862        fn render_relative_row_jump(
 7863            prefix: impl Into<String>,
 7864            current_row: u32,
 7865            target_row: u32,
 7866        ) -> Div {
 7867            let (row_diff, arrow) = if target_row < current_row {
 7868                (current_row - target_row, IconName::ArrowUp)
 7869            } else {
 7870                (target_row - current_row, IconName::ArrowDown)
 7871            };
 7872
 7873            h_flex()
 7874                .child(
 7875                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7876                        .color(Color::Muted)
 7877                        .size(LabelSize::Small),
 7878                )
 7879                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7880        }
 7881
 7882        match &completion.completion {
 7883            InlineCompletion::Move {
 7884                target, snapshot, ..
 7885            } => Some(
 7886                h_flex()
 7887                    .px_2()
 7888                    .gap_2()
 7889                    .flex_1()
 7890                    .child(
 7891                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7892                            Icon::new(IconName::ZedPredictDown)
 7893                        } else {
 7894                            Icon::new(IconName::ZedPredictUp)
 7895                        },
 7896                    )
 7897                    .child(Label::new("Jump to Edit")),
 7898            ),
 7899
 7900            InlineCompletion::Edit {
 7901                edits,
 7902                edit_preview,
 7903                snapshot,
 7904                display_mode: _,
 7905            } => {
 7906                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7907
 7908                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7909                    &snapshot,
 7910                    &edits,
 7911                    edit_preview.as_ref()?,
 7912                    true,
 7913                    cx,
 7914                )
 7915                .first_line_preview();
 7916
 7917                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7918                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7919
 7920                let preview = h_flex()
 7921                    .gap_1()
 7922                    .min_w_16()
 7923                    .child(styled_text)
 7924                    .when(has_more_lines, |parent| parent.child(""));
 7925
 7926                let left = if first_edit_row != cursor_point.row {
 7927                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7928                        .into_any_element()
 7929                } else {
 7930                    Icon::new(IconName::ZedPredict).into_any_element()
 7931                };
 7932
 7933                Some(
 7934                    h_flex()
 7935                        .h_full()
 7936                        .flex_1()
 7937                        .gap_2()
 7938                        .pr_1()
 7939                        .overflow_x_hidden()
 7940                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7941                        .child(left)
 7942                        .child(preview),
 7943                )
 7944            }
 7945        }
 7946    }
 7947
 7948    fn render_context_menu(
 7949        &self,
 7950        style: &EditorStyle,
 7951        max_height_in_lines: u32,
 7952        window: &mut Window,
 7953        cx: &mut Context<Editor>,
 7954    ) -> Option<AnyElement> {
 7955        let menu = self.context_menu.borrow();
 7956        let menu = menu.as_ref()?;
 7957        if !menu.visible() {
 7958            return None;
 7959        };
 7960        Some(menu.render(style, max_height_in_lines, window, cx))
 7961    }
 7962
 7963    fn render_context_menu_aside(
 7964        &mut self,
 7965        max_size: Size<Pixels>,
 7966        window: &mut Window,
 7967        cx: &mut Context<Editor>,
 7968    ) -> Option<AnyElement> {
 7969        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7970            if menu.visible() {
 7971                menu.render_aside(self, max_size, window, cx)
 7972            } else {
 7973                None
 7974            }
 7975        })
 7976    }
 7977
 7978    fn hide_context_menu(
 7979        &mut self,
 7980        window: &mut Window,
 7981        cx: &mut Context<Self>,
 7982    ) -> Option<CodeContextMenu> {
 7983        cx.notify();
 7984        self.completion_tasks.clear();
 7985        let context_menu = self.context_menu.borrow_mut().take();
 7986        self.stale_inline_completion_in_menu.take();
 7987        self.update_visible_inline_completion(window, cx);
 7988        context_menu
 7989    }
 7990
 7991    fn show_snippet_choices(
 7992        &mut self,
 7993        choices: &Vec<String>,
 7994        selection: Range<Anchor>,
 7995        cx: &mut Context<Self>,
 7996    ) {
 7997        if selection.start.buffer_id.is_none() {
 7998            return;
 7999        }
 8000        let buffer_id = selection.start.buffer_id.unwrap();
 8001        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8002        let id = post_inc(&mut self.next_completion_id);
 8003
 8004        if let Some(buffer) = buffer {
 8005            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8006                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 8007            ));
 8008        }
 8009    }
 8010
 8011    pub fn insert_snippet(
 8012        &mut self,
 8013        insertion_ranges: &[Range<usize>],
 8014        snippet: Snippet,
 8015        window: &mut Window,
 8016        cx: &mut Context<Self>,
 8017    ) -> Result<()> {
 8018        struct Tabstop<T> {
 8019            is_end_tabstop: bool,
 8020            ranges: Vec<Range<T>>,
 8021            choices: Option<Vec<String>>,
 8022        }
 8023
 8024        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8025            let snippet_text: Arc<str> = snippet.text.clone().into();
 8026            let edits = insertion_ranges
 8027                .iter()
 8028                .cloned()
 8029                .map(|range| (range, snippet_text.clone()));
 8030            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8031
 8032            let snapshot = &*buffer.read(cx);
 8033            let snippet = &snippet;
 8034            snippet
 8035                .tabstops
 8036                .iter()
 8037                .map(|tabstop| {
 8038                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8039                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8040                    });
 8041                    let mut tabstop_ranges = tabstop
 8042                        .ranges
 8043                        .iter()
 8044                        .flat_map(|tabstop_range| {
 8045                            let mut delta = 0_isize;
 8046                            insertion_ranges.iter().map(move |insertion_range| {
 8047                                let insertion_start = insertion_range.start as isize + delta;
 8048                                delta +=
 8049                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8050
 8051                                let start = ((insertion_start + tabstop_range.start) as usize)
 8052                                    .min(snapshot.len());
 8053                                let end = ((insertion_start + tabstop_range.end) as usize)
 8054                                    .min(snapshot.len());
 8055                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8056                            })
 8057                        })
 8058                        .collect::<Vec<_>>();
 8059                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8060
 8061                    Tabstop {
 8062                        is_end_tabstop,
 8063                        ranges: tabstop_ranges,
 8064                        choices: tabstop.choices.clone(),
 8065                    }
 8066                })
 8067                .collect::<Vec<_>>()
 8068        });
 8069        if let Some(tabstop) = tabstops.first() {
 8070            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8071                s.select_ranges(tabstop.ranges.iter().cloned());
 8072            });
 8073
 8074            if let Some(choices) = &tabstop.choices {
 8075                if let Some(selection) = tabstop.ranges.first() {
 8076                    self.show_snippet_choices(choices, selection.clone(), cx)
 8077                }
 8078            }
 8079
 8080            // If we're already at the last tabstop and it's at the end of the snippet,
 8081            // we're done, we don't need to keep the state around.
 8082            if !tabstop.is_end_tabstop {
 8083                let choices = tabstops
 8084                    .iter()
 8085                    .map(|tabstop| tabstop.choices.clone())
 8086                    .collect();
 8087
 8088                let ranges = tabstops
 8089                    .into_iter()
 8090                    .map(|tabstop| tabstop.ranges)
 8091                    .collect::<Vec<_>>();
 8092
 8093                self.snippet_stack.push(SnippetState {
 8094                    active_index: 0,
 8095                    ranges,
 8096                    choices,
 8097                });
 8098            }
 8099
 8100            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8101            if self.autoclose_regions.is_empty() {
 8102                let snapshot = self.buffer.read(cx).snapshot(cx);
 8103                for selection in &mut self.selections.all::<Point>(cx) {
 8104                    let selection_head = selection.head();
 8105                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8106                        continue;
 8107                    };
 8108
 8109                    let mut bracket_pair = None;
 8110                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8111                    let prev_chars = snapshot
 8112                        .reversed_chars_at(selection_head)
 8113                        .collect::<String>();
 8114                    for (pair, enabled) in scope.brackets() {
 8115                        if enabled
 8116                            && pair.close
 8117                            && prev_chars.starts_with(pair.start.as_str())
 8118                            && next_chars.starts_with(pair.end.as_str())
 8119                        {
 8120                            bracket_pair = Some(pair.clone());
 8121                            break;
 8122                        }
 8123                    }
 8124                    if let Some(pair) = bracket_pair {
 8125                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8126                        let autoclose_enabled =
 8127                            self.use_autoclose && snapshot_settings.use_autoclose;
 8128                        if autoclose_enabled {
 8129                            let start = snapshot.anchor_after(selection_head);
 8130                            let end = snapshot.anchor_after(selection_head);
 8131                            self.autoclose_regions.push(AutocloseRegion {
 8132                                selection_id: selection.id,
 8133                                range: start..end,
 8134                                pair,
 8135                            });
 8136                        }
 8137                    }
 8138                }
 8139            }
 8140        }
 8141        Ok(())
 8142    }
 8143
 8144    pub fn move_to_next_snippet_tabstop(
 8145        &mut self,
 8146        window: &mut Window,
 8147        cx: &mut Context<Self>,
 8148    ) -> bool {
 8149        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8150    }
 8151
 8152    pub fn move_to_prev_snippet_tabstop(
 8153        &mut self,
 8154        window: &mut Window,
 8155        cx: &mut Context<Self>,
 8156    ) -> bool {
 8157        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8158    }
 8159
 8160    pub fn move_to_snippet_tabstop(
 8161        &mut self,
 8162        bias: Bias,
 8163        window: &mut Window,
 8164        cx: &mut Context<Self>,
 8165    ) -> bool {
 8166        if let Some(mut snippet) = self.snippet_stack.pop() {
 8167            match bias {
 8168                Bias::Left => {
 8169                    if snippet.active_index > 0 {
 8170                        snippet.active_index -= 1;
 8171                    } else {
 8172                        self.snippet_stack.push(snippet);
 8173                        return false;
 8174                    }
 8175                }
 8176                Bias::Right => {
 8177                    if snippet.active_index + 1 < snippet.ranges.len() {
 8178                        snippet.active_index += 1;
 8179                    } else {
 8180                        self.snippet_stack.push(snippet);
 8181                        return false;
 8182                    }
 8183                }
 8184            }
 8185            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8186                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8187                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8188                });
 8189
 8190                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8191                    if let Some(selection) = current_ranges.first() {
 8192                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8193                    }
 8194                }
 8195
 8196                // If snippet state is not at the last tabstop, push it back on the stack
 8197                if snippet.active_index + 1 < snippet.ranges.len() {
 8198                    self.snippet_stack.push(snippet);
 8199                }
 8200                return true;
 8201            }
 8202        }
 8203
 8204        false
 8205    }
 8206
 8207    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8208        self.transact(window, cx, |this, window, cx| {
 8209            this.select_all(&SelectAll, window, cx);
 8210            this.insert("", window, cx);
 8211        });
 8212    }
 8213
 8214    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8215        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8216        self.transact(window, cx, |this, window, cx| {
 8217            this.select_autoclose_pair(window, cx);
 8218            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8219            if !this.linked_edit_ranges.is_empty() {
 8220                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8221                let snapshot = this.buffer.read(cx).snapshot(cx);
 8222
 8223                for selection in selections.iter() {
 8224                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8225                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8226                    if selection_start.buffer_id != selection_end.buffer_id {
 8227                        continue;
 8228                    }
 8229                    if let Some(ranges) =
 8230                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8231                    {
 8232                        for (buffer, entries) in ranges {
 8233                            linked_ranges.entry(buffer).or_default().extend(entries);
 8234                        }
 8235                    }
 8236                }
 8237            }
 8238
 8239            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8240            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8241            for selection in &mut selections {
 8242                if selection.is_empty() {
 8243                    let old_head = selection.head();
 8244                    let mut new_head =
 8245                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8246                            .to_point(&display_map);
 8247                    if let Some((buffer, line_buffer_range)) = display_map
 8248                        .buffer_snapshot
 8249                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8250                    {
 8251                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8252                        let indent_len = match indent_size.kind {
 8253                            IndentKind::Space => {
 8254                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8255                            }
 8256                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8257                        };
 8258                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8259                            let indent_len = indent_len.get();
 8260                            new_head = cmp::min(
 8261                                new_head,
 8262                                MultiBufferPoint::new(
 8263                                    old_head.row,
 8264                                    ((old_head.column - 1) / indent_len) * indent_len,
 8265                                ),
 8266                            );
 8267                        }
 8268                    }
 8269
 8270                    selection.set_head(new_head, SelectionGoal::None);
 8271                }
 8272            }
 8273
 8274            this.signature_help_state.set_backspace_pressed(true);
 8275            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8276                s.select(selections)
 8277            });
 8278            this.insert("", window, cx);
 8279            let empty_str: Arc<str> = Arc::from("");
 8280            for (buffer, edits) in linked_ranges {
 8281                let snapshot = buffer.read(cx).snapshot();
 8282                use text::ToPoint as TP;
 8283
 8284                let edits = edits
 8285                    .into_iter()
 8286                    .map(|range| {
 8287                        let end_point = TP::to_point(&range.end, &snapshot);
 8288                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8289
 8290                        if end_point == start_point {
 8291                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8292                                .saturating_sub(1);
 8293                            start_point =
 8294                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8295                        };
 8296
 8297                        (start_point..end_point, empty_str.clone())
 8298                    })
 8299                    .sorted_by_key(|(range, _)| range.start)
 8300                    .collect::<Vec<_>>();
 8301                buffer.update(cx, |this, cx| {
 8302                    this.edit(edits, None, cx);
 8303                })
 8304            }
 8305            this.refresh_inline_completion(true, false, window, cx);
 8306            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8307        });
 8308    }
 8309
 8310    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8311        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8312        self.transact(window, cx, |this, window, cx| {
 8313            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8314                s.move_with(|map, selection| {
 8315                    if selection.is_empty() {
 8316                        let cursor = movement::right(map, selection.head());
 8317                        selection.end = cursor;
 8318                        selection.reversed = true;
 8319                        selection.goal = SelectionGoal::None;
 8320                    }
 8321                })
 8322            });
 8323            this.insert("", window, cx);
 8324            this.refresh_inline_completion(true, false, window, cx);
 8325        });
 8326    }
 8327
 8328    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8329        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8330        if self.move_to_prev_snippet_tabstop(window, cx) {
 8331            return;
 8332        }
 8333        self.outdent(&Outdent, window, cx);
 8334    }
 8335
 8336    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8337        if self.move_to_next_snippet_tabstop(window, cx) {
 8338            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8339            return;
 8340        }
 8341        if self.read_only(cx) {
 8342            return;
 8343        }
 8344        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8345        let mut selections = self.selections.all_adjusted(cx);
 8346        let buffer = self.buffer.read(cx);
 8347        let snapshot = buffer.snapshot(cx);
 8348        let rows_iter = selections.iter().map(|s| s.head().row);
 8349        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8350
 8351        let mut edits = Vec::new();
 8352        let mut prev_edited_row = 0;
 8353        let mut row_delta = 0;
 8354        for selection in &mut selections {
 8355            if selection.start.row != prev_edited_row {
 8356                row_delta = 0;
 8357            }
 8358            prev_edited_row = selection.end.row;
 8359
 8360            // If the selection is non-empty, then increase the indentation of the selected lines.
 8361            if !selection.is_empty() {
 8362                row_delta =
 8363                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8364                continue;
 8365            }
 8366
 8367            // If the selection is empty and the cursor is in the leading whitespace before the
 8368            // suggested indentation, then auto-indent the line.
 8369            let cursor = selection.head();
 8370            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8371            if let Some(suggested_indent) =
 8372                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8373            {
 8374                if cursor.column < suggested_indent.len
 8375                    && cursor.column <= current_indent.len
 8376                    && current_indent.len <= suggested_indent.len
 8377                {
 8378                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8379                    selection.end = selection.start;
 8380                    if row_delta == 0 {
 8381                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8382                            cursor.row,
 8383                            current_indent,
 8384                            suggested_indent,
 8385                        ));
 8386                        row_delta = suggested_indent.len - current_indent.len;
 8387                    }
 8388                    continue;
 8389                }
 8390            }
 8391
 8392            // Otherwise, insert a hard or soft tab.
 8393            let settings = buffer.language_settings_at(cursor, cx);
 8394            let tab_size = if settings.hard_tabs {
 8395                IndentSize::tab()
 8396            } else {
 8397                let tab_size = settings.tab_size.get();
 8398                let indent_remainder = snapshot
 8399                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8400                    .flat_map(str::chars)
 8401                    .fold(row_delta % tab_size, |counter: u32, c| {
 8402                        if c == '\t' {
 8403                            0
 8404                        } else {
 8405                            (counter + 1) % tab_size
 8406                        }
 8407                    });
 8408
 8409                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8410                IndentSize::spaces(chars_to_next_tab_stop)
 8411            };
 8412            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8413            selection.end = selection.start;
 8414            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8415            row_delta += tab_size.len;
 8416        }
 8417
 8418        self.transact(window, cx, |this, window, cx| {
 8419            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8420            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8421                s.select(selections)
 8422            });
 8423            this.refresh_inline_completion(true, false, window, cx);
 8424        });
 8425    }
 8426
 8427    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8428        if self.read_only(cx) {
 8429            return;
 8430        }
 8431        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8432        let mut selections = self.selections.all::<Point>(cx);
 8433        let mut prev_edited_row = 0;
 8434        let mut row_delta = 0;
 8435        let mut edits = Vec::new();
 8436        let buffer = self.buffer.read(cx);
 8437        let snapshot = buffer.snapshot(cx);
 8438        for selection in &mut selections {
 8439            if selection.start.row != prev_edited_row {
 8440                row_delta = 0;
 8441            }
 8442            prev_edited_row = selection.end.row;
 8443
 8444            row_delta =
 8445                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8446        }
 8447
 8448        self.transact(window, cx, |this, window, cx| {
 8449            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8450            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8451                s.select(selections)
 8452            });
 8453        });
 8454    }
 8455
 8456    fn indent_selection(
 8457        buffer: &MultiBuffer,
 8458        snapshot: &MultiBufferSnapshot,
 8459        selection: &mut Selection<Point>,
 8460        edits: &mut Vec<(Range<Point>, String)>,
 8461        delta_for_start_row: u32,
 8462        cx: &App,
 8463    ) -> u32 {
 8464        let settings = buffer.language_settings_at(selection.start, cx);
 8465        let tab_size = settings.tab_size.get();
 8466        let indent_kind = if settings.hard_tabs {
 8467            IndentKind::Tab
 8468        } else {
 8469            IndentKind::Space
 8470        };
 8471        let mut start_row = selection.start.row;
 8472        let mut end_row = selection.end.row + 1;
 8473
 8474        // If a selection ends at the beginning of a line, don't indent
 8475        // that last line.
 8476        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8477            end_row -= 1;
 8478        }
 8479
 8480        // Avoid re-indenting a row that has already been indented by a
 8481        // previous selection, but still update this selection's column
 8482        // to reflect that indentation.
 8483        if delta_for_start_row > 0 {
 8484            start_row += 1;
 8485            selection.start.column += delta_for_start_row;
 8486            if selection.end.row == selection.start.row {
 8487                selection.end.column += delta_for_start_row;
 8488            }
 8489        }
 8490
 8491        let mut delta_for_end_row = 0;
 8492        let has_multiple_rows = start_row + 1 != end_row;
 8493        for row in start_row..end_row {
 8494            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8495            let indent_delta = match (current_indent.kind, indent_kind) {
 8496                (IndentKind::Space, IndentKind::Space) => {
 8497                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8498                    IndentSize::spaces(columns_to_next_tab_stop)
 8499                }
 8500                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8501                (_, IndentKind::Tab) => IndentSize::tab(),
 8502            };
 8503
 8504            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8505                0
 8506            } else {
 8507                selection.start.column
 8508            };
 8509            let row_start = Point::new(row, start);
 8510            edits.push((
 8511                row_start..row_start,
 8512                indent_delta.chars().collect::<String>(),
 8513            ));
 8514
 8515            // Update this selection's endpoints to reflect the indentation.
 8516            if row == selection.start.row {
 8517                selection.start.column += indent_delta.len;
 8518            }
 8519            if row == selection.end.row {
 8520                selection.end.column += indent_delta.len;
 8521                delta_for_end_row = indent_delta.len;
 8522            }
 8523        }
 8524
 8525        if selection.start.row == selection.end.row {
 8526            delta_for_start_row + delta_for_end_row
 8527        } else {
 8528            delta_for_end_row
 8529        }
 8530    }
 8531
 8532    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8533        if self.read_only(cx) {
 8534            return;
 8535        }
 8536        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8537        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8538        let selections = self.selections.all::<Point>(cx);
 8539        let mut deletion_ranges = Vec::new();
 8540        let mut last_outdent = None;
 8541        {
 8542            let buffer = self.buffer.read(cx);
 8543            let snapshot = buffer.snapshot(cx);
 8544            for selection in &selections {
 8545                let settings = buffer.language_settings_at(selection.start, cx);
 8546                let tab_size = settings.tab_size.get();
 8547                let mut rows = selection.spanned_rows(false, &display_map);
 8548
 8549                // Avoid re-outdenting a row that has already been outdented by a
 8550                // previous selection.
 8551                if let Some(last_row) = last_outdent {
 8552                    if last_row == rows.start {
 8553                        rows.start = rows.start.next_row();
 8554                    }
 8555                }
 8556                let has_multiple_rows = rows.len() > 1;
 8557                for row in rows.iter_rows() {
 8558                    let indent_size = snapshot.indent_size_for_line(row);
 8559                    if indent_size.len > 0 {
 8560                        let deletion_len = match indent_size.kind {
 8561                            IndentKind::Space => {
 8562                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8563                                if columns_to_prev_tab_stop == 0 {
 8564                                    tab_size
 8565                                } else {
 8566                                    columns_to_prev_tab_stop
 8567                                }
 8568                            }
 8569                            IndentKind::Tab => 1,
 8570                        };
 8571                        let start = if has_multiple_rows
 8572                            || deletion_len > selection.start.column
 8573                            || indent_size.len < selection.start.column
 8574                        {
 8575                            0
 8576                        } else {
 8577                            selection.start.column - deletion_len
 8578                        };
 8579                        deletion_ranges.push(
 8580                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8581                        );
 8582                        last_outdent = Some(row);
 8583                    }
 8584                }
 8585            }
 8586        }
 8587
 8588        self.transact(window, cx, |this, window, cx| {
 8589            this.buffer.update(cx, |buffer, cx| {
 8590                let empty_str: Arc<str> = Arc::default();
 8591                buffer.edit(
 8592                    deletion_ranges
 8593                        .into_iter()
 8594                        .map(|range| (range, empty_str.clone())),
 8595                    None,
 8596                    cx,
 8597                );
 8598            });
 8599            let selections = this.selections.all::<usize>(cx);
 8600            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8601                s.select(selections)
 8602            });
 8603        });
 8604    }
 8605
 8606    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8607        if self.read_only(cx) {
 8608            return;
 8609        }
 8610        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8611        let selections = self
 8612            .selections
 8613            .all::<usize>(cx)
 8614            .into_iter()
 8615            .map(|s| s.range());
 8616
 8617        self.transact(window, cx, |this, window, cx| {
 8618            this.buffer.update(cx, |buffer, cx| {
 8619                buffer.autoindent_ranges(selections, cx);
 8620            });
 8621            let selections = this.selections.all::<usize>(cx);
 8622            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8623                s.select(selections)
 8624            });
 8625        });
 8626    }
 8627
 8628    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8629        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8630        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8631        let selections = self.selections.all::<Point>(cx);
 8632
 8633        let mut new_cursors = Vec::new();
 8634        let mut edit_ranges = Vec::new();
 8635        let mut selections = selections.iter().peekable();
 8636        while let Some(selection) = selections.next() {
 8637            let mut rows = selection.spanned_rows(false, &display_map);
 8638            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8639
 8640            // Accumulate contiguous regions of rows that we want to delete.
 8641            while let Some(next_selection) = selections.peek() {
 8642                let next_rows = next_selection.spanned_rows(false, &display_map);
 8643                if next_rows.start <= rows.end {
 8644                    rows.end = next_rows.end;
 8645                    selections.next().unwrap();
 8646                } else {
 8647                    break;
 8648                }
 8649            }
 8650
 8651            let buffer = &display_map.buffer_snapshot;
 8652            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8653            let edit_end;
 8654            let cursor_buffer_row;
 8655            if buffer.max_point().row >= rows.end.0 {
 8656                // If there's a line after the range, delete the \n from the end of the row range
 8657                // and position the cursor on the next line.
 8658                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8659                cursor_buffer_row = rows.end;
 8660            } else {
 8661                // If there isn't a line after the range, delete the \n from the line before the
 8662                // start of the row range and position the cursor there.
 8663                edit_start = edit_start.saturating_sub(1);
 8664                edit_end = buffer.len();
 8665                cursor_buffer_row = rows.start.previous_row();
 8666            }
 8667
 8668            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8669            *cursor.column_mut() =
 8670                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8671
 8672            new_cursors.push((
 8673                selection.id,
 8674                buffer.anchor_after(cursor.to_point(&display_map)),
 8675            ));
 8676            edit_ranges.push(edit_start..edit_end);
 8677        }
 8678
 8679        self.transact(window, cx, |this, window, cx| {
 8680            let buffer = this.buffer.update(cx, |buffer, cx| {
 8681                let empty_str: Arc<str> = Arc::default();
 8682                buffer.edit(
 8683                    edit_ranges
 8684                        .into_iter()
 8685                        .map(|range| (range, empty_str.clone())),
 8686                    None,
 8687                    cx,
 8688                );
 8689                buffer.snapshot(cx)
 8690            });
 8691            let new_selections = new_cursors
 8692                .into_iter()
 8693                .map(|(id, cursor)| {
 8694                    let cursor = cursor.to_point(&buffer);
 8695                    Selection {
 8696                        id,
 8697                        start: cursor,
 8698                        end: cursor,
 8699                        reversed: false,
 8700                        goal: SelectionGoal::None,
 8701                    }
 8702                })
 8703                .collect();
 8704
 8705            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8706                s.select(new_selections);
 8707            });
 8708        });
 8709    }
 8710
 8711    pub fn join_lines_impl(
 8712        &mut self,
 8713        insert_whitespace: bool,
 8714        window: &mut Window,
 8715        cx: &mut Context<Self>,
 8716    ) {
 8717        if self.read_only(cx) {
 8718            return;
 8719        }
 8720        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8721        for selection in self.selections.all::<Point>(cx) {
 8722            let start = MultiBufferRow(selection.start.row);
 8723            // Treat single line selections as if they include the next line. Otherwise this action
 8724            // would do nothing for single line selections individual cursors.
 8725            let end = if selection.start.row == selection.end.row {
 8726                MultiBufferRow(selection.start.row + 1)
 8727            } else {
 8728                MultiBufferRow(selection.end.row)
 8729            };
 8730
 8731            if let Some(last_row_range) = row_ranges.last_mut() {
 8732                if start <= last_row_range.end {
 8733                    last_row_range.end = end;
 8734                    continue;
 8735                }
 8736            }
 8737            row_ranges.push(start..end);
 8738        }
 8739
 8740        let snapshot = self.buffer.read(cx).snapshot(cx);
 8741        let mut cursor_positions = Vec::new();
 8742        for row_range in &row_ranges {
 8743            let anchor = snapshot.anchor_before(Point::new(
 8744                row_range.end.previous_row().0,
 8745                snapshot.line_len(row_range.end.previous_row()),
 8746            ));
 8747            cursor_positions.push(anchor..anchor);
 8748        }
 8749
 8750        self.transact(window, cx, |this, window, cx| {
 8751            for row_range in row_ranges.into_iter().rev() {
 8752                for row in row_range.iter_rows().rev() {
 8753                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8754                    let next_line_row = row.next_row();
 8755                    let indent = snapshot.indent_size_for_line(next_line_row);
 8756                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8757
 8758                    let replace =
 8759                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8760                            " "
 8761                        } else {
 8762                            ""
 8763                        };
 8764
 8765                    this.buffer.update(cx, |buffer, cx| {
 8766                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8767                    });
 8768                }
 8769            }
 8770
 8771            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8772                s.select_anchor_ranges(cursor_positions)
 8773            });
 8774        });
 8775    }
 8776
 8777    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8778        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8779        self.join_lines_impl(true, window, cx);
 8780    }
 8781
 8782    pub fn sort_lines_case_sensitive(
 8783        &mut self,
 8784        _: &SortLinesCaseSensitive,
 8785        window: &mut Window,
 8786        cx: &mut Context<Self>,
 8787    ) {
 8788        self.manipulate_lines(window, cx, |lines| lines.sort())
 8789    }
 8790
 8791    pub fn sort_lines_case_insensitive(
 8792        &mut self,
 8793        _: &SortLinesCaseInsensitive,
 8794        window: &mut Window,
 8795        cx: &mut Context<Self>,
 8796    ) {
 8797        self.manipulate_lines(window, cx, |lines| {
 8798            lines.sort_by_key(|line| line.to_lowercase())
 8799        })
 8800    }
 8801
 8802    pub fn unique_lines_case_insensitive(
 8803        &mut self,
 8804        _: &UniqueLinesCaseInsensitive,
 8805        window: &mut Window,
 8806        cx: &mut Context<Self>,
 8807    ) {
 8808        self.manipulate_lines(window, cx, |lines| {
 8809            let mut seen = HashSet::default();
 8810            lines.retain(|line| seen.insert(line.to_lowercase()));
 8811        })
 8812    }
 8813
 8814    pub fn unique_lines_case_sensitive(
 8815        &mut self,
 8816        _: &UniqueLinesCaseSensitive,
 8817        window: &mut Window,
 8818        cx: &mut Context<Self>,
 8819    ) {
 8820        self.manipulate_lines(window, cx, |lines| {
 8821            let mut seen = HashSet::default();
 8822            lines.retain(|line| seen.insert(*line));
 8823        })
 8824    }
 8825
 8826    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8827        let Some(project) = self.project.clone() else {
 8828            return;
 8829        };
 8830        self.reload(project, window, cx)
 8831            .detach_and_notify_err(window, cx);
 8832    }
 8833
 8834    pub fn restore_file(
 8835        &mut self,
 8836        _: &::git::RestoreFile,
 8837        window: &mut Window,
 8838        cx: &mut Context<Self>,
 8839    ) {
 8840        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8841        let mut buffer_ids = HashSet::default();
 8842        let snapshot = self.buffer().read(cx).snapshot(cx);
 8843        for selection in self.selections.all::<usize>(cx) {
 8844            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8845        }
 8846
 8847        let buffer = self.buffer().read(cx);
 8848        let ranges = buffer_ids
 8849            .into_iter()
 8850            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8851            .collect::<Vec<_>>();
 8852
 8853        self.restore_hunks_in_ranges(ranges, window, cx);
 8854    }
 8855
 8856    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8857        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8858        let selections = self
 8859            .selections
 8860            .all(cx)
 8861            .into_iter()
 8862            .map(|s| s.range())
 8863            .collect();
 8864        self.restore_hunks_in_ranges(selections, window, cx);
 8865    }
 8866
 8867    pub fn restore_hunks_in_ranges(
 8868        &mut self,
 8869        ranges: Vec<Range<Point>>,
 8870        window: &mut Window,
 8871        cx: &mut Context<Editor>,
 8872    ) {
 8873        let mut revert_changes = HashMap::default();
 8874        let chunk_by = self
 8875            .snapshot(window, cx)
 8876            .hunks_for_ranges(ranges)
 8877            .into_iter()
 8878            .chunk_by(|hunk| hunk.buffer_id);
 8879        for (buffer_id, hunks) in &chunk_by {
 8880            let hunks = hunks.collect::<Vec<_>>();
 8881            for hunk in &hunks {
 8882                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8883            }
 8884            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8885        }
 8886        drop(chunk_by);
 8887        if !revert_changes.is_empty() {
 8888            self.transact(window, cx, |editor, window, cx| {
 8889                editor.restore(revert_changes, window, cx);
 8890            });
 8891        }
 8892    }
 8893
 8894    pub fn open_active_item_in_terminal(
 8895        &mut self,
 8896        _: &OpenInTerminal,
 8897        window: &mut Window,
 8898        cx: &mut Context<Self>,
 8899    ) {
 8900        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8901            let project_path = buffer.read(cx).project_path(cx)?;
 8902            let project = self.project.as_ref()?.read(cx);
 8903            let entry = project.entry_for_path(&project_path, cx)?;
 8904            let parent = match &entry.canonical_path {
 8905                Some(canonical_path) => canonical_path.to_path_buf(),
 8906                None => project.absolute_path(&project_path, cx)?,
 8907            }
 8908            .parent()?
 8909            .to_path_buf();
 8910            Some(parent)
 8911        }) {
 8912            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8913        }
 8914    }
 8915
 8916    fn set_breakpoint_context_menu(
 8917        &mut self,
 8918        display_row: DisplayRow,
 8919        position: Option<Anchor>,
 8920        clicked_point: gpui::Point<Pixels>,
 8921        window: &mut Window,
 8922        cx: &mut Context<Self>,
 8923    ) {
 8924        if !cx.has_flag::<Debugger>() {
 8925            return;
 8926        }
 8927        let source = self
 8928            .buffer
 8929            .read(cx)
 8930            .snapshot(cx)
 8931            .anchor_before(Point::new(display_row.0, 0u32));
 8932
 8933        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8934
 8935        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8936            self,
 8937            source,
 8938            clicked_point,
 8939            context_menu,
 8940            window,
 8941            cx,
 8942        );
 8943    }
 8944
 8945    fn add_edit_breakpoint_block(
 8946        &mut self,
 8947        anchor: Anchor,
 8948        breakpoint: &Breakpoint,
 8949        edit_action: BreakpointPromptEditAction,
 8950        window: &mut Window,
 8951        cx: &mut Context<Self>,
 8952    ) {
 8953        let weak_editor = cx.weak_entity();
 8954        let bp_prompt = cx.new(|cx| {
 8955            BreakpointPromptEditor::new(
 8956                weak_editor,
 8957                anchor,
 8958                breakpoint.clone(),
 8959                edit_action,
 8960                window,
 8961                cx,
 8962            )
 8963        });
 8964
 8965        let height = bp_prompt.update(cx, |this, cx| {
 8966            this.prompt
 8967                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8968        });
 8969        let cloned_prompt = bp_prompt.clone();
 8970        let blocks = vec![BlockProperties {
 8971            style: BlockStyle::Sticky,
 8972            placement: BlockPlacement::Above(anchor),
 8973            height: Some(height),
 8974            render: Arc::new(move |cx| {
 8975                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8976                cloned_prompt.clone().into_any_element()
 8977            }),
 8978            priority: 0,
 8979        }];
 8980
 8981        let focus_handle = bp_prompt.focus_handle(cx);
 8982        window.focus(&focus_handle);
 8983
 8984        let block_ids = self.insert_blocks(blocks, None, cx);
 8985        bp_prompt.update(cx, |prompt, _| {
 8986            prompt.add_block_ids(block_ids);
 8987        });
 8988    }
 8989
 8990    pub(crate) fn breakpoint_at_row(
 8991        &self,
 8992        row: u32,
 8993        window: &mut Window,
 8994        cx: &mut Context<Self>,
 8995    ) -> Option<(Anchor, Breakpoint)> {
 8996        let snapshot = self.snapshot(window, cx);
 8997        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8998
 8999        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9000    }
 9001
 9002    pub(crate) fn breakpoint_at_anchor(
 9003        &self,
 9004        breakpoint_position: Anchor,
 9005        snapshot: &EditorSnapshot,
 9006        cx: &mut Context<Self>,
 9007    ) -> Option<(Anchor, Breakpoint)> {
 9008        let project = self.project.clone()?;
 9009
 9010        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9011            snapshot
 9012                .buffer_snapshot
 9013                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9014        })?;
 9015
 9016        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9017        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9018        let buffer_snapshot = buffer.read(cx).snapshot();
 9019
 9020        let row = buffer_snapshot
 9021            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9022            .row;
 9023
 9024        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9025        let anchor_end = snapshot
 9026            .buffer_snapshot
 9027            .anchor_after(Point::new(row, line_len));
 9028
 9029        let bp = self
 9030            .breakpoint_store
 9031            .as_ref()?
 9032            .read_with(cx, |breakpoint_store, cx| {
 9033                breakpoint_store
 9034                    .breakpoints(
 9035                        &buffer,
 9036                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9037                        &buffer_snapshot,
 9038                        cx,
 9039                    )
 9040                    .next()
 9041                    .and_then(|(anchor, bp)| {
 9042                        let breakpoint_row = buffer_snapshot
 9043                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9044                            .row;
 9045
 9046                        if breakpoint_row == row {
 9047                            snapshot
 9048                                .buffer_snapshot
 9049                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9050                                .map(|anchor| (anchor, bp.clone()))
 9051                        } else {
 9052                            None
 9053                        }
 9054                    })
 9055            });
 9056        bp
 9057    }
 9058
 9059    pub fn edit_log_breakpoint(
 9060        &mut self,
 9061        _: &EditLogBreakpoint,
 9062        window: &mut Window,
 9063        cx: &mut Context<Self>,
 9064    ) {
 9065        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9066            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9067                message: None,
 9068                state: BreakpointState::Enabled,
 9069                condition: None,
 9070                hit_condition: None,
 9071            });
 9072
 9073            self.add_edit_breakpoint_block(
 9074                anchor,
 9075                &breakpoint,
 9076                BreakpointPromptEditAction::Log,
 9077                window,
 9078                cx,
 9079            );
 9080        }
 9081    }
 9082
 9083    fn breakpoints_at_cursors(
 9084        &self,
 9085        window: &mut Window,
 9086        cx: &mut Context<Self>,
 9087    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9088        let snapshot = self.snapshot(window, cx);
 9089        let cursors = self
 9090            .selections
 9091            .disjoint_anchors()
 9092            .into_iter()
 9093            .map(|selection| {
 9094                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9095
 9096                let breakpoint_position = self
 9097                    .breakpoint_at_row(cursor_position.row, window, cx)
 9098                    .map(|bp| bp.0)
 9099                    .unwrap_or_else(|| {
 9100                        snapshot
 9101                            .display_snapshot
 9102                            .buffer_snapshot
 9103                            .anchor_after(Point::new(cursor_position.row, 0))
 9104                    });
 9105
 9106                let breakpoint = self
 9107                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9108                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9109
 9110                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9111            })
 9112            // 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.
 9113            .collect::<HashMap<Anchor, _>>();
 9114
 9115        cursors.into_iter().collect()
 9116    }
 9117
 9118    pub fn enable_breakpoint(
 9119        &mut self,
 9120        _: &crate::actions::EnableBreakpoint,
 9121        window: &mut Window,
 9122        cx: &mut Context<Self>,
 9123    ) {
 9124        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9125            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9126                continue;
 9127            };
 9128            self.edit_breakpoint_at_anchor(
 9129                anchor,
 9130                breakpoint,
 9131                BreakpointEditAction::InvertState,
 9132                cx,
 9133            );
 9134        }
 9135    }
 9136
 9137    pub fn disable_breakpoint(
 9138        &mut self,
 9139        _: &crate::actions::DisableBreakpoint,
 9140        window: &mut Window,
 9141        cx: &mut Context<Self>,
 9142    ) {
 9143        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9144            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9145                continue;
 9146            };
 9147            self.edit_breakpoint_at_anchor(
 9148                anchor,
 9149                breakpoint,
 9150                BreakpointEditAction::InvertState,
 9151                cx,
 9152            );
 9153        }
 9154    }
 9155
 9156    pub fn toggle_breakpoint(
 9157        &mut self,
 9158        _: &crate::actions::ToggleBreakpoint,
 9159        window: &mut Window,
 9160        cx: &mut Context<Self>,
 9161    ) {
 9162        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9163            if let Some(breakpoint) = breakpoint {
 9164                self.edit_breakpoint_at_anchor(
 9165                    anchor,
 9166                    breakpoint,
 9167                    BreakpointEditAction::Toggle,
 9168                    cx,
 9169                );
 9170            } else {
 9171                self.edit_breakpoint_at_anchor(
 9172                    anchor,
 9173                    Breakpoint::new_standard(),
 9174                    BreakpointEditAction::Toggle,
 9175                    cx,
 9176                );
 9177            }
 9178        }
 9179    }
 9180
 9181    pub fn edit_breakpoint_at_anchor(
 9182        &mut self,
 9183        breakpoint_position: Anchor,
 9184        breakpoint: Breakpoint,
 9185        edit_action: BreakpointEditAction,
 9186        cx: &mut Context<Self>,
 9187    ) {
 9188        let Some(breakpoint_store) = &self.breakpoint_store else {
 9189            return;
 9190        };
 9191
 9192        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9193            if breakpoint_position == Anchor::min() {
 9194                self.buffer()
 9195                    .read(cx)
 9196                    .excerpt_buffer_ids()
 9197                    .into_iter()
 9198                    .next()
 9199            } else {
 9200                None
 9201            }
 9202        }) else {
 9203            return;
 9204        };
 9205
 9206        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9207            return;
 9208        };
 9209
 9210        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9211            breakpoint_store.toggle_breakpoint(
 9212                buffer,
 9213                (breakpoint_position.text_anchor, breakpoint),
 9214                edit_action,
 9215                cx,
 9216            );
 9217        });
 9218
 9219        cx.notify();
 9220    }
 9221
 9222    #[cfg(any(test, feature = "test-support"))]
 9223    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9224        self.breakpoint_store.clone()
 9225    }
 9226
 9227    pub fn prepare_restore_change(
 9228        &self,
 9229        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9230        hunk: &MultiBufferDiffHunk,
 9231        cx: &mut App,
 9232    ) -> Option<()> {
 9233        if hunk.is_created_file() {
 9234            return None;
 9235        }
 9236        let buffer = self.buffer.read(cx);
 9237        let diff = buffer.diff_for(hunk.buffer_id)?;
 9238        let buffer = buffer.buffer(hunk.buffer_id)?;
 9239        let buffer = buffer.read(cx);
 9240        let original_text = diff
 9241            .read(cx)
 9242            .base_text()
 9243            .as_rope()
 9244            .slice(hunk.diff_base_byte_range.clone());
 9245        let buffer_snapshot = buffer.snapshot();
 9246        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9247        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9248            probe
 9249                .0
 9250                .start
 9251                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9252                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9253        }) {
 9254            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9255            Some(())
 9256        } else {
 9257            None
 9258        }
 9259    }
 9260
 9261    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9262        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9263    }
 9264
 9265    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9266        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9267    }
 9268
 9269    fn manipulate_lines<Fn>(
 9270        &mut self,
 9271        window: &mut Window,
 9272        cx: &mut Context<Self>,
 9273        mut callback: Fn,
 9274    ) where
 9275        Fn: FnMut(&mut Vec<&str>),
 9276    {
 9277        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9278
 9279        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9280        let buffer = self.buffer.read(cx).snapshot(cx);
 9281
 9282        let mut edits = Vec::new();
 9283
 9284        let selections = self.selections.all::<Point>(cx);
 9285        let mut selections = selections.iter().peekable();
 9286        let mut contiguous_row_selections = Vec::new();
 9287        let mut new_selections = Vec::new();
 9288        let mut added_lines = 0;
 9289        let mut removed_lines = 0;
 9290
 9291        while let Some(selection) = selections.next() {
 9292            let (start_row, end_row) = consume_contiguous_rows(
 9293                &mut contiguous_row_selections,
 9294                selection,
 9295                &display_map,
 9296                &mut selections,
 9297            );
 9298
 9299            let start_point = Point::new(start_row.0, 0);
 9300            let end_point = Point::new(
 9301                end_row.previous_row().0,
 9302                buffer.line_len(end_row.previous_row()),
 9303            );
 9304            let text = buffer
 9305                .text_for_range(start_point..end_point)
 9306                .collect::<String>();
 9307
 9308            let mut lines = text.split('\n').collect_vec();
 9309
 9310            let lines_before = lines.len();
 9311            callback(&mut lines);
 9312            let lines_after = lines.len();
 9313
 9314            edits.push((start_point..end_point, lines.join("\n")));
 9315
 9316            // Selections must change based on added and removed line count
 9317            let start_row =
 9318                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9319            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9320            new_selections.push(Selection {
 9321                id: selection.id,
 9322                start: start_row,
 9323                end: end_row,
 9324                goal: SelectionGoal::None,
 9325                reversed: selection.reversed,
 9326            });
 9327
 9328            if lines_after > lines_before {
 9329                added_lines += lines_after - lines_before;
 9330            } else if lines_before > lines_after {
 9331                removed_lines += lines_before - lines_after;
 9332            }
 9333        }
 9334
 9335        self.transact(window, cx, |this, window, cx| {
 9336            let buffer = this.buffer.update(cx, |buffer, cx| {
 9337                buffer.edit(edits, None, cx);
 9338                buffer.snapshot(cx)
 9339            });
 9340
 9341            // Recalculate offsets on newly edited buffer
 9342            let new_selections = new_selections
 9343                .iter()
 9344                .map(|s| {
 9345                    let start_point = Point::new(s.start.0, 0);
 9346                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9347                    Selection {
 9348                        id: s.id,
 9349                        start: buffer.point_to_offset(start_point),
 9350                        end: buffer.point_to_offset(end_point),
 9351                        goal: s.goal,
 9352                        reversed: s.reversed,
 9353                    }
 9354                })
 9355                .collect();
 9356
 9357            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9358                s.select(new_selections);
 9359            });
 9360
 9361            this.request_autoscroll(Autoscroll::fit(), cx);
 9362        });
 9363    }
 9364
 9365    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9366        self.manipulate_text(window, cx, |text| {
 9367            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9368            if has_upper_case_characters {
 9369                text.to_lowercase()
 9370            } else {
 9371                text.to_uppercase()
 9372            }
 9373        })
 9374    }
 9375
 9376    pub fn convert_to_upper_case(
 9377        &mut self,
 9378        _: &ConvertToUpperCase,
 9379        window: &mut Window,
 9380        cx: &mut Context<Self>,
 9381    ) {
 9382        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9383    }
 9384
 9385    pub fn convert_to_lower_case(
 9386        &mut self,
 9387        _: &ConvertToLowerCase,
 9388        window: &mut Window,
 9389        cx: &mut Context<Self>,
 9390    ) {
 9391        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9392    }
 9393
 9394    pub fn convert_to_title_case(
 9395        &mut self,
 9396        _: &ConvertToTitleCase,
 9397        window: &mut Window,
 9398        cx: &mut Context<Self>,
 9399    ) {
 9400        self.manipulate_text(window, cx, |text| {
 9401            text.split('\n')
 9402                .map(|line| line.to_case(Case::Title))
 9403                .join("\n")
 9404        })
 9405    }
 9406
 9407    pub fn convert_to_snake_case(
 9408        &mut self,
 9409        _: &ConvertToSnakeCase,
 9410        window: &mut Window,
 9411        cx: &mut Context<Self>,
 9412    ) {
 9413        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9414    }
 9415
 9416    pub fn convert_to_kebab_case(
 9417        &mut self,
 9418        _: &ConvertToKebabCase,
 9419        window: &mut Window,
 9420        cx: &mut Context<Self>,
 9421    ) {
 9422        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9423    }
 9424
 9425    pub fn convert_to_upper_camel_case(
 9426        &mut self,
 9427        _: &ConvertToUpperCamelCase,
 9428        window: &mut Window,
 9429        cx: &mut Context<Self>,
 9430    ) {
 9431        self.manipulate_text(window, cx, |text| {
 9432            text.split('\n')
 9433                .map(|line| line.to_case(Case::UpperCamel))
 9434                .join("\n")
 9435        })
 9436    }
 9437
 9438    pub fn convert_to_lower_camel_case(
 9439        &mut self,
 9440        _: &ConvertToLowerCamelCase,
 9441        window: &mut Window,
 9442        cx: &mut Context<Self>,
 9443    ) {
 9444        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9445    }
 9446
 9447    pub fn convert_to_opposite_case(
 9448        &mut self,
 9449        _: &ConvertToOppositeCase,
 9450        window: &mut Window,
 9451        cx: &mut Context<Self>,
 9452    ) {
 9453        self.manipulate_text(window, cx, |text| {
 9454            text.chars()
 9455                .fold(String::with_capacity(text.len()), |mut t, c| {
 9456                    if c.is_uppercase() {
 9457                        t.extend(c.to_lowercase());
 9458                    } else {
 9459                        t.extend(c.to_uppercase());
 9460                    }
 9461                    t
 9462                })
 9463        })
 9464    }
 9465
 9466    pub fn convert_to_rot13(
 9467        &mut self,
 9468        _: &ConvertToRot13,
 9469        window: &mut Window,
 9470        cx: &mut Context<Self>,
 9471    ) {
 9472        self.manipulate_text(window, cx, |text| {
 9473            text.chars()
 9474                .map(|c| match c {
 9475                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9476                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9477                    _ => c,
 9478                })
 9479                .collect()
 9480        })
 9481    }
 9482
 9483    pub fn convert_to_rot47(
 9484        &mut self,
 9485        _: &ConvertToRot47,
 9486        window: &mut Window,
 9487        cx: &mut Context<Self>,
 9488    ) {
 9489        self.manipulate_text(window, cx, |text| {
 9490            text.chars()
 9491                .map(|c| {
 9492                    let code_point = c as u32;
 9493                    if code_point >= 33 && code_point <= 126 {
 9494                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9495                    }
 9496                    c
 9497                })
 9498                .collect()
 9499        })
 9500    }
 9501
 9502    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9503    where
 9504        Fn: FnMut(&str) -> String,
 9505    {
 9506        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9507        let buffer = self.buffer.read(cx).snapshot(cx);
 9508
 9509        let mut new_selections = Vec::new();
 9510        let mut edits = Vec::new();
 9511        let mut selection_adjustment = 0i32;
 9512
 9513        for selection in self.selections.all::<usize>(cx) {
 9514            let selection_is_empty = selection.is_empty();
 9515
 9516            let (start, end) = if selection_is_empty {
 9517                let word_range = movement::surrounding_word(
 9518                    &display_map,
 9519                    selection.start.to_display_point(&display_map),
 9520                );
 9521                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9522                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9523                (start, end)
 9524            } else {
 9525                (selection.start, selection.end)
 9526            };
 9527
 9528            let text = buffer.text_for_range(start..end).collect::<String>();
 9529            let old_length = text.len() as i32;
 9530            let text = callback(&text);
 9531
 9532            new_selections.push(Selection {
 9533                start: (start as i32 - selection_adjustment) as usize,
 9534                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9535                goal: SelectionGoal::None,
 9536                ..selection
 9537            });
 9538
 9539            selection_adjustment += old_length - text.len() as i32;
 9540
 9541            edits.push((start..end, text));
 9542        }
 9543
 9544        self.transact(window, cx, |this, window, cx| {
 9545            this.buffer.update(cx, |buffer, cx| {
 9546                buffer.edit(edits, None, cx);
 9547            });
 9548
 9549            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9550                s.select(new_selections);
 9551            });
 9552
 9553            this.request_autoscroll(Autoscroll::fit(), cx);
 9554        });
 9555    }
 9556
 9557    pub fn duplicate(
 9558        &mut self,
 9559        upwards: bool,
 9560        whole_lines: bool,
 9561        window: &mut Window,
 9562        cx: &mut Context<Self>,
 9563    ) {
 9564        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9565
 9566        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9567        let buffer = &display_map.buffer_snapshot;
 9568        let selections = self.selections.all::<Point>(cx);
 9569
 9570        let mut edits = Vec::new();
 9571        let mut selections_iter = selections.iter().peekable();
 9572        while let Some(selection) = selections_iter.next() {
 9573            let mut rows = selection.spanned_rows(false, &display_map);
 9574            // duplicate line-wise
 9575            if whole_lines || selection.start == selection.end {
 9576                // Avoid duplicating the same lines twice.
 9577                while let Some(next_selection) = selections_iter.peek() {
 9578                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9579                    if next_rows.start < rows.end {
 9580                        rows.end = next_rows.end;
 9581                        selections_iter.next().unwrap();
 9582                    } else {
 9583                        break;
 9584                    }
 9585                }
 9586
 9587                // Copy the text from the selected row region and splice it either at the start
 9588                // or end of the region.
 9589                let start = Point::new(rows.start.0, 0);
 9590                let end = Point::new(
 9591                    rows.end.previous_row().0,
 9592                    buffer.line_len(rows.end.previous_row()),
 9593                );
 9594                let text = buffer
 9595                    .text_for_range(start..end)
 9596                    .chain(Some("\n"))
 9597                    .collect::<String>();
 9598                let insert_location = if upwards {
 9599                    Point::new(rows.end.0, 0)
 9600                } else {
 9601                    start
 9602                };
 9603                edits.push((insert_location..insert_location, text));
 9604            } else {
 9605                // duplicate character-wise
 9606                let start = selection.start;
 9607                let end = selection.end;
 9608                let text = buffer.text_for_range(start..end).collect::<String>();
 9609                edits.push((selection.end..selection.end, text));
 9610            }
 9611        }
 9612
 9613        self.transact(window, cx, |this, _, cx| {
 9614            this.buffer.update(cx, |buffer, cx| {
 9615                buffer.edit(edits, None, cx);
 9616            });
 9617
 9618            this.request_autoscroll(Autoscroll::fit(), cx);
 9619        });
 9620    }
 9621
 9622    pub fn duplicate_line_up(
 9623        &mut self,
 9624        _: &DuplicateLineUp,
 9625        window: &mut Window,
 9626        cx: &mut Context<Self>,
 9627    ) {
 9628        self.duplicate(true, true, window, cx);
 9629    }
 9630
 9631    pub fn duplicate_line_down(
 9632        &mut self,
 9633        _: &DuplicateLineDown,
 9634        window: &mut Window,
 9635        cx: &mut Context<Self>,
 9636    ) {
 9637        self.duplicate(false, true, window, cx);
 9638    }
 9639
 9640    pub fn duplicate_selection(
 9641        &mut self,
 9642        _: &DuplicateSelection,
 9643        window: &mut Window,
 9644        cx: &mut Context<Self>,
 9645    ) {
 9646        self.duplicate(false, false, window, cx);
 9647    }
 9648
 9649    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9650        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9651
 9652        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9653        let buffer = self.buffer.read(cx).snapshot(cx);
 9654
 9655        let mut edits = Vec::new();
 9656        let mut unfold_ranges = Vec::new();
 9657        let mut refold_creases = Vec::new();
 9658
 9659        let selections = self.selections.all::<Point>(cx);
 9660        let mut selections = selections.iter().peekable();
 9661        let mut contiguous_row_selections = Vec::new();
 9662        let mut new_selections = Vec::new();
 9663
 9664        while let Some(selection) = selections.next() {
 9665            // Find all the selections that span a contiguous row range
 9666            let (start_row, end_row) = consume_contiguous_rows(
 9667                &mut contiguous_row_selections,
 9668                selection,
 9669                &display_map,
 9670                &mut selections,
 9671            );
 9672
 9673            // Move the text spanned by the row range to be before the line preceding the row range
 9674            if start_row.0 > 0 {
 9675                let range_to_move = Point::new(
 9676                    start_row.previous_row().0,
 9677                    buffer.line_len(start_row.previous_row()),
 9678                )
 9679                    ..Point::new(
 9680                        end_row.previous_row().0,
 9681                        buffer.line_len(end_row.previous_row()),
 9682                    );
 9683                let insertion_point = display_map
 9684                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9685                    .0;
 9686
 9687                // Don't move lines across excerpts
 9688                if buffer
 9689                    .excerpt_containing(insertion_point..range_to_move.end)
 9690                    .is_some()
 9691                {
 9692                    let text = buffer
 9693                        .text_for_range(range_to_move.clone())
 9694                        .flat_map(|s| s.chars())
 9695                        .skip(1)
 9696                        .chain(['\n'])
 9697                        .collect::<String>();
 9698
 9699                    edits.push((
 9700                        buffer.anchor_after(range_to_move.start)
 9701                            ..buffer.anchor_before(range_to_move.end),
 9702                        String::new(),
 9703                    ));
 9704                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9705                    edits.push((insertion_anchor..insertion_anchor, text));
 9706
 9707                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9708
 9709                    // Move selections up
 9710                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9711                        |mut selection| {
 9712                            selection.start.row -= row_delta;
 9713                            selection.end.row -= row_delta;
 9714                            selection
 9715                        },
 9716                    ));
 9717
 9718                    // Move folds up
 9719                    unfold_ranges.push(range_to_move.clone());
 9720                    for fold in display_map.folds_in_range(
 9721                        buffer.anchor_before(range_to_move.start)
 9722                            ..buffer.anchor_after(range_to_move.end),
 9723                    ) {
 9724                        let mut start = fold.range.start.to_point(&buffer);
 9725                        let mut end = fold.range.end.to_point(&buffer);
 9726                        start.row -= row_delta;
 9727                        end.row -= row_delta;
 9728                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9729                    }
 9730                }
 9731            }
 9732
 9733            // If we didn't move line(s), preserve the existing selections
 9734            new_selections.append(&mut contiguous_row_selections);
 9735        }
 9736
 9737        self.transact(window, cx, |this, window, cx| {
 9738            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9739            this.buffer.update(cx, |buffer, cx| {
 9740                for (range, text) in edits {
 9741                    buffer.edit([(range, text)], None, cx);
 9742                }
 9743            });
 9744            this.fold_creases(refold_creases, true, window, cx);
 9745            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9746                s.select(new_selections);
 9747            })
 9748        });
 9749    }
 9750
 9751    pub fn move_line_down(
 9752        &mut self,
 9753        _: &MoveLineDown,
 9754        window: &mut Window,
 9755        cx: &mut Context<Self>,
 9756    ) {
 9757        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9758
 9759        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9760        let buffer = self.buffer.read(cx).snapshot(cx);
 9761
 9762        let mut edits = Vec::new();
 9763        let mut unfold_ranges = Vec::new();
 9764        let mut refold_creases = Vec::new();
 9765
 9766        let selections = self.selections.all::<Point>(cx);
 9767        let mut selections = selections.iter().peekable();
 9768        let mut contiguous_row_selections = Vec::new();
 9769        let mut new_selections = Vec::new();
 9770
 9771        while let Some(selection) = selections.next() {
 9772            // Find all the selections that span a contiguous row range
 9773            let (start_row, end_row) = consume_contiguous_rows(
 9774                &mut contiguous_row_selections,
 9775                selection,
 9776                &display_map,
 9777                &mut selections,
 9778            );
 9779
 9780            // Move the text spanned by the row range to be after the last line of the row range
 9781            if end_row.0 <= buffer.max_point().row {
 9782                let range_to_move =
 9783                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9784                let insertion_point = display_map
 9785                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9786                    .0;
 9787
 9788                // Don't move lines across excerpt boundaries
 9789                if buffer
 9790                    .excerpt_containing(range_to_move.start..insertion_point)
 9791                    .is_some()
 9792                {
 9793                    let mut text = String::from("\n");
 9794                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9795                    text.pop(); // Drop trailing newline
 9796                    edits.push((
 9797                        buffer.anchor_after(range_to_move.start)
 9798                            ..buffer.anchor_before(range_to_move.end),
 9799                        String::new(),
 9800                    ));
 9801                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9802                    edits.push((insertion_anchor..insertion_anchor, text));
 9803
 9804                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9805
 9806                    // Move selections down
 9807                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9808                        |mut selection| {
 9809                            selection.start.row += row_delta;
 9810                            selection.end.row += row_delta;
 9811                            selection
 9812                        },
 9813                    ));
 9814
 9815                    // Move folds down
 9816                    unfold_ranges.push(range_to_move.clone());
 9817                    for fold in display_map.folds_in_range(
 9818                        buffer.anchor_before(range_to_move.start)
 9819                            ..buffer.anchor_after(range_to_move.end),
 9820                    ) {
 9821                        let mut start = fold.range.start.to_point(&buffer);
 9822                        let mut end = fold.range.end.to_point(&buffer);
 9823                        start.row += row_delta;
 9824                        end.row += row_delta;
 9825                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9826                    }
 9827                }
 9828            }
 9829
 9830            // If we didn't move line(s), preserve the existing selections
 9831            new_selections.append(&mut contiguous_row_selections);
 9832        }
 9833
 9834        self.transact(window, cx, |this, window, cx| {
 9835            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9836            this.buffer.update(cx, |buffer, cx| {
 9837                for (range, text) in edits {
 9838                    buffer.edit([(range, text)], None, cx);
 9839                }
 9840            });
 9841            this.fold_creases(refold_creases, true, window, cx);
 9842            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9843                s.select(new_selections)
 9844            });
 9845        });
 9846    }
 9847
 9848    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9849        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9850        let text_layout_details = &self.text_layout_details(window);
 9851        self.transact(window, cx, |this, window, cx| {
 9852            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9853                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9854                s.move_with(|display_map, selection| {
 9855                    if !selection.is_empty() {
 9856                        return;
 9857                    }
 9858
 9859                    let mut head = selection.head();
 9860                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9861                    if head.column() == display_map.line_len(head.row()) {
 9862                        transpose_offset = display_map
 9863                            .buffer_snapshot
 9864                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9865                    }
 9866
 9867                    if transpose_offset == 0 {
 9868                        return;
 9869                    }
 9870
 9871                    *head.column_mut() += 1;
 9872                    head = display_map.clip_point(head, Bias::Right);
 9873                    let goal = SelectionGoal::HorizontalPosition(
 9874                        display_map
 9875                            .x_for_display_point(head, text_layout_details)
 9876                            .into(),
 9877                    );
 9878                    selection.collapse_to(head, goal);
 9879
 9880                    let transpose_start = display_map
 9881                        .buffer_snapshot
 9882                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9883                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9884                        let transpose_end = display_map
 9885                            .buffer_snapshot
 9886                            .clip_offset(transpose_offset + 1, Bias::Right);
 9887                        if let Some(ch) =
 9888                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9889                        {
 9890                            edits.push((transpose_start..transpose_offset, String::new()));
 9891                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9892                        }
 9893                    }
 9894                });
 9895                edits
 9896            });
 9897            this.buffer
 9898                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9899            let selections = this.selections.all::<usize>(cx);
 9900            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9901                s.select(selections);
 9902            });
 9903        });
 9904    }
 9905
 9906    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9907        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9908        self.rewrap_impl(RewrapOptions::default(), cx)
 9909    }
 9910
 9911    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9912        let buffer = self.buffer.read(cx).snapshot(cx);
 9913        let selections = self.selections.all::<Point>(cx);
 9914        let mut selections = selections.iter().peekable();
 9915
 9916        let mut edits = Vec::new();
 9917        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9918
 9919        while let Some(selection) = selections.next() {
 9920            let mut start_row = selection.start.row;
 9921            let mut end_row = selection.end.row;
 9922
 9923            // Skip selections that overlap with a range that has already been rewrapped.
 9924            let selection_range = start_row..end_row;
 9925            if rewrapped_row_ranges
 9926                .iter()
 9927                .any(|range| range.overlaps(&selection_range))
 9928            {
 9929                continue;
 9930            }
 9931
 9932            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9933
 9934            // Since not all lines in the selection may be at the same indent
 9935            // level, choose the indent size that is the most common between all
 9936            // of the lines.
 9937            //
 9938            // If there is a tie, we use the deepest indent.
 9939            let (indent_size, indent_end) = {
 9940                let mut indent_size_occurrences = HashMap::default();
 9941                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9942
 9943                for row in start_row..=end_row {
 9944                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9945                    rows_by_indent_size.entry(indent).or_default().push(row);
 9946                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9947                }
 9948
 9949                let indent_size = indent_size_occurrences
 9950                    .into_iter()
 9951                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9952                    .map(|(indent, _)| indent)
 9953                    .unwrap_or_default();
 9954                let row = rows_by_indent_size[&indent_size][0];
 9955                let indent_end = Point::new(row, indent_size.len);
 9956
 9957                (indent_size, indent_end)
 9958            };
 9959
 9960            let mut line_prefix = indent_size.chars().collect::<String>();
 9961
 9962            let mut inside_comment = false;
 9963            if let Some(comment_prefix) =
 9964                buffer
 9965                    .language_scope_at(selection.head())
 9966                    .and_then(|language| {
 9967                        language
 9968                            .line_comment_prefixes()
 9969                            .iter()
 9970                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9971                            .cloned()
 9972                    })
 9973            {
 9974                line_prefix.push_str(&comment_prefix);
 9975                inside_comment = true;
 9976            }
 9977
 9978            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9979            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9980                RewrapBehavior::InComments => inside_comment,
 9981                RewrapBehavior::InSelections => !selection.is_empty(),
 9982                RewrapBehavior::Anywhere => true,
 9983            };
 9984
 9985            let should_rewrap = options.override_language_settings
 9986                || allow_rewrap_based_on_language
 9987                || self.hard_wrap.is_some();
 9988            if !should_rewrap {
 9989                continue;
 9990            }
 9991
 9992            if selection.is_empty() {
 9993                'expand_upwards: while start_row > 0 {
 9994                    let prev_row = start_row - 1;
 9995                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9996                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9997                    {
 9998                        start_row = prev_row;
 9999                    } else {
10000                        break 'expand_upwards;
10001                    }
10002                }
10003
10004                'expand_downwards: while end_row < buffer.max_point().row {
10005                    let next_row = end_row + 1;
10006                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10007                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10008                    {
10009                        end_row = next_row;
10010                    } else {
10011                        break 'expand_downwards;
10012                    }
10013                }
10014            }
10015
10016            let start = Point::new(start_row, 0);
10017            let start_offset = start.to_offset(&buffer);
10018            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10019            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10020            let Some(lines_without_prefixes) = selection_text
10021                .lines()
10022                .map(|line| {
10023                    line.strip_prefix(&line_prefix)
10024                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10025                        .ok_or_else(|| {
10026                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10027                        })
10028                })
10029                .collect::<Result<Vec<_>, _>>()
10030                .log_err()
10031            else {
10032                continue;
10033            };
10034
10035            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10036                buffer
10037                    .language_settings_at(Point::new(start_row, 0), cx)
10038                    .preferred_line_length as usize
10039            });
10040            let wrapped_text = wrap_with_prefix(
10041                line_prefix,
10042                lines_without_prefixes.join("\n"),
10043                wrap_column,
10044                tab_size,
10045                options.preserve_existing_whitespace,
10046            );
10047
10048            // TODO: should always use char-based diff while still supporting cursor behavior that
10049            // matches vim.
10050            let mut diff_options = DiffOptions::default();
10051            if options.override_language_settings {
10052                diff_options.max_word_diff_len = 0;
10053                diff_options.max_word_diff_line_count = 0;
10054            } else {
10055                diff_options.max_word_diff_len = usize::MAX;
10056                diff_options.max_word_diff_line_count = usize::MAX;
10057            }
10058
10059            for (old_range, new_text) in
10060                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10061            {
10062                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10063                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10064                edits.push((edit_start..edit_end, new_text));
10065            }
10066
10067            rewrapped_row_ranges.push(start_row..=end_row);
10068        }
10069
10070        self.buffer
10071            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10072    }
10073
10074    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10075        let mut text = String::new();
10076        let buffer = self.buffer.read(cx).snapshot(cx);
10077        let mut selections = self.selections.all::<Point>(cx);
10078        let mut clipboard_selections = Vec::with_capacity(selections.len());
10079        {
10080            let max_point = buffer.max_point();
10081            let mut is_first = true;
10082            for selection in &mut selections {
10083                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10084                if is_entire_line {
10085                    selection.start = Point::new(selection.start.row, 0);
10086                    if !selection.is_empty() && selection.end.column == 0 {
10087                        selection.end = cmp::min(max_point, selection.end);
10088                    } else {
10089                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10090                    }
10091                    selection.goal = SelectionGoal::None;
10092                }
10093                if is_first {
10094                    is_first = false;
10095                } else {
10096                    text += "\n";
10097                }
10098                let mut len = 0;
10099                for chunk in buffer.text_for_range(selection.start..selection.end) {
10100                    text.push_str(chunk);
10101                    len += chunk.len();
10102                }
10103                clipboard_selections.push(ClipboardSelection {
10104                    len,
10105                    is_entire_line,
10106                    first_line_indent: buffer
10107                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10108                        .len,
10109                });
10110            }
10111        }
10112
10113        self.transact(window, cx, |this, window, cx| {
10114            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10115                s.select(selections);
10116            });
10117            this.insert("", window, cx);
10118        });
10119        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10120    }
10121
10122    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10123        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10124        let item = self.cut_common(window, cx);
10125        cx.write_to_clipboard(item);
10126    }
10127
10128    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10129        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10130        self.change_selections(None, window, cx, |s| {
10131            s.move_with(|snapshot, sel| {
10132                if sel.is_empty() {
10133                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10134                }
10135            });
10136        });
10137        let item = self.cut_common(window, cx);
10138        cx.set_global(KillRing(item))
10139    }
10140
10141    pub fn kill_ring_yank(
10142        &mut self,
10143        _: &KillRingYank,
10144        window: &mut Window,
10145        cx: &mut Context<Self>,
10146    ) {
10147        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10148        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10149            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10150                (kill_ring.text().to_string(), kill_ring.metadata_json())
10151            } else {
10152                return;
10153            }
10154        } else {
10155            return;
10156        };
10157        self.do_paste(&text, metadata, false, window, cx);
10158    }
10159
10160    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10161        self.do_copy(true, cx);
10162    }
10163
10164    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10165        self.do_copy(false, cx);
10166    }
10167
10168    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10169        let selections = self.selections.all::<Point>(cx);
10170        let buffer = self.buffer.read(cx).read(cx);
10171        let mut text = String::new();
10172
10173        let mut clipboard_selections = Vec::with_capacity(selections.len());
10174        {
10175            let max_point = buffer.max_point();
10176            let mut is_first = true;
10177            for selection in &selections {
10178                let mut start = selection.start;
10179                let mut end = selection.end;
10180                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10181                if is_entire_line {
10182                    start = Point::new(start.row, 0);
10183                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10184                }
10185
10186                let mut trimmed_selections = Vec::new();
10187                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10188                    let row = MultiBufferRow(start.row);
10189                    let first_indent = buffer.indent_size_for_line(row);
10190                    if first_indent.len == 0 || start.column > first_indent.len {
10191                        trimmed_selections.push(start..end);
10192                    } else {
10193                        trimmed_selections.push(
10194                            Point::new(row.0, first_indent.len)
10195                                ..Point::new(row.0, buffer.line_len(row)),
10196                        );
10197                        for row in start.row + 1..=end.row {
10198                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10199                            if row == end.row {
10200                                line_len = end.column;
10201                            }
10202                            if line_len == 0 {
10203                                trimmed_selections
10204                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10205                                continue;
10206                            }
10207                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10208                            if row_indent_size.len >= first_indent.len {
10209                                trimmed_selections.push(
10210                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10211                                );
10212                            } else {
10213                                trimmed_selections.clear();
10214                                trimmed_selections.push(start..end);
10215                                break;
10216                            }
10217                        }
10218                    }
10219                } else {
10220                    trimmed_selections.push(start..end);
10221                }
10222
10223                for trimmed_range in trimmed_selections {
10224                    if is_first {
10225                        is_first = false;
10226                    } else {
10227                        text += "\n";
10228                    }
10229                    let mut len = 0;
10230                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10231                        text.push_str(chunk);
10232                        len += chunk.len();
10233                    }
10234                    clipboard_selections.push(ClipboardSelection {
10235                        len,
10236                        is_entire_line,
10237                        first_line_indent: buffer
10238                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10239                            .len,
10240                    });
10241                }
10242            }
10243        }
10244
10245        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10246            text,
10247            clipboard_selections,
10248        ));
10249    }
10250
10251    pub fn do_paste(
10252        &mut self,
10253        text: &String,
10254        clipboard_selections: Option<Vec<ClipboardSelection>>,
10255        handle_entire_lines: bool,
10256        window: &mut Window,
10257        cx: &mut Context<Self>,
10258    ) {
10259        if self.read_only(cx) {
10260            return;
10261        }
10262
10263        let clipboard_text = Cow::Borrowed(text);
10264
10265        self.transact(window, cx, |this, window, cx| {
10266            if let Some(mut clipboard_selections) = clipboard_selections {
10267                let old_selections = this.selections.all::<usize>(cx);
10268                let all_selections_were_entire_line =
10269                    clipboard_selections.iter().all(|s| s.is_entire_line);
10270                let first_selection_indent_column =
10271                    clipboard_selections.first().map(|s| s.first_line_indent);
10272                if clipboard_selections.len() != old_selections.len() {
10273                    clipboard_selections.drain(..);
10274                }
10275                let cursor_offset = this.selections.last::<usize>(cx).head();
10276                let mut auto_indent_on_paste = true;
10277
10278                this.buffer.update(cx, |buffer, cx| {
10279                    let snapshot = buffer.read(cx);
10280                    auto_indent_on_paste = snapshot
10281                        .language_settings_at(cursor_offset, cx)
10282                        .auto_indent_on_paste;
10283
10284                    let mut start_offset = 0;
10285                    let mut edits = Vec::new();
10286                    let mut original_indent_columns = Vec::new();
10287                    for (ix, selection) in old_selections.iter().enumerate() {
10288                        let to_insert;
10289                        let entire_line;
10290                        let original_indent_column;
10291                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10292                            let end_offset = start_offset + clipboard_selection.len;
10293                            to_insert = &clipboard_text[start_offset..end_offset];
10294                            entire_line = clipboard_selection.is_entire_line;
10295                            start_offset = end_offset + 1;
10296                            original_indent_column = Some(clipboard_selection.first_line_indent);
10297                        } else {
10298                            to_insert = clipboard_text.as_str();
10299                            entire_line = all_selections_were_entire_line;
10300                            original_indent_column = first_selection_indent_column
10301                        }
10302
10303                        // If the corresponding selection was empty when this slice of the
10304                        // clipboard text was written, then the entire line containing the
10305                        // selection was copied. If this selection is also currently empty,
10306                        // then paste the line before the current line of the buffer.
10307                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10308                            let column = selection.start.to_point(&snapshot).column as usize;
10309                            let line_start = selection.start - column;
10310                            line_start..line_start
10311                        } else {
10312                            selection.range()
10313                        };
10314
10315                        edits.push((range, to_insert));
10316                        original_indent_columns.push(original_indent_column);
10317                    }
10318                    drop(snapshot);
10319
10320                    buffer.edit(
10321                        edits,
10322                        if auto_indent_on_paste {
10323                            Some(AutoindentMode::Block {
10324                                original_indent_columns,
10325                            })
10326                        } else {
10327                            None
10328                        },
10329                        cx,
10330                    );
10331                });
10332
10333                let selections = this.selections.all::<usize>(cx);
10334                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10335                    s.select(selections)
10336                });
10337            } else {
10338                this.insert(&clipboard_text, window, cx);
10339            }
10340        });
10341    }
10342
10343    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10344        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10345        if let Some(item) = cx.read_from_clipboard() {
10346            let entries = item.entries();
10347
10348            match entries.first() {
10349                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10350                // of all the pasted entries.
10351                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10352                    .do_paste(
10353                        clipboard_string.text(),
10354                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10355                        true,
10356                        window,
10357                        cx,
10358                    ),
10359                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10360            }
10361        }
10362    }
10363
10364    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10365        if self.read_only(cx) {
10366            return;
10367        }
10368
10369        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10370
10371        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10372            if let Some((selections, _)) =
10373                self.selection_history.transaction(transaction_id).cloned()
10374            {
10375                self.change_selections(None, window, cx, |s| {
10376                    s.select_anchors(selections.to_vec());
10377                });
10378            } else {
10379                log::error!(
10380                    "No entry in selection_history found for undo. \
10381                     This may correspond to a bug where undo does not update the selection. \
10382                     If this is occurring, please add details to \
10383                     https://github.com/zed-industries/zed/issues/22692"
10384                );
10385            }
10386            self.request_autoscroll(Autoscroll::fit(), cx);
10387            self.unmark_text(window, cx);
10388            self.refresh_inline_completion(true, false, window, cx);
10389            cx.emit(EditorEvent::Edited { transaction_id });
10390            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10391        }
10392    }
10393
10394    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10395        if self.read_only(cx) {
10396            return;
10397        }
10398
10399        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10400
10401        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10402            if let Some((_, Some(selections))) =
10403                self.selection_history.transaction(transaction_id).cloned()
10404            {
10405                self.change_selections(None, window, cx, |s| {
10406                    s.select_anchors(selections.to_vec());
10407                });
10408            } else {
10409                log::error!(
10410                    "No entry in selection_history found for redo. \
10411                     This may correspond to a bug where undo does not update the selection. \
10412                     If this is occurring, please add details to \
10413                     https://github.com/zed-industries/zed/issues/22692"
10414                );
10415            }
10416            self.request_autoscroll(Autoscroll::fit(), cx);
10417            self.unmark_text(window, cx);
10418            self.refresh_inline_completion(true, false, window, cx);
10419            cx.emit(EditorEvent::Edited { transaction_id });
10420        }
10421    }
10422
10423    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10424        self.buffer
10425            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10426    }
10427
10428    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10429        self.buffer
10430            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10431    }
10432
10433    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10434        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10435        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10436            s.move_with(|map, selection| {
10437                let cursor = if selection.is_empty() {
10438                    movement::left(map, selection.start)
10439                } else {
10440                    selection.start
10441                };
10442                selection.collapse_to(cursor, SelectionGoal::None);
10443            });
10444        })
10445    }
10446
10447    pub fn select_left(&mut self, _: &SelectLeft, 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_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10451        })
10452    }
10453
10454    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10455        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10456        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10457            s.move_with(|map, selection| {
10458                let cursor = if selection.is_empty() {
10459                    movement::right(map, selection.end)
10460                } else {
10461                    selection.end
10462                };
10463                selection.collapse_to(cursor, SelectionGoal::None)
10464            });
10465        })
10466    }
10467
10468    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10469        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10470        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10471            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10472        })
10473    }
10474
10475    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10476        if self.take_rename(true, window, cx).is_some() {
10477            return;
10478        }
10479
10480        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10481            cx.propagate();
10482            return;
10483        }
10484
10485        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10486
10487        let text_layout_details = &self.text_layout_details(window);
10488        let selection_count = self.selections.count();
10489        let first_selection = self.selections.first_anchor();
10490
10491        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10492            s.move_with(|map, selection| {
10493                if !selection.is_empty() {
10494                    selection.goal = SelectionGoal::None;
10495                }
10496                let (cursor, goal) = movement::up(
10497                    map,
10498                    selection.start,
10499                    selection.goal,
10500                    false,
10501                    text_layout_details,
10502                );
10503                selection.collapse_to(cursor, goal);
10504            });
10505        });
10506
10507        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10508        {
10509            cx.propagate();
10510        }
10511    }
10512
10513    pub fn move_up_by_lines(
10514        &mut self,
10515        action: &MoveUpByLines,
10516        window: &mut Window,
10517        cx: &mut Context<Self>,
10518    ) {
10519        if self.take_rename(true, window, cx).is_some() {
10520            return;
10521        }
10522
10523        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10524            cx.propagate();
10525            return;
10526        }
10527
10528        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10529
10530        let text_layout_details = &self.text_layout_details(window);
10531
10532        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10533            s.move_with(|map, selection| {
10534                if !selection.is_empty() {
10535                    selection.goal = SelectionGoal::None;
10536                }
10537                let (cursor, goal) = movement::up_by_rows(
10538                    map,
10539                    selection.start,
10540                    action.lines,
10541                    selection.goal,
10542                    false,
10543                    text_layout_details,
10544                );
10545                selection.collapse_to(cursor, goal);
10546            });
10547        })
10548    }
10549
10550    pub fn move_down_by_lines(
10551        &mut self,
10552        action: &MoveDownByLines,
10553        window: &mut Window,
10554        cx: &mut Context<Self>,
10555    ) {
10556        if self.take_rename(true, window, cx).is_some() {
10557            return;
10558        }
10559
10560        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10561            cx.propagate();
10562            return;
10563        }
10564
10565        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10566
10567        let text_layout_details = &self.text_layout_details(window);
10568
10569        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10570            s.move_with(|map, selection| {
10571                if !selection.is_empty() {
10572                    selection.goal = SelectionGoal::None;
10573                }
10574                let (cursor, goal) = movement::down_by_rows(
10575                    map,
10576                    selection.start,
10577                    action.lines,
10578                    selection.goal,
10579                    false,
10580                    text_layout_details,
10581                );
10582                selection.collapse_to(cursor, goal);
10583            });
10584        })
10585    }
10586
10587    pub fn select_down_by_lines(
10588        &mut self,
10589        action: &SelectDownByLines,
10590        window: &mut Window,
10591        cx: &mut Context<Self>,
10592    ) {
10593        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10594        let text_layout_details = &self.text_layout_details(window);
10595        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10596            s.move_heads_with(|map, head, goal| {
10597                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10598            })
10599        })
10600    }
10601
10602    pub fn select_up_by_lines(
10603        &mut self,
10604        action: &SelectUpByLines,
10605        window: &mut Window,
10606        cx: &mut Context<Self>,
10607    ) {
10608        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10609        let text_layout_details = &self.text_layout_details(window);
10610        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10611            s.move_heads_with(|map, head, goal| {
10612                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10613            })
10614        })
10615    }
10616
10617    pub fn select_page_up(
10618        &mut self,
10619        _: &SelectPageUp,
10620        window: &mut Window,
10621        cx: &mut Context<Self>,
10622    ) {
10623        let Some(row_count) = self.visible_row_count() else {
10624            return;
10625        };
10626
10627        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10628
10629        let text_layout_details = &self.text_layout_details(window);
10630
10631        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10632            s.move_heads_with(|map, head, goal| {
10633                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10634            })
10635        })
10636    }
10637
10638    pub fn move_page_up(
10639        &mut self,
10640        action: &MovePageUp,
10641        window: &mut Window,
10642        cx: &mut Context<Self>,
10643    ) {
10644        if self.take_rename(true, window, cx).is_some() {
10645            return;
10646        }
10647
10648        if self
10649            .context_menu
10650            .borrow_mut()
10651            .as_mut()
10652            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10653            .unwrap_or(false)
10654        {
10655            return;
10656        }
10657
10658        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10659            cx.propagate();
10660            return;
10661        }
10662
10663        let Some(row_count) = self.visible_row_count() else {
10664            return;
10665        };
10666
10667        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10668
10669        let autoscroll = if action.center_cursor {
10670            Autoscroll::center()
10671        } else {
10672            Autoscroll::fit()
10673        };
10674
10675        let text_layout_details = &self.text_layout_details(window);
10676
10677        self.change_selections(Some(autoscroll), window, cx, |s| {
10678            s.move_with(|map, selection| {
10679                if !selection.is_empty() {
10680                    selection.goal = SelectionGoal::None;
10681                }
10682                let (cursor, goal) = movement::up_by_rows(
10683                    map,
10684                    selection.end,
10685                    row_count,
10686                    selection.goal,
10687                    false,
10688                    text_layout_details,
10689                );
10690                selection.collapse_to(cursor, goal);
10691            });
10692        });
10693    }
10694
10695    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10696        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10697        let text_layout_details = &self.text_layout_details(window);
10698        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10699            s.move_heads_with(|map, head, goal| {
10700                movement::up(map, head, goal, false, text_layout_details)
10701            })
10702        })
10703    }
10704
10705    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10706        self.take_rename(true, window, cx);
10707
10708        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10709            cx.propagate();
10710            return;
10711        }
10712
10713        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10714
10715        let text_layout_details = &self.text_layout_details(window);
10716        let selection_count = self.selections.count();
10717        let first_selection = self.selections.first_anchor();
10718
10719        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10720            s.move_with(|map, selection| {
10721                if !selection.is_empty() {
10722                    selection.goal = SelectionGoal::None;
10723                }
10724                let (cursor, goal) = movement::down(
10725                    map,
10726                    selection.end,
10727                    selection.goal,
10728                    false,
10729                    text_layout_details,
10730                );
10731                selection.collapse_to(cursor, goal);
10732            });
10733        });
10734
10735        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10736        {
10737            cx.propagate();
10738        }
10739    }
10740
10741    pub fn select_page_down(
10742        &mut self,
10743        _: &SelectPageDown,
10744        window: &mut Window,
10745        cx: &mut Context<Self>,
10746    ) {
10747        let Some(row_count) = self.visible_row_count() else {
10748            return;
10749        };
10750
10751        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10752
10753        let text_layout_details = &self.text_layout_details(window);
10754
10755        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10756            s.move_heads_with(|map, head, goal| {
10757                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10758            })
10759        })
10760    }
10761
10762    pub fn move_page_down(
10763        &mut self,
10764        action: &MovePageDown,
10765        window: &mut Window,
10766        cx: &mut Context<Self>,
10767    ) {
10768        if self.take_rename(true, window, cx).is_some() {
10769            return;
10770        }
10771
10772        if self
10773            .context_menu
10774            .borrow_mut()
10775            .as_mut()
10776            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10777            .unwrap_or(false)
10778        {
10779            return;
10780        }
10781
10782        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10783            cx.propagate();
10784            return;
10785        }
10786
10787        let Some(row_count) = self.visible_row_count() else {
10788            return;
10789        };
10790
10791        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10792
10793        let autoscroll = if action.center_cursor {
10794            Autoscroll::center()
10795        } else {
10796            Autoscroll::fit()
10797        };
10798
10799        let text_layout_details = &self.text_layout_details(window);
10800        self.change_selections(Some(autoscroll), window, cx, |s| {
10801            s.move_with(|map, selection| {
10802                if !selection.is_empty() {
10803                    selection.goal = SelectionGoal::None;
10804                }
10805                let (cursor, goal) = movement::down_by_rows(
10806                    map,
10807                    selection.end,
10808                    row_count,
10809                    selection.goal,
10810                    false,
10811                    text_layout_details,
10812                );
10813                selection.collapse_to(cursor, goal);
10814            });
10815        });
10816    }
10817
10818    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10819        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10820        let text_layout_details = &self.text_layout_details(window);
10821        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10822            s.move_heads_with(|map, head, goal| {
10823                movement::down(map, head, goal, false, text_layout_details)
10824            })
10825        });
10826    }
10827
10828    pub fn context_menu_first(
10829        &mut self,
10830        _: &ContextMenuFirst,
10831        _window: &mut Window,
10832        cx: &mut Context<Self>,
10833    ) {
10834        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10835            context_menu.select_first(self.completion_provider.as_deref(), cx);
10836        }
10837    }
10838
10839    pub fn context_menu_prev(
10840        &mut self,
10841        _: &ContextMenuPrevious,
10842        _window: &mut Window,
10843        cx: &mut Context<Self>,
10844    ) {
10845        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10846            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10847        }
10848    }
10849
10850    pub fn context_menu_next(
10851        &mut self,
10852        _: &ContextMenuNext,
10853        _window: &mut Window,
10854        cx: &mut Context<Self>,
10855    ) {
10856        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10857            context_menu.select_next(self.completion_provider.as_deref(), cx);
10858        }
10859    }
10860
10861    pub fn context_menu_last(
10862        &mut self,
10863        _: &ContextMenuLast,
10864        _window: &mut Window,
10865        cx: &mut Context<Self>,
10866    ) {
10867        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10868            context_menu.select_last(self.completion_provider.as_deref(), cx);
10869        }
10870    }
10871
10872    pub fn move_to_previous_word_start(
10873        &mut self,
10874        _: &MoveToPreviousWordStart,
10875        window: &mut Window,
10876        cx: &mut Context<Self>,
10877    ) {
10878        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10879        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10880            s.move_cursors_with(|map, head, _| {
10881                (
10882                    movement::previous_word_start(map, head),
10883                    SelectionGoal::None,
10884                )
10885            });
10886        })
10887    }
10888
10889    pub fn move_to_previous_subword_start(
10890        &mut self,
10891        _: &MoveToPreviousSubwordStart,
10892        window: &mut Window,
10893        cx: &mut Context<Self>,
10894    ) {
10895        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10896        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10897            s.move_cursors_with(|map, head, _| {
10898                (
10899                    movement::previous_subword_start(map, head),
10900                    SelectionGoal::None,
10901                )
10902            });
10903        })
10904    }
10905
10906    pub fn select_to_previous_word_start(
10907        &mut self,
10908        _: &SelectToPreviousWordStart,
10909        window: &mut Window,
10910        cx: &mut Context<Self>,
10911    ) {
10912        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10913        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10914            s.move_heads_with(|map, head, _| {
10915                (
10916                    movement::previous_word_start(map, head),
10917                    SelectionGoal::None,
10918                )
10919            });
10920        })
10921    }
10922
10923    pub fn select_to_previous_subword_start(
10924        &mut self,
10925        _: &SelectToPreviousSubwordStart,
10926        window: &mut Window,
10927        cx: &mut Context<Self>,
10928    ) {
10929        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10930        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10931            s.move_heads_with(|map, head, _| {
10932                (
10933                    movement::previous_subword_start(map, head),
10934                    SelectionGoal::None,
10935                )
10936            });
10937        })
10938    }
10939
10940    pub fn delete_to_previous_word_start(
10941        &mut self,
10942        action: &DeleteToPreviousWordStart,
10943        window: &mut Window,
10944        cx: &mut Context<Self>,
10945    ) {
10946        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10947        self.transact(window, cx, |this, window, cx| {
10948            this.select_autoclose_pair(window, cx);
10949            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10950                s.move_with(|map, selection| {
10951                    if selection.is_empty() {
10952                        let cursor = if action.ignore_newlines {
10953                            movement::previous_word_start(map, selection.head())
10954                        } else {
10955                            movement::previous_word_start_or_newline(map, selection.head())
10956                        };
10957                        selection.set_head(cursor, SelectionGoal::None);
10958                    }
10959                });
10960            });
10961            this.insert("", window, cx);
10962        });
10963    }
10964
10965    pub fn delete_to_previous_subword_start(
10966        &mut self,
10967        _: &DeleteToPreviousSubwordStart,
10968        window: &mut Window,
10969        cx: &mut Context<Self>,
10970    ) {
10971        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10972        self.transact(window, cx, |this, window, cx| {
10973            this.select_autoclose_pair(window, cx);
10974            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10975                s.move_with(|map, selection| {
10976                    if selection.is_empty() {
10977                        let cursor = movement::previous_subword_start(map, selection.head());
10978                        selection.set_head(cursor, SelectionGoal::None);
10979                    }
10980                });
10981            });
10982            this.insert("", window, cx);
10983        });
10984    }
10985
10986    pub fn move_to_next_word_end(
10987        &mut self,
10988        _: &MoveToNextWordEnd,
10989        window: &mut Window,
10990        cx: &mut Context<Self>,
10991    ) {
10992        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10993        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10994            s.move_cursors_with(|map, head, _| {
10995                (movement::next_word_end(map, head), SelectionGoal::None)
10996            });
10997        })
10998    }
10999
11000    pub fn move_to_next_subword_end(
11001        &mut self,
11002        _: &MoveToNextSubwordEnd,
11003        window: &mut Window,
11004        cx: &mut Context<Self>,
11005    ) {
11006        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11007        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11008            s.move_cursors_with(|map, head, _| {
11009                (movement::next_subword_end(map, head), SelectionGoal::None)
11010            });
11011        })
11012    }
11013
11014    pub fn select_to_next_word_end(
11015        &mut self,
11016        _: &SelectToNextWordEnd,
11017        window: &mut Window,
11018        cx: &mut Context<Self>,
11019    ) {
11020        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11021        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11022            s.move_heads_with(|map, head, _| {
11023                (movement::next_word_end(map, head), SelectionGoal::None)
11024            });
11025        })
11026    }
11027
11028    pub fn select_to_next_subword_end(
11029        &mut self,
11030        _: &SelectToNextSubwordEnd,
11031        window: &mut Window,
11032        cx: &mut Context<Self>,
11033    ) {
11034        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11035        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11036            s.move_heads_with(|map, head, _| {
11037                (movement::next_subword_end(map, head), SelectionGoal::None)
11038            });
11039        })
11040    }
11041
11042    pub fn delete_to_next_word_end(
11043        &mut self,
11044        action: &DeleteToNextWordEnd,
11045        window: &mut Window,
11046        cx: &mut Context<Self>,
11047    ) {
11048        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11049        self.transact(window, cx, |this, window, cx| {
11050            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11051                s.move_with(|map, selection| {
11052                    if selection.is_empty() {
11053                        let cursor = if action.ignore_newlines {
11054                            movement::next_word_end(map, selection.head())
11055                        } else {
11056                            movement::next_word_end_or_newline(map, selection.head())
11057                        };
11058                        selection.set_head(cursor, SelectionGoal::None);
11059                    }
11060                });
11061            });
11062            this.insert("", window, cx);
11063        });
11064    }
11065
11066    pub fn delete_to_next_subword_end(
11067        &mut self,
11068        _: &DeleteToNextSubwordEnd,
11069        window: &mut Window,
11070        cx: &mut Context<Self>,
11071    ) {
11072        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11073        self.transact(window, cx, |this, window, cx| {
11074            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11075                s.move_with(|map, selection| {
11076                    if selection.is_empty() {
11077                        let cursor = movement::next_subword_end(map, selection.head());
11078                        selection.set_head(cursor, SelectionGoal::None);
11079                    }
11080                });
11081            });
11082            this.insert("", window, cx);
11083        });
11084    }
11085
11086    pub fn move_to_beginning_of_line(
11087        &mut self,
11088        action: &MoveToBeginningOfLine,
11089        window: &mut Window,
11090        cx: &mut Context<Self>,
11091    ) {
11092        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11093        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11094            s.move_cursors_with(|map, head, _| {
11095                (
11096                    movement::indented_line_beginning(
11097                        map,
11098                        head,
11099                        action.stop_at_soft_wraps,
11100                        action.stop_at_indent,
11101                    ),
11102                    SelectionGoal::None,
11103                )
11104            });
11105        })
11106    }
11107
11108    pub fn select_to_beginning_of_line(
11109        &mut self,
11110        action: &SelectToBeginningOfLine,
11111        window: &mut Window,
11112        cx: &mut Context<Self>,
11113    ) {
11114        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11115        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11116            s.move_heads_with(|map, head, _| {
11117                (
11118                    movement::indented_line_beginning(
11119                        map,
11120                        head,
11121                        action.stop_at_soft_wraps,
11122                        action.stop_at_indent,
11123                    ),
11124                    SelectionGoal::None,
11125                )
11126            });
11127        });
11128    }
11129
11130    pub fn delete_to_beginning_of_line(
11131        &mut self,
11132        action: &DeleteToBeginningOfLine,
11133        window: &mut Window,
11134        cx: &mut Context<Self>,
11135    ) {
11136        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11137        self.transact(window, cx, |this, window, cx| {
11138            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11139                s.move_with(|_, selection| {
11140                    selection.reversed = true;
11141                });
11142            });
11143
11144            this.select_to_beginning_of_line(
11145                &SelectToBeginningOfLine {
11146                    stop_at_soft_wraps: false,
11147                    stop_at_indent: action.stop_at_indent,
11148                },
11149                window,
11150                cx,
11151            );
11152            this.backspace(&Backspace, window, cx);
11153        });
11154    }
11155
11156    pub fn move_to_end_of_line(
11157        &mut self,
11158        action: &MoveToEndOfLine,
11159        window: &mut Window,
11160        cx: &mut Context<Self>,
11161    ) {
11162        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11163        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11164            s.move_cursors_with(|map, head, _| {
11165                (
11166                    movement::line_end(map, head, action.stop_at_soft_wraps),
11167                    SelectionGoal::None,
11168                )
11169            });
11170        })
11171    }
11172
11173    pub fn select_to_end_of_line(
11174        &mut self,
11175        action: &SelectToEndOfLine,
11176        window: &mut Window,
11177        cx: &mut Context<Self>,
11178    ) {
11179        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11180        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11181            s.move_heads_with(|map, head, _| {
11182                (
11183                    movement::line_end(map, head, action.stop_at_soft_wraps),
11184                    SelectionGoal::None,
11185                )
11186            });
11187        })
11188    }
11189
11190    pub fn delete_to_end_of_line(
11191        &mut self,
11192        _: &DeleteToEndOfLine,
11193        window: &mut Window,
11194        cx: &mut Context<Self>,
11195    ) {
11196        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11197        self.transact(window, cx, |this, window, cx| {
11198            this.select_to_end_of_line(
11199                &SelectToEndOfLine {
11200                    stop_at_soft_wraps: false,
11201                },
11202                window,
11203                cx,
11204            );
11205            this.delete(&Delete, window, cx);
11206        });
11207    }
11208
11209    pub fn cut_to_end_of_line(
11210        &mut self,
11211        _: &CutToEndOfLine,
11212        window: &mut Window,
11213        cx: &mut Context<Self>,
11214    ) {
11215        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11216        self.transact(window, cx, |this, window, cx| {
11217            this.select_to_end_of_line(
11218                &SelectToEndOfLine {
11219                    stop_at_soft_wraps: false,
11220                },
11221                window,
11222                cx,
11223            );
11224            this.cut(&Cut, window, cx);
11225        });
11226    }
11227
11228    pub fn move_to_start_of_paragraph(
11229        &mut self,
11230        _: &MoveToStartOfParagraph,
11231        window: &mut Window,
11232        cx: &mut Context<Self>,
11233    ) {
11234        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11235            cx.propagate();
11236            return;
11237        }
11238        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11239        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11240            s.move_with(|map, selection| {
11241                selection.collapse_to(
11242                    movement::start_of_paragraph(map, selection.head(), 1),
11243                    SelectionGoal::None,
11244                )
11245            });
11246        })
11247    }
11248
11249    pub fn move_to_end_of_paragraph(
11250        &mut self,
11251        _: &MoveToEndOfParagraph,
11252        window: &mut Window,
11253        cx: &mut Context<Self>,
11254    ) {
11255        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11256            cx.propagate();
11257            return;
11258        }
11259        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11260        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11261            s.move_with(|map, selection| {
11262                selection.collapse_to(
11263                    movement::end_of_paragraph(map, selection.head(), 1),
11264                    SelectionGoal::None,
11265                )
11266            });
11267        })
11268    }
11269
11270    pub fn select_to_start_of_paragraph(
11271        &mut self,
11272        _: &SelectToStartOfParagraph,
11273        window: &mut Window,
11274        cx: &mut Context<Self>,
11275    ) {
11276        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11277            cx.propagate();
11278            return;
11279        }
11280        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11281        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11282            s.move_heads_with(|map, head, _| {
11283                (
11284                    movement::start_of_paragraph(map, head, 1),
11285                    SelectionGoal::None,
11286                )
11287            });
11288        })
11289    }
11290
11291    pub fn select_to_end_of_paragraph(
11292        &mut self,
11293        _: &SelectToEndOfParagraph,
11294        window: &mut Window,
11295        cx: &mut Context<Self>,
11296    ) {
11297        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11298            cx.propagate();
11299            return;
11300        }
11301        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11302        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11303            s.move_heads_with(|map, head, _| {
11304                (
11305                    movement::end_of_paragraph(map, head, 1),
11306                    SelectionGoal::None,
11307                )
11308            });
11309        })
11310    }
11311
11312    pub fn move_to_start_of_excerpt(
11313        &mut self,
11314        _: &MoveToStartOfExcerpt,
11315        window: &mut Window,
11316        cx: &mut Context<Self>,
11317    ) {
11318        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11319            cx.propagate();
11320            return;
11321        }
11322        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11323        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11324            s.move_with(|map, selection| {
11325                selection.collapse_to(
11326                    movement::start_of_excerpt(
11327                        map,
11328                        selection.head(),
11329                        workspace::searchable::Direction::Prev,
11330                    ),
11331                    SelectionGoal::None,
11332                )
11333            });
11334        })
11335    }
11336
11337    pub fn move_to_start_of_next_excerpt(
11338        &mut self,
11339        _: &MoveToStartOfNextExcerpt,
11340        window: &mut Window,
11341        cx: &mut Context<Self>,
11342    ) {
11343        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11344            cx.propagate();
11345            return;
11346        }
11347
11348        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11349            s.move_with(|map, selection| {
11350                selection.collapse_to(
11351                    movement::start_of_excerpt(
11352                        map,
11353                        selection.head(),
11354                        workspace::searchable::Direction::Next,
11355                    ),
11356                    SelectionGoal::None,
11357                )
11358            });
11359        })
11360    }
11361
11362    pub fn move_to_end_of_excerpt(
11363        &mut self,
11364        _: &MoveToEndOfExcerpt,
11365        window: &mut Window,
11366        cx: &mut Context<Self>,
11367    ) {
11368        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11369            cx.propagate();
11370            return;
11371        }
11372        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11373        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11374            s.move_with(|map, selection| {
11375                selection.collapse_to(
11376                    movement::end_of_excerpt(
11377                        map,
11378                        selection.head(),
11379                        workspace::searchable::Direction::Next,
11380                    ),
11381                    SelectionGoal::None,
11382                )
11383            });
11384        })
11385    }
11386
11387    pub fn move_to_end_of_previous_excerpt(
11388        &mut self,
11389        _: &MoveToEndOfPreviousExcerpt,
11390        window: &mut Window,
11391        cx: &mut Context<Self>,
11392    ) {
11393        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11394            cx.propagate();
11395            return;
11396        }
11397        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11398        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11399            s.move_with(|map, selection| {
11400                selection.collapse_to(
11401                    movement::end_of_excerpt(
11402                        map,
11403                        selection.head(),
11404                        workspace::searchable::Direction::Prev,
11405                    ),
11406                    SelectionGoal::None,
11407                )
11408            });
11409        })
11410    }
11411
11412    pub fn select_to_start_of_excerpt(
11413        &mut self,
11414        _: &SelectToStartOfExcerpt,
11415        window: &mut Window,
11416        cx: &mut Context<Self>,
11417    ) {
11418        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11419            cx.propagate();
11420            return;
11421        }
11422        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11423        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11424            s.move_heads_with(|map, head, _| {
11425                (
11426                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11427                    SelectionGoal::None,
11428                )
11429            });
11430        })
11431    }
11432
11433    pub fn select_to_start_of_next_excerpt(
11434        &mut self,
11435        _: &SelectToStartOfNextExcerpt,
11436        window: &mut Window,
11437        cx: &mut Context<Self>,
11438    ) {
11439        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11440            cx.propagate();
11441            return;
11442        }
11443        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11444        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11445            s.move_heads_with(|map, head, _| {
11446                (
11447                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11448                    SelectionGoal::None,
11449                )
11450            });
11451        })
11452    }
11453
11454    pub fn select_to_end_of_excerpt(
11455        &mut self,
11456        _: &SelectToEndOfExcerpt,
11457        window: &mut Window,
11458        cx: &mut Context<Self>,
11459    ) {
11460        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11461            cx.propagate();
11462            return;
11463        }
11464        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11465        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11466            s.move_heads_with(|map, head, _| {
11467                (
11468                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11469                    SelectionGoal::None,
11470                )
11471            });
11472        })
11473    }
11474
11475    pub fn select_to_end_of_previous_excerpt(
11476        &mut self,
11477        _: &SelectToEndOfPreviousExcerpt,
11478        window: &mut Window,
11479        cx: &mut Context<Self>,
11480    ) {
11481        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11482            cx.propagate();
11483            return;
11484        }
11485        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11486        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11487            s.move_heads_with(|map, head, _| {
11488                (
11489                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11490                    SelectionGoal::None,
11491                )
11492            });
11493        })
11494    }
11495
11496    pub fn move_to_beginning(
11497        &mut self,
11498        _: &MoveToBeginning,
11499        window: &mut Window,
11500        cx: &mut Context<Self>,
11501    ) {
11502        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11503            cx.propagate();
11504            return;
11505        }
11506        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11507        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11508            s.select_ranges(vec![0..0]);
11509        });
11510    }
11511
11512    pub fn select_to_beginning(
11513        &mut self,
11514        _: &SelectToBeginning,
11515        window: &mut Window,
11516        cx: &mut Context<Self>,
11517    ) {
11518        let mut selection = self.selections.last::<Point>(cx);
11519        selection.set_head(Point::zero(), SelectionGoal::None);
11520        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11521        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11522            s.select(vec![selection]);
11523        });
11524    }
11525
11526    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11527        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11528            cx.propagate();
11529            return;
11530        }
11531        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11532        let cursor = self.buffer.read(cx).read(cx).len();
11533        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11534            s.select_ranges(vec![cursor..cursor])
11535        });
11536    }
11537
11538    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11539        self.nav_history = nav_history;
11540    }
11541
11542    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11543        self.nav_history.as_ref()
11544    }
11545
11546    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11547        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11548    }
11549
11550    fn push_to_nav_history(
11551        &mut self,
11552        cursor_anchor: Anchor,
11553        new_position: Option<Point>,
11554        is_deactivate: bool,
11555        cx: &mut Context<Self>,
11556    ) {
11557        if let Some(nav_history) = self.nav_history.as_mut() {
11558            let buffer = self.buffer.read(cx).read(cx);
11559            let cursor_position = cursor_anchor.to_point(&buffer);
11560            let scroll_state = self.scroll_manager.anchor();
11561            let scroll_top_row = scroll_state.top_row(&buffer);
11562            drop(buffer);
11563
11564            if let Some(new_position) = new_position {
11565                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11566                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11567                    return;
11568                }
11569            }
11570
11571            nav_history.push(
11572                Some(NavigationData {
11573                    cursor_anchor,
11574                    cursor_position,
11575                    scroll_anchor: scroll_state,
11576                    scroll_top_row,
11577                }),
11578                cx,
11579            );
11580            cx.emit(EditorEvent::PushedToNavHistory {
11581                anchor: cursor_anchor,
11582                is_deactivate,
11583            })
11584        }
11585    }
11586
11587    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11588        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11589        let buffer = self.buffer.read(cx).snapshot(cx);
11590        let mut selection = self.selections.first::<usize>(cx);
11591        selection.set_head(buffer.len(), SelectionGoal::None);
11592        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11593            s.select(vec![selection]);
11594        });
11595    }
11596
11597    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11598        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11599        let end = self.buffer.read(cx).read(cx).len();
11600        self.change_selections(None, window, cx, |s| {
11601            s.select_ranges(vec![0..end]);
11602        });
11603    }
11604
11605    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11606        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11607        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11608        let mut selections = self.selections.all::<Point>(cx);
11609        let max_point = display_map.buffer_snapshot.max_point();
11610        for selection in &mut selections {
11611            let rows = selection.spanned_rows(true, &display_map);
11612            selection.start = Point::new(rows.start.0, 0);
11613            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11614            selection.reversed = false;
11615        }
11616        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11617            s.select(selections);
11618        });
11619    }
11620
11621    pub fn split_selection_into_lines(
11622        &mut self,
11623        _: &SplitSelectionIntoLines,
11624        window: &mut Window,
11625        cx: &mut Context<Self>,
11626    ) {
11627        let selections = self
11628            .selections
11629            .all::<Point>(cx)
11630            .into_iter()
11631            .map(|selection| selection.start..selection.end)
11632            .collect::<Vec<_>>();
11633        self.unfold_ranges(&selections, true, true, cx);
11634
11635        let mut new_selection_ranges = Vec::new();
11636        {
11637            let buffer = self.buffer.read(cx).read(cx);
11638            for selection in selections {
11639                for row in selection.start.row..selection.end.row {
11640                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11641                    new_selection_ranges.push(cursor..cursor);
11642                }
11643
11644                let is_multiline_selection = selection.start.row != selection.end.row;
11645                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11646                // so this action feels more ergonomic when paired with other selection operations
11647                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11648                if !should_skip_last {
11649                    new_selection_ranges.push(selection.end..selection.end);
11650                }
11651            }
11652        }
11653        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11654            s.select_ranges(new_selection_ranges);
11655        });
11656    }
11657
11658    pub fn add_selection_above(
11659        &mut self,
11660        _: &AddSelectionAbove,
11661        window: &mut Window,
11662        cx: &mut Context<Self>,
11663    ) {
11664        self.add_selection(true, window, cx);
11665    }
11666
11667    pub fn add_selection_below(
11668        &mut self,
11669        _: &AddSelectionBelow,
11670        window: &mut Window,
11671        cx: &mut Context<Self>,
11672    ) {
11673        self.add_selection(false, window, cx);
11674    }
11675
11676    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11677        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11678
11679        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11680        let mut selections = self.selections.all::<Point>(cx);
11681        let text_layout_details = self.text_layout_details(window);
11682        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11683            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11684            let range = oldest_selection.display_range(&display_map).sorted();
11685
11686            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11687            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11688            let positions = start_x.min(end_x)..start_x.max(end_x);
11689
11690            selections.clear();
11691            let mut stack = Vec::new();
11692            for row in range.start.row().0..=range.end.row().0 {
11693                if let Some(selection) = self.selections.build_columnar_selection(
11694                    &display_map,
11695                    DisplayRow(row),
11696                    &positions,
11697                    oldest_selection.reversed,
11698                    &text_layout_details,
11699                ) {
11700                    stack.push(selection.id);
11701                    selections.push(selection);
11702                }
11703            }
11704
11705            if above {
11706                stack.reverse();
11707            }
11708
11709            AddSelectionsState { above, stack }
11710        });
11711
11712        let last_added_selection = *state.stack.last().unwrap();
11713        let mut new_selections = Vec::new();
11714        if above == state.above {
11715            let end_row = if above {
11716                DisplayRow(0)
11717            } else {
11718                display_map.max_point().row()
11719            };
11720
11721            'outer: for selection in selections {
11722                if selection.id == last_added_selection {
11723                    let range = selection.display_range(&display_map).sorted();
11724                    debug_assert_eq!(range.start.row(), range.end.row());
11725                    let mut row = range.start.row();
11726                    let positions =
11727                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11728                            px(start)..px(end)
11729                        } else {
11730                            let start_x =
11731                                display_map.x_for_display_point(range.start, &text_layout_details);
11732                            let end_x =
11733                                display_map.x_for_display_point(range.end, &text_layout_details);
11734                            start_x.min(end_x)..start_x.max(end_x)
11735                        };
11736
11737                    while row != end_row {
11738                        if above {
11739                            row.0 -= 1;
11740                        } else {
11741                            row.0 += 1;
11742                        }
11743
11744                        if let Some(new_selection) = self.selections.build_columnar_selection(
11745                            &display_map,
11746                            row,
11747                            &positions,
11748                            selection.reversed,
11749                            &text_layout_details,
11750                        ) {
11751                            state.stack.push(new_selection.id);
11752                            if above {
11753                                new_selections.push(new_selection);
11754                                new_selections.push(selection);
11755                            } else {
11756                                new_selections.push(selection);
11757                                new_selections.push(new_selection);
11758                            }
11759
11760                            continue 'outer;
11761                        }
11762                    }
11763                }
11764
11765                new_selections.push(selection);
11766            }
11767        } else {
11768            new_selections = selections;
11769            new_selections.retain(|s| s.id != last_added_selection);
11770            state.stack.pop();
11771        }
11772
11773        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11774            s.select(new_selections);
11775        });
11776        if state.stack.len() > 1 {
11777            self.add_selections_state = Some(state);
11778        }
11779    }
11780
11781    pub fn select_next_match_internal(
11782        &mut self,
11783        display_map: &DisplaySnapshot,
11784        replace_newest: bool,
11785        autoscroll: Option<Autoscroll>,
11786        window: &mut Window,
11787        cx: &mut Context<Self>,
11788    ) -> Result<()> {
11789        fn select_next_match_ranges(
11790            this: &mut Editor,
11791            range: Range<usize>,
11792            replace_newest: bool,
11793            auto_scroll: Option<Autoscroll>,
11794            window: &mut Window,
11795            cx: &mut Context<Editor>,
11796        ) {
11797            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11798            this.change_selections(auto_scroll, window, cx, |s| {
11799                if replace_newest {
11800                    s.delete(s.newest_anchor().id);
11801                }
11802                s.insert_range(range.clone());
11803            });
11804        }
11805
11806        let buffer = &display_map.buffer_snapshot;
11807        let mut selections = self.selections.all::<usize>(cx);
11808        if let Some(mut select_next_state) = self.select_next_state.take() {
11809            let query = &select_next_state.query;
11810            if !select_next_state.done {
11811                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11812                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11813                let mut next_selected_range = None;
11814
11815                let bytes_after_last_selection =
11816                    buffer.bytes_in_range(last_selection.end..buffer.len());
11817                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11818                let query_matches = query
11819                    .stream_find_iter(bytes_after_last_selection)
11820                    .map(|result| (last_selection.end, result))
11821                    .chain(
11822                        query
11823                            .stream_find_iter(bytes_before_first_selection)
11824                            .map(|result| (0, result)),
11825                    );
11826
11827                for (start_offset, query_match) in query_matches {
11828                    let query_match = query_match.unwrap(); // can only fail due to I/O
11829                    let offset_range =
11830                        start_offset + query_match.start()..start_offset + query_match.end();
11831                    let display_range = offset_range.start.to_display_point(display_map)
11832                        ..offset_range.end.to_display_point(display_map);
11833
11834                    if !select_next_state.wordwise
11835                        || (!movement::is_inside_word(display_map, display_range.start)
11836                            && !movement::is_inside_word(display_map, display_range.end))
11837                    {
11838                        // TODO: This is n^2, because we might check all the selections
11839                        if !selections
11840                            .iter()
11841                            .any(|selection| selection.range().overlaps(&offset_range))
11842                        {
11843                            next_selected_range = Some(offset_range);
11844                            break;
11845                        }
11846                    }
11847                }
11848
11849                if let Some(next_selected_range) = next_selected_range {
11850                    select_next_match_ranges(
11851                        self,
11852                        next_selected_range,
11853                        replace_newest,
11854                        autoscroll,
11855                        window,
11856                        cx,
11857                    );
11858                } else {
11859                    select_next_state.done = true;
11860                }
11861            }
11862
11863            self.select_next_state = Some(select_next_state);
11864        } else {
11865            let mut only_carets = true;
11866            let mut same_text_selected = true;
11867            let mut selected_text = None;
11868
11869            let mut selections_iter = selections.iter().peekable();
11870            while let Some(selection) = selections_iter.next() {
11871                if selection.start != selection.end {
11872                    only_carets = false;
11873                }
11874
11875                if same_text_selected {
11876                    if selected_text.is_none() {
11877                        selected_text =
11878                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11879                    }
11880
11881                    if let Some(next_selection) = selections_iter.peek() {
11882                        if next_selection.range().len() == selection.range().len() {
11883                            let next_selected_text = buffer
11884                                .text_for_range(next_selection.range())
11885                                .collect::<String>();
11886                            if Some(next_selected_text) != selected_text {
11887                                same_text_selected = false;
11888                                selected_text = None;
11889                            }
11890                        } else {
11891                            same_text_selected = false;
11892                            selected_text = None;
11893                        }
11894                    }
11895                }
11896            }
11897
11898            if only_carets {
11899                for selection in &mut selections {
11900                    let word_range = movement::surrounding_word(
11901                        display_map,
11902                        selection.start.to_display_point(display_map),
11903                    );
11904                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11905                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11906                    selection.goal = SelectionGoal::None;
11907                    selection.reversed = false;
11908                    select_next_match_ranges(
11909                        self,
11910                        selection.start..selection.end,
11911                        replace_newest,
11912                        autoscroll,
11913                        window,
11914                        cx,
11915                    );
11916                }
11917
11918                if selections.len() == 1 {
11919                    let selection = selections
11920                        .last()
11921                        .expect("ensured that there's only one selection");
11922                    let query = buffer
11923                        .text_for_range(selection.start..selection.end)
11924                        .collect::<String>();
11925                    let is_empty = query.is_empty();
11926                    let select_state = SelectNextState {
11927                        query: AhoCorasick::new(&[query])?,
11928                        wordwise: true,
11929                        done: is_empty,
11930                    };
11931                    self.select_next_state = Some(select_state);
11932                } else {
11933                    self.select_next_state = None;
11934                }
11935            } else if let Some(selected_text) = selected_text {
11936                self.select_next_state = Some(SelectNextState {
11937                    query: AhoCorasick::new(&[selected_text])?,
11938                    wordwise: false,
11939                    done: false,
11940                });
11941                self.select_next_match_internal(
11942                    display_map,
11943                    replace_newest,
11944                    autoscroll,
11945                    window,
11946                    cx,
11947                )?;
11948            }
11949        }
11950        Ok(())
11951    }
11952
11953    pub fn select_all_matches(
11954        &mut self,
11955        _action: &SelectAllMatches,
11956        window: &mut Window,
11957        cx: &mut Context<Self>,
11958    ) -> Result<()> {
11959        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11960
11961        self.push_to_selection_history();
11962        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11963
11964        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11965        let Some(select_next_state) = self.select_next_state.as_mut() else {
11966            return Ok(());
11967        };
11968        if select_next_state.done {
11969            return Ok(());
11970        }
11971
11972        let mut new_selections = Vec::new();
11973
11974        let reversed = self.selections.oldest::<usize>(cx).reversed;
11975        let buffer = &display_map.buffer_snapshot;
11976        let query_matches = select_next_state
11977            .query
11978            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11979
11980        for query_match in query_matches.into_iter() {
11981            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11982            let offset_range = if reversed {
11983                query_match.end()..query_match.start()
11984            } else {
11985                query_match.start()..query_match.end()
11986            };
11987            let display_range = offset_range.start.to_display_point(&display_map)
11988                ..offset_range.end.to_display_point(&display_map);
11989
11990            if !select_next_state.wordwise
11991                || (!movement::is_inside_word(&display_map, display_range.start)
11992                    && !movement::is_inside_word(&display_map, display_range.end))
11993            {
11994                new_selections.push(offset_range.start..offset_range.end);
11995            }
11996        }
11997
11998        select_next_state.done = true;
11999        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12000        self.change_selections(None, window, cx, |selections| {
12001            selections.select_ranges(new_selections)
12002        });
12003
12004        Ok(())
12005    }
12006
12007    pub fn select_next(
12008        &mut self,
12009        action: &SelectNext,
12010        window: &mut Window,
12011        cx: &mut Context<Self>,
12012    ) -> Result<()> {
12013        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12014        self.push_to_selection_history();
12015        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12016        self.select_next_match_internal(
12017            &display_map,
12018            action.replace_newest,
12019            Some(Autoscroll::newest()),
12020            window,
12021            cx,
12022        )?;
12023        Ok(())
12024    }
12025
12026    pub fn select_previous(
12027        &mut self,
12028        action: &SelectPrevious,
12029        window: &mut Window,
12030        cx: &mut Context<Self>,
12031    ) -> Result<()> {
12032        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12033        self.push_to_selection_history();
12034        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12035        let buffer = &display_map.buffer_snapshot;
12036        let mut selections = self.selections.all::<usize>(cx);
12037        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12038            let query = &select_prev_state.query;
12039            if !select_prev_state.done {
12040                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12041                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12042                let mut next_selected_range = None;
12043                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12044                let bytes_before_last_selection =
12045                    buffer.reversed_bytes_in_range(0..last_selection.start);
12046                let bytes_after_first_selection =
12047                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12048                let query_matches = query
12049                    .stream_find_iter(bytes_before_last_selection)
12050                    .map(|result| (last_selection.start, result))
12051                    .chain(
12052                        query
12053                            .stream_find_iter(bytes_after_first_selection)
12054                            .map(|result| (buffer.len(), result)),
12055                    );
12056                for (end_offset, query_match) in query_matches {
12057                    let query_match = query_match.unwrap(); // can only fail due to I/O
12058                    let offset_range =
12059                        end_offset - query_match.end()..end_offset - query_match.start();
12060                    let display_range = offset_range.start.to_display_point(&display_map)
12061                        ..offset_range.end.to_display_point(&display_map);
12062
12063                    if !select_prev_state.wordwise
12064                        || (!movement::is_inside_word(&display_map, display_range.start)
12065                            && !movement::is_inside_word(&display_map, display_range.end))
12066                    {
12067                        next_selected_range = Some(offset_range);
12068                        break;
12069                    }
12070                }
12071
12072                if let Some(next_selected_range) = next_selected_range {
12073                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12074                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12075                        if action.replace_newest {
12076                            s.delete(s.newest_anchor().id);
12077                        }
12078                        s.insert_range(next_selected_range);
12079                    });
12080                } else {
12081                    select_prev_state.done = true;
12082                }
12083            }
12084
12085            self.select_prev_state = Some(select_prev_state);
12086        } else {
12087            let mut only_carets = true;
12088            let mut same_text_selected = true;
12089            let mut selected_text = None;
12090
12091            let mut selections_iter = selections.iter().peekable();
12092            while let Some(selection) = selections_iter.next() {
12093                if selection.start != selection.end {
12094                    only_carets = false;
12095                }
12096
12097                if same_text_selected {
12098                    if selected_text.is_none() {
12099                        selected_text =
12100                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12101                    }
12102
12103                    if let Some(next_selection) = selections_iter.peek() {
12104                        if next_selection.range().len() == selection.range().len() {
12105                            let next_selected_text = buffer
12106                                .text_for_range(next_selection.range())
12107                                .collect::<String>();
12108                            if Some(next_selected_text) != selected_text {
12109                                same_text_selected = false;
12110                                selected_text = None;
12111                            }
12112                        } else {
12113                            same_text_selected = false;
12114                            selected_text = None;
12115                        }
12116                    }
12117                }
12118            }
12119
12120            if only_carets {
12121                for selection in &mut selections {
12122                    let word_range = movement::surrounding_word(
12123                        &display_map,
12124                        selection.start.to_display_point(&display_map),
12125                    );
12126                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12127                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12128                    selection.goal = SelectionGoal::None;
12129                    selection.reversed = false;
12130                }
12131                if selections.len() == 1 {
12132                    let selection = selections
12133                        .last()
12134                        .expect("ensured that there's only one selection");
12135                    let query = buffer
12136                        .text_for_range(selection.start..selection.end)
12137                        .collect::<String>();
12138                    let is_empty = query.is_empty();
12139                    let select_state = SelectNextState {
12140                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12141                        wordwise: true,
12142                        done: is_empty,
12143                    };
12144                    self.select_prev_state = Some(select_state);
12145                } else {
12146                    self.select_prev_state = None;
12147                }
12148
12149                self.unfold_ranges(
12150                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12151                    false,
12152                    true,
12153                    cx,
12154                );
12155                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12156                    s.select(selections);
12157                });
12158            } else if let Some(selected_text) = selected_text {
12159                self.select_prev_state = Some(SelectNextState {
12160                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12161                    wordwise: false,
12162                    done: false,
12163                });
12164                self.select_previous(action, window, cx)?;
12165            }
12166        }
12167        Ok(())
12168    }
12169
12170    pub fn find_next_match(
12171        &mut self,
12172        _: &FindNextMatch,
12173        window: &mut Window,
12174        cx: &mut Context<Self>,
12175    ) -> Result<()> {
12176        let selections = self.selections.disjoint_anchors();
12177        match selections.first() {
12178            Some(first) if selections.len() >= 2 => {
12179                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12180                    s.select_ranges([first.range()]);
12181                });
12182            }
12183            _ => self.select_next(
12184                &SelectNext {
12185                    replace_newest: true,
12186                },
12187                window,
12188                cx,
12189            )?,
12190        }
12191        Ok(())
12192    }
12193
12194    pub fn find_previous_match(
12195        &mut self,
12196        _: &FindPreviousMatch,
12197        window: &mut Window,
12198        cx: &mut Context<Self>,
12199    ) -> Result<()> {
12200        let selections = self.selections.disjoint_anchors();
12201        match selections.last() {
12202            Some(last) if selections.len() >= 2 => {
12203                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12204                    s.select_ranges([last.range()]);
12205                });
12206            }
12207            _ => self.select_previous(
12208                &SelectPrevious {
12209                    replace_newest: true,
12210                },
12211                window,
12212                cx,
12213            )?,
12214        }
12215        Ok(())
12216    }
12217
12218    pub fn toggle_comments(
12219        &mut self,
12220        action: &ToggleComments,
12221        window: &mut Window,
12222        cx: &mut Context<Self>,
12223    ) {
12224        if self.read_only(cx) {
12225            return;
12226        }
12227        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12228        let text_layout_details = &self.text_layout_details(window);
12229        self.transact(window, cx, |this, window, cx| {
12230            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12231            let mut edits = Vec::new();
12232            let mut selection_edit_ranges = Vec::new();
12233            let mut last_toggled_row = None;
12234            let snapshot = this.buffer.read(cx).read(cx);
12235            let empty_str: Arc<str> = Arc::default();
12236            let mut suffixes_inserted = Vec::new();
12237            let ignore_indent = action.ignore_indent;
12238
12239            fn comment_prefix_range(
12240                snapshot: &MultiBufferSnapshot,
12241                row: MultiBufferRow,
12242                comment_prefix: &str,
12243                comment_prefix_whitespace: &str,
12244                ignore_indent: bool,
12245            ) -> Range<Point> {
12246                let indent_size = if ignore_indent {
12247                    0
12248                } else {
12249                    snapshot.indent_size_for_line(row).len
12250                };
12251
12252                let start = Point::new(row.0, indent_size);
12253
12254                let mut line_bytes = snapshot
12255                    .bytes_in_range(start..snapshot.max_point())
12256                    .flatten()
12257                    .copied();
12258
12259                // If this line currently begins with the line comment prefix, then record
12260                // the range containing the prefix.
12261                if line_bytes
12262                    .by_ref()
12263                    .take(comment_prefix.len())
12264                    .eq(comment_prefix.bytes())
12265                {
12266                    // Include any whitespace that matches the comment prefix.
12267                    let matching_whitespace_len = line_bytes
12268                        .zip(comment_prefix_whitespace.bytes())
12269                        .take_while(|(a, b)| a == b)
12270                        .count() as u32;
12271                    let end = Point::new(
12272                        start.row,
12273                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12274                    );
12275                    start..end
12276                } else {
12277                    start..start
12278                }
12279            }
12280
12281            fn comment_suffix_range(
12282                snapshot: &MultiBufferSnapshot,
12283                row: MultiBufferRow,
12284                comment_suffix: &str,
12285                comment_suffix_has_leading_space: bool,
12286            ) -> Range<Point> {
12287                let end = Point::new(row.0, snapshot.line_len(row));
12288                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12289
12290                let mut line_end_bytes = snapshot
12291                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12292                    .flatten()
12293                    .copied();
12294
12295                let leading_space_len = if suffix_start_column > 0
12296                    && line_end_bytes.next() == Some(b' ')
12297                    && comment_suffix_has_leading_space
12298                {
12299                    1
12300                } else {
12301                    0
12302                };
12303
12304                // If this line currently begins with the line comment prefix, then record
12305                // the range containing the prefix.
12306                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12307                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12308                    start..end
12309                } else {
12310                    end..end
12311                }
12312            }
12313
12314            // TODO: Handle selections that cross excerpts
12315            for selection in &mut selections {
12316                let start_column = snapshot
12317                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12318                    .len;
12319                let language = if let Some(language) =
12320                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12321                {
12322                    language
12323                } else {
12324                    continue;
12325                };
12326
12327                selection_edit_ranges.clear();
12328
12329                // If multiple selections contain a given row, avoid processing that
12330                // row more than once.
12331                let mut start_row = MultiBufferRow(selection.start.row);
12332                if last_toggled_row == Some(start_row) {
12333                    start_row = start_row.next_row();
12334                }
12335                let end_row =
12336                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12337                        MultiBufferRow(selection.end.row - 1)
12338                    } else {
12339                        MultiBufferRow(selection.end.row)
12340                    };
12341                last_toggled_row = Some(end_row);
12342
12343                if start_row > end_row {
12344                    continue;
12345                }
12346
12347                // If the language has line comments, toggle those.
12348                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12349
12350                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12351                if ignore_indent {
12352                    full_comment_prefixes = full_comment_prefixes
12353                        .into_iter()
12354                        .map(|s| Arc::from(s.trim_end()))
12355                        .collect();
12356                }
12357
12358                if !full_comment_prefixes.is_empty() {
12359                    let first_prefix = full_comment_prefixes
12360                        .first()
12361                        .expect("prefixes is non-empty");
12362                    let prefix_trimmed_lengths = full_comment_prefixes
12363                        .iter()
12364                        .map(|p| p.trim_end_matches(' ').len())
12365                        .collect::<SmallVec<[usize; 4]>>();
12366
12367                    let mut all_selection_lines_are_comments = true;
12368
12369                    for row in start_row.0..=end_row.0 {
12370                        let row = MultiBufferRow(row);
12371                        if start_row < end_row && snapshot.is_line_blank(row) {
12372                            continue;
12373                        }
12374
12375                        let prefix_range = full_comment_prefixes
12376                            .iter()
12377                            .zip(prefix_trimmed_lengths.iter().copied())
12378                            .map(|(prefix, trimmed_prefix_len)| {
12379                                comment_prefix_range(
12380                                    snapshot.deref(),
12381                                    row,
12382                                    &prefix[..trimmed_prefix_len],
12383                                    &prefix[trimmed_prefix_len..],
12384                                    ignore_indent,
12385                                )
12386                            })
12387                            .max_by_key(|range| range.end.column - range.start.column)
12388                            .expect("prefixes is non-empty");
12389
12390                        if prefix_range.is_empty() {
12391                            all_selection_lines_are_comments = false;
12392                        }
12393
12394                        selection_edit_ranges.push(prefix_range);
12395                    }
12396
12397                    if all_selection_lines_are_comments {
12398                        edits.extend(
12399                            selection_edit_ranges
12400                                .iter()
12401                                .cloned()
12402                                .map(|range| (range, empty_str.clone())),
12403                        );
12404                    } else {
12405                        let min_column = selection_edit_ranges
12406                            .iter()
12407                            .map(|range| range.start.column)
12408                            .min()
12409                            .unwrap_or(0);
12410                        edits.extend(selection_edit_ranges.iter().map(|range| {
12411                            let position = Point::new(range.start.row, min_column);
12412                            (position..position, first_prefix.clone())
12413                        }));
12414                    }
12415                } else if let Some((full_comment_prefix, comment_suffix)) =
12416                    language.block_comment_delimiters()
12417                {
12418                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12419                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12420                    let prefix_range = comment_prefix_range(
12421                        snapshot.deref(),
12422                        start_row,
12423                        comment_prefix,
12424                        comment_prefix_whitespace,
12425                        ignore_indent,
12426                    );
12427                    let suffix_range = comment_suffix_range(
12428                        snapshot.deref(),
12429                        end_row,
12430                        comment_suffix.trim_start_matches(' '),
12431                        comment_suffix.starts_with(' '),
12432                    );
12433
12434                    if prefix_range.is_empty() || suffix_range.is_empty() {
12435                        edits.push((
12436                            prefix_range.start..prefix_range.start,
12437                            full_comment_prefix.clone(),
12438                        ));
12439                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12440                        suffixes_inserted.push((end_row, comment_suffix.len()));
12441                    } else {
12442                        edits.push((prefix_range, empty_str.clone()));
12443                        edits.push((suffix_range, empty_str.clone()));
12444                    }
12445                } else {
12446                    continue;
12447                }
12448            }
12449
12450            drop(snapshot);
12451            this.buffer.update(cx, |buffer, cx| {
12452                buffer.edit(edits, None, cx);
12453            });
12454
12455            // Adjust selections so that they end before any comment suffixes that
12456            // were inserted.
12457            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12458            let mut selections = this.selections.all::<Point>(cx);
12459            let snapshot = this.buffer.read(cx).read(cx);
12460            for selection in &mut selections {
12461                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12462                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12463                        Ordering::Less => {
12464                            suffixes_inserted.next();
12465                            continue;
12466                        }
12467                        Ordering::Greater => break,
12468                        Ordering::Equal => {
12469                            if selection.end.column == snapshot.line_len(row) {
12470                                if selection.is_empty() {
12471                                    selection.start.column -= suffix_len as u32;
12472                                }
12473                                selection.end.column -= suffix_len as u32;
12474                            }
12475                            break;
12476                        }
12477                    }
12478                }
12479            }
12480
12481            drop(snapshot);
12482            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12483                s.select(selections)
12484            });
12485
12486            let selections = this.selections.all::<Point>(cx);
12487            let selections_on_single_row = selections.windows(2).all(|selections| {
12488                selections[0].start.row == selections[1].start.row
12489                    && selections[0].end.row == selections[1].end.row
12490                    && selections[0].start.row == selections[0].end.row
12491            });
12492            let selections_selecting = selections
12493                .iter()
12494                .any(|selection| selection.start != selection.end);
12495            let advance_downwards = action.advance_downwards
12496                && selections_on_single_row
12497                && !selections_selecting
12498                && !matches!(this.mode, EditorMode::SingleLine { .. });
12499
12500            if advance_downwards {
12501                let snapshot = this.buffer.read(cx).snapshot(cx);
12502
12503                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12504                    s.move_cursors_with(|display_snapshot, display_point, _| {
12505                        let mut point = display_point.to_point(display_snapshot);
12506                        point.row += 1;
12507                        point = snapshot.clip_point(point, Bias::Left);
12508                        let display_point = point.to_display_point(display_snapshot);
12509                        let goal = SelectionGoal::HorizontalPosition(
12510                            display_snapshot
12511                                .x_for_display_point(display_point, text_layout_details)
12512                                .into(),
12513                        );
12514                        (display_point, goal)
12515                    })
12516                });
12517            }
12518        });
12519    }
12520
12521    pub fn select_enclosing_symbol(
12522        &mut self,
12523        _: &SelectEnclosingSymbol,
12524        window: &mut Window,
12525        cx: &mut Context<Self>,
12526    ) {
12527        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12528
12529        let buffer = self.buffer.read(cx).snapshot(cx);
12530        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12531
12532        fn update_selection(
12533            selection: &Selection<usize>,
12534            buffer_snap: &MultiBufferSnapshot,
12535        ) -> Option<Selection<usize>> {
12536            let cursor = selection.head();
12537            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12538            for symbol in symbols.iter().rev() {
12539                let start = symbol.range.start.to_offset(buffer_snap);
12540                let end = symbol.range.end.to_offset(buffer_snap);
12541                let new_range = start..end;
12542                if start < selection.start || end > selection.end {
12543                    return Some(Selection {
12544                        id: selection.id,
12545                        start: new_range.start,
12546                        end: new_range.end,
12547                        goal: SelectionGoal::None,
12548                        reversed: selection.reversed,
12549                    });
12550                }
12551            }
12552            None
12553        }
12554
12555        let mut selected_larger_symbol = false;
12556        let new_selections = old_selections
12557            .iter()
12558            .map(|selection| match update_selection(selection, &buffer) {
12559                Some(new_selection) => {
12560                    if new_selection.range() != selection.range() {
12561                        selected_larger_symbol = true;
12562                    }
12563                    new_selection
12564                }
12565                None => selection.clone(),
12566            })
12567            .collect::<Vec<_>>();
12568
12569        if selected_larger_symbol {
12570            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12571                s.select(new_selections);
12572            });
12573        }
12574    }
12575
12576    pub fn select_larger_syntax_node(
12577        &mut self,
12578        _: &SelectLargerSyntaxNode,
12579        window: &mut Window,
12580        cx: &mut Context<Self>,
12581    ) {
12582        let Some(visible_row_count) = self.visible_row_count() else {
12583            return;
12584        };
12585        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12586        if old_selections.is_empty() {
12587            return;
12588        }
12589
12590        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12591
12592        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12593        let buffer = self.buffer.read(cx).snapshot(cx);
12594
12595        let mut selected_larger_node = false;
12596        let mut new_selections = old_selections
12597            .iter()
12598            .map(|selection| {
12599                let old_range = selection.start..selection.end;
12600
12601                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12602                    // manually select word at selection
12603                    if ["string_content", "inline"].contains(&node.kind()) {
12604                        let word_range = {
12605                            let display_point = buffer
12606                                .offset_to_point(old_range.start)
12607                                .to_display_point(&display_map);
12608                            let Range { start, end } =
12609                                movement::surrounding_word(&display_map, display_point);
12610                            start.to_point(&display_map).to_offset(&buffer)
12611                                ..end.to_point(&display_map).to_offset(&buffer)
12612                        };
12613                        // ignore if word is already selected
12614                        if !word_range.is_empty() && old_range != word_range {
12615                            let last_word_range = {
12616                                let display_point = buffer
12617                                    .offset_to_point(old_range.end)
12618                                    .to_display_point(&display_map);
12619                                let Range { start, end } =
12620                                    movement::surrounding_word(&display_map, display_point);
12621                                start.to_point(&display_map).to_offset(&buffer)
12622                                    ..end.to_point(&display_map).to_offset(&buffer)
12623                            };
12624                            // only select word if start and end point belongs to same word
12625                            if word_range == last_word_range {
12626                                selected_larger_node = true;
12627                                return Selection {
12628                                    id: selection.id,
12629                                    start: word_range.start,
12630                                    end: word_range.end,
12631                                    goal: SelectionGoal::None,
12632                                    reversed: selection.reversed,
12633                                };
12634                            }
12635                        }
12636                    }
12637                }
12638
12639                let mut new_range = old_range.clone();
12640                let mut new_node = None;
12641                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12642                {
12643                    new_node = Some(node);
12644                    new_range = match containing_range {
12645                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12646                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12647                    };
12648                    if !display_map.intersects_fold(new_range.start)
12649                        && !display_map.intersects_fold(new_range.end)
12650                    {
12651                        break;
12652                    }
12653                }
12654
12655                if let Some(node) = new_node {
12656                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12657                    // nodes. Parent and grandparent are also logged because this operation will not
12658                    // visit nodes that have the same range as their parent.
12659                    log::info!("Node: {node:?}");
12660                    let parent = node.parent();
12661                    log::info!("Parent: {parent:?}");
12662                    let grandparent = parent.and_then(|x| x.parent());
12663                    log::info!("Grandparent: {grandparent:?}");
12664                }
12665
12666                selected_larger_node |= new_range != old_range;
12667                Selection {
12668                    id: selection.id,
12669                    start: new_range.start,
12670                    end: new_range.end,
12671                    goal: SelectionGoal::None,
12672                    reversed: selection.reversed,
12673                }
12674            })
12675            .collect::<Vec<_>>();
12676
12677        if !selected_larger_node {
12678            return; // don't put this call in the history
12679        }
12680
12681        // scroll based on transformation done to the last selection created by the user
12682        let (last_old, last_new) = old_selections
12683            .last()
12684            .zip(new_selections.last().cloned())
12685            .expect("old_selections isn't empty");
12686
12687        // revert selection
12688        let is_selection_reversed = {
12689            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12690            new_selections.last_mut().expect("checked above").reversed =
12691                should_newest_selection_be_reversed;
12692            should_newest_selection_be_reversed
12693        };
12694
12695        if selected_larger_node {
12696            self.select_syntax_node_history.disable_clearing = true;
12697            self.change_selections(None, window, cx, |s| {
12698                s.select(new_selections.clone());
12699            });
12700            self.select_syntax_node_history.disable_clearing = false;
12701        }
12702
12703        let start_row = last_new.start.to_display_point(&display_map).row().0;
12704        let end_row = last_new.end.to_display_point(&display_map).row().0;
12705        let selection_height = end_row - start_row + 1;
12706        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12707
12708        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12709        let scroll_behavior = if fits_on_the_screen {
12710            self.request_autoscroll(Autoscroll::fit(), cx);
12711            SelectSyntaxNodeScrollBehavior::FitSelection
12712        } else if is_selection_reversed {
12713            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12714            SelectSyntaxNodeScrollBehavior::CursorTop
12715        } else {
12716            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12717            SelectSyntaxNodeScrollBehavior::CursorBottom
12718        };
12719
12720        self.select_syntax_node_history.push((
12721            old_selections,
12722            scroll_behavior,
12723            is_selection_reversed,
12724        ));
12725    }
12726
12727    pub fn select_smaller_syntax_node(
12728        &mut self,
12729        _: &SelectSmallerSyntaxNode,
12730        window: &mut Window,
12731        cx: &mut Context<Self>,
12732    ) {
12733        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12734
12735        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12736            self.select_syntax_node_history.pop()
12737        {
12738            if let Some(selection) = selections.last_mut() {
12739                selection.reversed = is_selection_reversed;
12740            }
12741
12742            self.select_syntax_node_history.disable_clearing = true;
12743            self.change_selections(None, window, cx, |s| {
12744                s.select(selections.to_vec());
12745            });
12746            self.select_syntax_node_history.disable_clearing = false;
12747
12748            match scroll_behavior {
12749                SelectSyntaxNodeScrollBehavior::CursorTop => {
12750                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12751                }
12752                SelectSyntaxNodeScrollBehavior::FitSelection => {
12753                    self.request_autoscroll(Autoscroll::fit(), cx);
12754                }
12755                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12756                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12757                }
12758            }
12759        }
12760    }
12761
12762    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12763        if !EditorSettings::get_global(cx).gutter.runnables {
12764            self.clear_tasks();
12765            return Task::ready(());
12766        }
12767        let project = self.project.as_ref().map(Entity::downgrade);
12768        let task_sources = self.lsp_task_sources(cx);
12769        cx.spawn_in(window, async move |editor, cx| {
12770            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12771            let Some(project) = project.and_then(|p| p.upgrade()) else {
12772                return;
12773            };
12774            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12775                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12776            }) else {
12777                return;
12778            };
12779
12780            let hide_runnables = project
12781                .update(cx, |project, cx| {
12782                    // Do not display any test indicators in non-dev server remote projects.
12783                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12784                })
12785                .unwrap_or(true);
12786            if hide_runnables {
12787                return;
12788            }
12789            let new_rows =
12790                cx.background_spawn({
12791                    let snapshot = display_snapshot.clone();
12792                    async move {
12793                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12794                    }
12795                })
12796                    .await;
12797            let Ok(lsp_tasks) =
12798                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12799            else {
12800                return;
12801            };
12802            let lsp_tasks = lsp_tasks.await;
12803
12804            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12805                lsp_tasks
12806                    .into_iter()
12807                    .flat_map(|(kind, tasks)| {
12808                        tasks.into_iter().filter_map(move |(location, task)| {
12809                            Some((kind.clone(), location?, task))
12810                        })
12811                    })
12812                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12813                        let buffer = location.target.buffer;
12814                        let buffer_snapshot = buffer.read(cx).snapshot();
12815                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12816                            |(excerpt_id, snapshot, _)| {
12817                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
12818                                    display_snapshot
12819                                        .buffer_snapshot
12820                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
12821                                } else {
12822                                    None
12823                                }
12824                            },
12825                        );
12826                        if let Some(offset) = offset {
12827                            let task_buffer_range =
12828                                location.target.range.to_point(&buffer_snapshot);
12829                            let context_buffer_range =
12830                                task_buffer_range.to_offset(&buffer_snapshot);
12831                            let context_range = BufferOffset(context_buffer_range.start)
12832                                ..BufferOffset(context_buffer_range.end);
12833
12834                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12835                                .or_insert_with(|| RunnableTasks {
12836                                    templates: Vec::new(),
12837                                    offset,
12838                                    column: task_buffer_range.start.column,
12839                                    extra_variables: HashMap::default(),
12840                                    context_range,
12841                                })
12842                                .templates
12843                                .push((kind, task.original_task().clone()));
12844                        }
12845
12846                        acc
12847                    })
12848            }) else {
12849                return;
12850            };
12851
12852            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12853            editor
12854                .update(cx, |editor, _| {
12855                    editor.clear_tasks();
12856                    for (key, mut value) in rows {
12857                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12858                            value.templates.extend(lsp_tasks.templates);
12859                        }
12860
12861                        editor.insert_tasks(key, value);
12862                    }
12863                    for (key, value) in lsp_tasks_by_rows {
12864                        editor.insert_tasks(key, value);
12865                    }
12866                })
12867                .ok();
12868        })
12869    }
12870    fn fetch_runnable_ranges(
12871        snapshot: &DisplaySnapshot,
12872        range: Range<Anchor>,
12873    ) -> Vec<language::RunnableRange> {
12874        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12875    }
12876
12877    fn runnable_rows(
12878        project: Entity<Project>,
12879        snapshot: DisplaySnapshot,
12880        runnable_ranges: Vec<RunnableRange>,
12881        mut cx: AsyncWindowContext,
12882    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12883        runnable_ranges
12884            .into_iter()
12885            .filter_map(|mut runnable| {
12886                let tasks = cx
12887                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12888                    .ok()?;
12889                if tasks.is_empty() {
12890                    return None;
12891                }
12892
12893                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12894
12895                let row = snapshot
12896                    .buffer_snapshot
12897                    .buffer_line_for_row(MultiBufferRow(point.row))?
12898                    .1
12899                    .start
12900                    .row;
12901
12902                let context_range =
12903                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12904                Some((
12905                    (runnable.buffer_id, row),
12906                    RunnableTasks {
12907                        templates: tasks,
12908                        offset: snapshot
12909                            .buffer_snapshot
12910                            .anchor_before(runnable.run_range.start),
12911                        context_range,
12912                        column: point.column,
12913                        extra_variables: runnable.extra_captures,
12914                    },
12915                ))
12916            })
12917            .collect()
12918    }
12919
12920    fn templates_with_tags(
12921        project: &Entity<Project>,
12922        runnable: &mut Runnable,
12923        cx: &mut App,
12924    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12925        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12926            let (worktree_id, file) = project
12927                .buffer_for_id(runnable.buffer, cx)
12928                .and_then(|buffer| buffer.read(cx).file())
12929                .map(|file| (file.worktree_id(cx), file.clone()))
12930                .unzip();
12931
12932            (
12933                project.task_store().read(cx).task_inventory().cloned(),
12934                worktree_id,
12935                file,
12936            )
12937        });
12938
12939        let mut templates_with_tags = mem::take(&mut runnable.tags)
12940            .into_iter()
12941            .flat_map(|RunnableTag(tag)| {
12942                inventory
12943                    .as_ref()
12944                    .into_iter()
12945                    .flat_map(|inventory| {
12946                        inventory.read(cx).list_tasks(
12947                            file.clone(),
12948                            Some(runnable.language.clone()),
12949                            worktree_id,
12950                            cx,
12951                        )
12952                    })
12953                    .filter(move |(_, template)| {
12954                        template.tags.iter().any(|source_tag| source_tag == &tag)
12955                    })
12956            })
12957            .sorted_by_key(|(kind, _)| kind.to_owned())
12958            .collect::<Vec<_>>();
12959        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12960            // Strongest source wins; if we have worktree tag binding, prefer that to
12961            // global and language bindings;
12962            // if we have a global binding, prefer that to language binding.
12963            let first_mismatch = templates_with_tags
12964                .iter()
12965                .position(|(tag_source, _)| tag_source != leading_tag_source);
12966            if let Some(index) = first_mismatch {
12967                templates_with_tags.truncate(index);
12968            }
12969        }
12970
12971        templates_with_tags
12972    }
12973
12974    pub fn move_to_enclosing_bracket(
12975        &mut self,
12976        _: &MoveToEnclosingBracket,
12977        window: &mut Window,
12978        cx: &mut Context<Self>,
12979    ) {
12980        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12981        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12982            s.move_offsets_with(|snapshot, selection| {
12983                let Some(enclosing_bracket_ranges) =
12984                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12985                else {
12986                    return;
12987                };
12988
12989                let mut best_length = usize::MAX;
12990                let mut best_inside = false;
12991                let mut best_in_bracket_range = false;
12992                let mut best_destination = None;
12993                for (open, close) in enclosing_bracket_ranges {
12994                    let close = close.to_inclusive();
12995                    let length = close.end() - open.start;
12996                    let inside = selection.start >= open.end && selection.end <= *close.start();
12997                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12998                        || close.contains(&selection.head());
12999
13000                    // If best is next to a bracket and current isn't, skip
13001                    if !in_bracket_range && best_in_bracket_range {
13002                        continue;
13003                    }
13004
13005                    // Prefer smaller lengths unless best is inside and current isn't
13006                    if length > best_length && (best_inside || !inside) {
13007                        continue;
13008                    }
13009
13010                    best_length = length;
13011                    best_inside = inside;
13012                    best_in_bracket_range = in_bracket_range;
13013                    best_destination = Some(
13014                        if close.contains(&selection.start) && close.contains(&selection.end) {
13015                            if inside { open.end } else { open.start }
13016                        } else if inside {
13017                            *close.start()
13018                        } else {
13019                            *close.end()
13020                        },
13021                    );
13022                }
13023
13024                if let Some(destination) = best_destination {
13025                    selection.collapse_to(destination, SelectionGoal::None);
13026                }
13027            })
13028        });
13029    }
13030
13031    pub fn undo_selection(
13032        &mut self,
13033        _: &UndoSelection,
13034        window: &mut Window,
13035        cx: &mut Context<Self>,
13036    ) {
13037        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13038        self.end_selection(window, cx);
13039        self.selection_history.mode = SelectionHistoryMode::Undoing;
13040        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13041            self.change_selections(None, window, cx, |s| {
13042                s.select_anchors(entry.selections.to_vec())
13043            });
13044            self.select_next_state = entry.select_next_state;
13045            self.select_prev_state = entry.select_prev_state;
13046            self.add_selections_state = entry.add_selections_state;
13047            self.request_autoscroll(Autoscroll::newest(), cx);
13048        }
13049        self.selection_history.mode = SelectionHistoryMode::Normal;
13050    }
13051
13052    pub fn redo_selection(
13053        &mut self,
13054        _: &RedoSelection,
13055        window: &mut Window,
13056        cx: &mut Context<Self>,
13057    ) {
13058        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13059        self.end_selection(window, cx);
13060        self.selection_history.mode = SelectionHistoryMode::Redoing;
13061        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13062            self.change_selections(None, window, cx, |s| {
13063                s.select_anchors(entry.selections.to_vec())
13064            });
13065            self.select_next_state = entry.select_next_state;
13066            self.select_prev_state = entry.select_prev_state;
13067            self.add_selections_state = entry.add_selections_state;
13068            self.request_autoscroll(Autoscroll::newest(), cx);
13069        }
13070        self.selection_history.mode = SelectionHistoryMode::Normal;
13071    }
13072
13073    pub fn expand_excerpts(
13074        &mut self,
13075        action: &ExpandExcerpts,
13076        _: &mut Window,
13077        cx: &mut Context<Self>,
13078    ) {
13079        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13080    }
13081
13082    pub fn expand_excerpts_down(
13083        &mut self,
13084        action: &ExpandExcerptsDown,
13085        _: &mut Window,
13086        cx: &mut Context<Self>,
13087    ) {
13088        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13089    }
13090
13091    pub fn expand_excerpts_up(
13092        &mut self,
13093        action: &ExpandExcerptsUp,
13094        _: &mut Window,
13095        cx: &mut Context<Self>,
13096    ) {
13097        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13098    }
13099
13100    pub fn expand_excerpts_for_direction(
13101        &mut self,
13102        lines: u32,
13103        direction: ExpandExcerptDirection,
13104
13105        cx: &mut Context<Self>,
13106    ) {
13107        let selections = self.selections.disjoint_anchors();
13108
13109        let lines = if lines == 0 {
13110            EditorSettings::get_global(cx).expand_excerpt_lines
13111        } else {
13112            lines
13113        };
13114
13115        self.buffer.update(cx, |buffer, cx| {
13116            let snapshot = buffer.snapshot(cx);
13117            let mut excerpt_ids = selections
13118                .iter()
13119                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13120                .collect::<Vec<_>>();
13121            excerpt_ids.sort();
13122            excerpt_ids.dedup();
13123            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13124        })
13125    }
13126
13127    pub fn expand_excerpt(
13128        &mut self,
13129        excerpt: ExcerptId,
13130        direction: ExpandExcerptDirection,
13131        window: &mut Window,
13132        cx: &mut Context<Self>,
13133    ) {
13134        let current_scroll_position = self.scroll_position(cx);
13135        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13136        let mut should_scroll_up = false;
13137
13138        if direction == ExpandExcerptDirection::Down {
13139            let multi_buffer = self.buffer.read(cx);
13140            let snapshot = multi_buffer.snapshot(cx);
13141            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13142                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13143                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13144                        let buffer_snapshot = buffer.read(cx).snapshot();
13145                        let excerpt_end_row =
13146                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13147                        let last_row = buffer_snapshot.max_point().row;
13148                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13149                        should_scroll_up = lines_below >= lines_to_expand;
13150                    }
13151                }
13152            }
13153        }
13154
13155        self.buffer.update(cx, |buffer, cx| {
13156            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13157        });
13158
13159        if should_scroll_up {
13160            let new_scroll_position =
13161                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13162            self.set_scroll_position(new_scroll_position, window, cx);
13163        }
13164    }
13165
13166    pub fn go_to_singleton_buffer_point(
13167        &mut self,
13168        point: Point,
13169        window: &mut Window,
13170        cx: &mut Context<Self>,
13171    ) {
13172        self.go_to_singleton_buffer_range(point..point, window, cx);
13173    }
13174
13175    pub fn go_to_singleton_buffer_range(
13176        &mut self,
13177        range: Range<Point>,
13178        window: &mut Window,
13179        cx: &mut Context<Self>,
13180    ) {
13181        let multibuffer = self.buffer().read(cx);
13182        let Some(buffer) = multibuffer.as_singleton() else {
13183            return;
13184        };
13185        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13186            return;
13187        };
13188        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13189            return;
13190        };
13191        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13192            s.select_anchor_ranges([start..end])
13193        });
13194    }
13195
13196    pub fn go_to_diagnostic(
13197        &mut self,
13198        _: &GoToDiagnostic,
13199        window: &mut Window,
13200        cx: &mut Context<Self>,
13201    ) {
13202        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13203        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13204    }
13205
13206    pub fn go_to_prev_diagnostic(
13207        &mut self,
13208        _: &GoToPreviousDiagnostic,
13209        window: &mut Window,
13210        cx: &mut Context<Self>,
13211    ) {
13212        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13213        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13214    }
13215
13216    pub fn go_to_diagnostic_impl(
13217        &mut self,
13218        direction: Direction,
13219        window: &mut Window,
13220        cx: &mut Context<Self>,
13221    ) {
13222        let buffer = self.buffer.read(cx).snapshot(cx);
13223        let selection = self.selections.newest::<usize>(cx);
13224
13225        let mut active_group_id = None;
13226        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13227            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13228                active_group_id = Some(active_group.group_id);
13229            }
13230        }
13231
13232        fn filtered(
13233            snapshot: EditorSnapshot,
13234            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13235        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13236            diagnostics
13237                .filter(|entry| entry.range.start != entry.range.end)
13238                .filter(|entry| !entry.diagnostic.is_unnecessary)
13239                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13240        }
13241
13242        let snapshot = self.snapshot(window, cx);
13243        let before = filtered(
13244            snapshot.clone(),
13245            buffer
13246                .diagnostics_in_range(0..selection.start)
13247                .filter(|entry| entry.range.start <= selection.start),
13248        );
13249        let after = filtered(
13250            snapshot,
13251            buffer
13252                .diagnostics_in_range(selection.start..buffer.len())
13253                .filter(|entry| entry.range.start >= selection.start),
13254        );
13255
13256        let mut found: Option<DiagnosticEntry<usize>> = None;
13257        if direction == Direction::Prev {
13258            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13259            {
13260                for diagnostic in prev_diagnostics.into_iter().rev() {
13261                    if diagnostic.range.start != selection.start
13262                        || active_group_id
13263                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13264                    {
13265                        found = Some(diagnostic);
13266                        break 'outer;
13267                    }
13268                }
13269            }
13270        } else {
13271            for diagnostic in after.chain(before) {
13272                if diagnostic.range.start != selection.start
13273                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13274                {
13275                    found = Some(diagnostic);
13276                    break;
13277                }
13278            }
13279        }
13280        let Some(next_diagnostic) = found else {
13281            return;
13282        };
13283
13284        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13285            return;
13286        };
13287        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13288            s.select_ranges(vec![
13289                next_diagnostic.range.start..next_diagnostic.range.start,
13290            ])
13291        });
13292        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13293        self.refresh_inline_completion(false, true, window, cx);
13294    }
13295
13296    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13297        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13298        let snapshot = self.snapshot(window, cx);
13299        let selection = self.selections.newest::<Point>(cx);
13300        self.go_to_hunk_before_or_after_position(
13301            &snapshot,
13302            selection.head(),
13303            Direction::Next,
13304            window,
13305            cx,
13306        );
13307    }
13308
13309    pub fn go_to_hunk_before_or_after_position(
13310        &mut self,
13311        snapshot: &EditorSnapshot,
13312        position: Point,
13313        direction: Direction,
13314        window: &mut Window,
13315        cx: &mut Context<Editor>,
13316    ) {
13317        let row = if direction == Direction::Next {
13318            self.hunk_after_position(snapshot, position)
13319                .map(|hunk| hunk.row_range.start)
13320        } else {
13321            self.hunk_before_position(snapshot, position)
13322        };
13323
13324        if let Some(row) = row {
13325            let destination = Point::new(row.0, 0);
13326            let autoscroll = Autoscroll::center();
13327
13328            self.unfold_ranges(&[destination..destination], false, false, cx);
13329            self.change_selections(Some(autoscroll), window, cx, |s| {
13330                s.select_ranges([destination..destination]);
13331            });
13332        }
13333    }
13334
13335    fn hunk_after_position(
13336        &mut self,
13337        snapshot: &EditorSnapshot,
13338        position: Point,
13339    ) -> Option<MultiBufferDiffHunk> {
13340        snapshot
13341            .buffer_snapshot
13342            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13343            .find(|hunk| hunk.row_range.start.0 > position.row)
13344            .or_else(|| {
13345                snapshot
13346                    .buffer_snapshot
13347                    .diff_hunks_in_range(Point::zero()..position)
13348                    .find(|hunk| hunk.row_range.end.0 < position.row)
13349            })
13350    }
13351
13352    fn go_to_prev_hunk(
13353        &mut self,
13354        _: &GoToPreviousHunk,
13355        window: &mut Window,
13356        cx: &mut Context<Self>,
13357    ) {
13358        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13359        let snapshot = self.snapshot(window, cx);
13360        let selection = self.selections.newest::<Point>(cx);
13361        self.go_to_hunk_before_or_after_position(
13362            &snapshot,
13363            selection.head(),
13364            Direction::Prev,
13365            window,
13366            cx,
13367        );
13368    }
13369
13370    fn hunk_before_position(
13371        &mut self,
13372        snapshot: &EditorSnapshot,
13373        position: Point,
13374    ) -> Option<MultiBufferRow> {
13375        snapshot
13376            .buffer_snapshot
13377            .diff_hunk_before(position)
13378            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13379    }
13380
13381    fn go_to_next_change(
13382        &mut self,
13383        _: &GoToNextChange,
13384        window: &mut Window,
13385        cx: &mut Context<Self>,
13386    ) {
13387        if let Some(selections) = self
13388            .change_list
13389            .next_change(1, Direction::Next)
13390            .map(|s| s.to_vec())
13391        {
13392            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13393                let map = s.display_map();
13394                s.select_display_ranges(selections.iter().map(|a| {
13395                    let point = a.to_display_point(&map);
13396                    point..point
13397                }))
13398            })
13399        }
13400    }
13401
13402    fn go_to_previous_change(
13403        &mut self,
13404        _: &GoToPreviousChange,
13405        window: &mut Window,
13406        cx: &mut Context<Self>,
13407    ) {
13408        if let Some(selections) = self
13409            .change_list
13410            .next_change(1, Direction::Prev)
13411            .map(|s| s.to_vec())
13412        {
13413            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13414                let map = s.display_map();
13415                s.select_display_ranges(selections.iter().map(|a| {
13416                    let point = a.to_display_point(&map);
13417                    point..point
13418                }))
13419            })
13420        }
13421    }
13422
13423    fn go_to_line<T: 'static>(
13424        &mut self,
13425        position: Anchor,
13426        highlight_color: Option<Hsla>,
13427        window: &mut Window,
13428        cx: &mut Context<Self>,
13429    ) {
13430        let snapshot = self.snapshot(window, cx).display_snapshot;
13431        let position = position.to_point(&snapshot.buffer_snapshot);
13432        let start = snapshot
13433            .buffer_snapshot
13434            .clip_point(Point::new(position.row, 0), Bias::Left);
13435        let end = start + Point::new(1, 0);
13436        let start = snapshot.buffer_snapshot.anchor_before(start);
13437        let end = snapshot.buffer_snapshot.anchor_before(end);
13438
13439        self.highlight_rows::<T>(
13440            start..end,
13441            highlight_color
13442                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13443            false,
13444            cx,
13445        );
13446        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13447    }
13448
13449    pub fn go_to_definition(
13450        &mut self,
13451        _: &GoToDefinition,
13452        window: &mut Window,
13453        cx: &mut Context<Self>,
13454    ) -> Task<Result<Navigated>> {
13455        let definition =
13456            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13457        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13458        cx.spawn_in(window, async move |editor, cx| {
13459            if definition.await? == Navigated::Yes {
13460                return Ok(Navigated::Yes);
13461            }
13462            match fallback_strategy {
13463                GoToDefinitionFallback::None => Ok(Navigated::No),
13464                GoToDefinitionFallback::FindAllReferences => {
13465                    match editor.update_in(cx, |editor, window, cx| {
13466                        editor.find_all_references(&FindAllReferences, window, cx)
13467                    })? {
13468                        Some(references) => references.await,
13469                        None => Ok(Navigated::No),
13470                    }
13471                }
13472            }
13473        })
13474    }
13475
13476    pub fn go_to_declaration(
13477        &mut self,
13478        _: &GoToDeclaration,
13479        window: &mut Window,
13480        cx: &mut Context<Self>,
13481    ) -> Task<Result<Navigated>> {
13482        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13483    }
13484
13485    pub fn go_to_declaration_split(
13486        &mut self,
13487        _: &GoToDeclaration,
13488        window: &mut Window,
13489        cx: &mut Context<Self>,
13490    ) -> Task<Result<Navigated>> {
13491        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13492    }
13493
13494    pub fn go_to_implementation(
13495        &mut self,
13496        _: &GoToImplementation,
13497        window: &mut Window,
13498        cx: &mut Context<Self>,
13499    ) -> Task<Result<Navigated>> {
13500        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13501    }
13502
13503    pub fn go_to_implementation_split(
13504        &mut self,
13505        _: &GoToImplementationSplit,
13506        window: &mut Window,
13507        cx: &mut Context<Self>,
13508    ) -> Task<Result<Navigated>> {
13509        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13510    }
13511
13512    pub fn go_to_type_definition(
13513        &mut self,
13514        _: &GoToTypeDefinition,
13515        window: &mut Window,
13516        cx: &mut Context<Self>,
13517    ) -> Task<Result<Navigated>> {
13518        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13519    }
13520
13521    pub fn go_to_definition_split(
13522        &mut self,
13523        _: &GoToDefinitionSplit,
13524        window: &mut Window,
13525        cx: &mut Context<Self>,
13526    ) -> Task<Result<Navigated>> {
13527        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13528    }
13529
13530    pub fn go_to_type_definition_split(
13531        &mut self,
13532        _: &GoToTypeDefinitionSplit,
13533        window: &mut Window,
13534        cx: &mut Context<Self>,
13535    ) -> Task<Result<Navigated>> {
13536        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13537    }
13538
13539    fn go_to_definition_of_kind(
13540        &mut self,
13541        kind: GotoDefinitionKind,
13542        split: bool,
13543        window: &mut Window,
13544        cx: &mut Context<Self>,
13545    ) -> Task<Result<Navigated>> {
13546        let Some(provider) = self.semantics_provider.clone() else {
13547            return Task::ready(Ok(Navigated::No));
13548        };
13549        let head = self.selections.newest::<usize>(cx).head();
13550        let buffer = self.buffer.read(cx);
13551        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13552            text_anchor
13553        } else {
13554            return Task::ready(Ok(Navigated::No));
13555        };
13556
13557        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13558            return Task::ready(Ok(Navigated::No));
13559        };
13560
13561        cx.spawn_in(window, async move |editor, cx| {
13562            let definitions = definitions.await?;
13563            let navigated = editor
13564                .update_in(cx, |editor, window, cx| {
13565                    editor.navigate_to_hover_links(
13566                        Some(kind),
13567                        definitions
13568                            .into_iter()
13569                            .filter(|location| {
13570                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13571                            })
13572                            .map(HoverLink::Text)
13573                            .collect::<Vec<_>>(),
13574                        split,
13575                        window,
13576                        cx,
13577                    )
13578                })?
13579                .await?;
13580            anyhow::Ok(navigated)
13581        })
13582    }
13583
13584    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13585        let selection = self.selections.newest_anchor();
13586        let head = selection.head();
13587        let tail = selection.tail();
13588
13589        let Some((buffer, start_position)) =
13590            self.buffer.read(cx).text_anchor_for_position(head, cx)
13591        else {
13592            return;
13593        };
13594
13595        let end_position = if head != tail {
13596            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13597                return;
13598            };
13599            Some(pos)
13600        } else {
13601            None
13602        };
13603
13604        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13605            let url = if let Some(end_pos) = end_position {
13606                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13607            } else {
13608                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13609            };
13610
13611            if let Some(url) = url {
13612                editor.update(cx, |_, cx| {
13613                    cx.open_url(&url);
13614                })
13615            } else {
13616                Ok(())
13617            }
13618        });
13619
13620        url_finder.detach();
13621    }
13622
13623    pub fn open_selected_filename(
13624        &mut self,
13625        _: &OpenSelectedFilename,
13626        window: &mut Window,
13627        cx: &mut Context<Self>,
13628    ) {
13629        let Some(workspace) = self.workspace() else {
13630            return;
13631        };
13632
13633        let position = self.selections.newest_anchor().head();
13634
13635        let Some((buffer, buffer_position)) =
13636            self.buffer.read(cx).text_anchor_for_position(position, cx)
13637        else {
13638            return;
13639        };
13640
13641        let project = self.project.clone();
13642
13643        cx.spawn_in(window, async move |_, cx| {
13644            let result = find_file(&buffer, project, buffer_position, cx).await;
13645
13646            if let Some((_, path)) = result {
13647                workspace
13648                    .update_in(cx, |workspace, window, cx| {
13649                        workspace.open_resolved_path(path, window, cx)
13650                    })?
13651                    .await?;
13652            }
13653            anyhow::Ok(())
13654        })
13655        .detach();
13656    }
13657
13658    pub(crate) fn navigate_to_hover_links(
13659        &mut self,
13660        kind: Option<GotoDefinitionKind>,
13661        mut definitions: Vec<HoverLink>,
13662        split: bool,
13663        window: &mut Window,
13664        cx: &mut Context<Editor>,
13665    ) -> Task<Result<Navigated>> {
13666        // If there is one definition, just open it directly
13667        if definitions.len() == 1 {
13668            let definition = definitions.pop().unwrap();
13669
13670            enum TargetTaskResult {
13671                Location(Option<Location>),
13672                AlreadyNavigated,
13673            }
13674
13675            let target_task = match definition {
13676                HoverLink::Text(link) => {
13677                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13678                }
13679                HoverLink::InlayHint(lsp_location, server_id) => {
13680                    let computation =
13681                        self.compute_target_location(lsp_location, server_id, window, cx);
13682                    cx.background_spawn(async move {
13683                        let location = computation.await?;
13684                        Ok(TargetTaskResult::Location(location))
13685                    })
13686                }
13687                HoverLink::Url(url) => {
13688                    cx.open_url(&url);
13689                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13690                }
13691                HoverLink::File(path) => {
13692                    if let Some(workspace) = self.workspace() {
13693                        cx.spawn_in(window, async move |_, cx| {
13694                            workspace
13695                                .update_in(cx, |workspace, window, cx| {
13696                                    workspace.open_resolved_path(path, window, cx)
13697                                })?
13698                                .await
13699                                .map(|_| TargetTaskResult::AlreadyNavigated)
13700                        })
13701                    } else {
13702                        Task::ready(Ok(TargetTaskResult::Location(None)))
13703                    }
13704                }
13705            };
13706            cx.spawn_in(window, async move |editor, cx| {
13707                let target = match target_task.await.context("target resolution task")? {
13708                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13709                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13710                    TargetTaskResult::Location(Some(target)) => target,
13711                };
13712
13713                editor.update_in(cx, |editor, window, cx| {
13714                    let Some(workspace) = editor.workspace() else {
13715                        return Navigated::No;
13716                    };
13717                    let pane = workspace.read(cx).active_pane().clone();
13718
13719                    let range = target.range.to_point(target.buffer.read(cx));
13720                    let range = editor.range_for_match(&range);
13721                    let range = collapse_multiline_range(range);
13722
13723                    if !split
13724                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13725                    {
13726                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13727                    } else {
13728                        window.defer(cx, move |window, cx| {
13729                            let target_editor: Entity<Self> =
13730                                workspace.update(cx, |workspace, cx| {
13731                                    let pane = if split {
13732                                        workspace.adjacent_pane(window, cx)
13733                                    } else {
13734                                        workspace.active_pane().clone()
13735                                    };
13736
13737                                    workspace.open_project_item(
13738                                        pane,
13739                                        target.buffer.clone(),
13740                                        true,
13741                                        true,
13742                                        window,
13743                                        cx,
13744                                    )
13745                                });
13746                            target_editor.update(cx, |target_editor, cx| {
13747                                // When selecting a definition in a different buffer, disable the nav history
13748                                // to avoid creating a history entry at the previous cursor location.
13749                                pane.update(cx, |pane, _| pane.disable_history());
13750                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13751                                pane.update(cx, |pane, _| pane.enable_history());
13752                            });
13753                        });
13754                    }
13755                    Navigated::Yes
13756                })
13757            })
13758        } else if !definitions.is_empty() {
13759            cx.spawn_in(window, async move |editor, cx| {
13760                let (title, location_tasks, workspace) = editor
13761                    .update_in(cx, |editor, window, cx| {
13762                        let tab_kind = match kind {
13763                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13764                            _ => "Definitions",
13765                        };
13766                        let title = definitions
13767                            .iter()
13768                            .find_map(|definition| match definition {
13769                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13770                                    let buffer = origin.buffer.read(cx);
13771                                    format!(
13772                                        "{} for {}",
13773                                        tab_kind,
13774                                        buffer
13775                                            .text_for_range(origin.range.clone())
13776                                            .collect::<String>()
13777                                    )
13778                                }),
13779                                HoverLink::InlayHint(_, _) => None,
13780                                HoverLink::Url(_) => None,
13781                                HoverLink::File(_) => None,
13782                            })
13783                            .unwrap_or(tab_kind.to_string());
13784                        let location_tasks = definitions
13785                            .into_iter()
13786                            .map(|definition| match definition {
13787                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13788                                HoverLink::InlayHint(lsp_location, server_id) => editor
13789                                    .compute_target_location(lsp_location, server_id, window, cx),
13790                                HoverLink::Url(_) => Task::ready(Ok(None)),
13791                                HoverLink::File(_) => Task::ready(Ok(None)),
13792                            })
13793                            .collect::<Vec<_>>();
13794                        (title, location_tasks, editor.workspace().clone())
13795                    })
13796                    .context("location tasks preparation")?;
13797
13798                let locations = future::join_all(location_tasks)
13799                    .await
13800                    .into_iter()
13801                    .filter_map(|location| location.transpose())
13802                    .collect::<Result<_>>()
13803                    .context("location tasks")?;
13804
13805                let Some(workspace) = workspace else {
13806                    return Ok(Navigated::No);
13807                };
13808                let opened = workspace
13809                    .update_in(cx, |workspace, window, cx| {
13810                        Self::open_locations_in_multibuffer(
13811                            workspace,
13812                            locations,
13813                            title,
13814                            split,
13815                            MultibufferSelectionMode::First,
13816                            window,
13817                            cx,
13818                        )
13819                    })
13820                    .ok();
13821
13822                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13823            })
13824        } else {
13825            Task::ready(Ok(Navigated::No))
13826        }
13827    }
13828
13829    fn compute_target_location(
13830        &self,
13831        lsp_location: lsp::Location,
13832        server_id: LanguageServerId,
13833        window: &mut Window,
13834        cx: &mut Context<Self>,
13835    ) -> Task<anyhow::Result<Option<Location>>> {
13836        let Some(project) = self.project.clone() else {
13837            return Task::ready(Ok(None));
13838        };
13839
13840        cx.spawn_in(window, async move |editor, cx| {
13841            let location_task = editor.update(cx, |_, cx| {
13842                project.update(cx, |project, cx| {
13843                    let language_server_name = project
13844                        .language_server_statuses(cx)
13845                        .find(|(id, _)| server_id == *id)
13846                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13847                    language_server_name.map(|language_server_name| {
13848                        project.open_local_buffer_via_lsp(
13849                            lsp_location.uri.clone(),
13850                            server_id,
13851                            language_server_name,
13852                            cx,
13853                        )
13854                    })
13855                })
13856            })?;
13857            let location = match location_task {
13858                Some(task) => Some({
13859                    let target_buffer_handle = task.await.context("open local buffer")?;
13860                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13861                        let target_start = target_buffer
13862                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13863                        let target_end = target_buffer
13864                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13865                        target_buffer.anchor_after(target_start)
13866                            ..target_buffer.anchor_before(target_end)
13867                    })?;
13868                    Location {
13869                        buffer: target_buffer_handle,
13870                        range,
13871                    }
13872                }),
13873                None => None,
13874            };
13875            Ok(location)
13876        })
13877    }
13878
13879    pub fn find_all_references(
13880        &mut self,
13881        _: &FindAllReferences,
13882        window: &mut Window,
13883        cx: &mut Context<Self>,
13884    ) -> Option<Task<Result<Navigated>>> {
13885        let selection = self.selections.newest::<usize>(cx);
13886        let multi_buffer = self.buffer.read(cx);
13887        let head = selection.head();
13888
13889        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13890        let head_anchor = multi_buffer_snapshot.anchor_at(
13891            head,
13892            if head < selection.tail() {
13893                Bias::Right
13894            } else {
13895                Bias::Left
13896            },
13897        );
13898
13899        match self
13900            .find_all_references_task_sources
13901            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13902        {
13903            Ok(_) => {
13904                log::info!(
13905                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13906                );
13907                return None;
13908            }
13909            Err(i) => {
13910                self.find_all_references_task_sources.insert(i, head_anchor);
13911            }
13912        }
13913
13914        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13915        let workspace = self.workspace()?;
13916        let project = workspace.read(cx).project().clone();
13917        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13918        Some(cx.spawn_in(window, async move |editor, cx| {
13919            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13920                if let Ok(i) = editor
13921                    .find_all_references_task_sources
13922                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13923                {
13924                    editor.find_all_references_task_sources.remove(i);
13925                }
13926            });
13927
13928            let locations = references.await?;
13929            if locations.is_empty() {
13930                return anyhow::Ok(Navigated::No);
13931            }
13932
13933            workspace.update_in(cx, |workspace, window, cx| {
13934                let title = locations
13935                    .first()
13936                    .as_ref()
13937                    .map(|location| {
13938                        let buffer = location.buffer.read(cx);
13939                        format!(
13940                            "References to `{}`",
13941                            buffer
13942                                .text_for_range(location.range.clone())
13943                                .collect::<String>()
13944                        )
13945                    })
13946                    .unwrap();
13947                Self::open_locations_in_multibuffer(
13948                    workspace,
13949                    locations,
13950                    title,
13951                    false,
13952                    MultibufferSelectionMode::First,
13953                    window,
13954                    cx,
13955                );
13956                Navigated::Yes
13957            })
13958        }))
13959    }
13960
13961    /// Opens a multibuffer with the given project locations in it
13962    pub fn open_locations_in_multibuffer(
13963        workspace: &mut Workspace,
13964        mut locations: Vec<Location>,
13965        title: String,
13966        split: bool,
13967        multibuffer_selection_mode: MultibufferSelectionMode,
13968        window: &mut Window,
13969        cx: &mut Context<Workspace>,
13970    ) {
13971        // If there are multiple definitions, open them in a multibuffer
13972        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13973        let mut locations = locations.into_iter().peekable();
13974        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13975        let capability = workspace.project().read(cx).capability();
13976
13977        let excerpt_buffer = cx.new(|cx| {
13978            let mut multibuffer = MultiBuffer::new(capability);
13979            while let Some(location) = locations.next() {
13980                let buffer = location.buffer.read(cx);
13981                let mut ranges_for_buffer = Vec::new();
13982                let range = location.range.to_point(buffer);
13983                ranges_for_buffer.push(range.clone());
13984
13985                while let Some(next_location) = locations.peek() {
13986                    if next_location.buffer == location.buffer {
13987                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13988                        locations.next();
13989                    } else {
13990                        break;
13991                    }
13992                }
13993
13994                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13995                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13996                    PathKey::for_buffer(&location.buffer, cx),
13997                    location.buffer.clone(),
13998                    ranges_for_buffer,
13999                    DEFAULT_MULTIBUFFER_CONTEXT,
14000                    cx,
14001                );
14002                ranges.extend(new_ranges)
14003            }
14004
14005            multibuffer.with_title(title)
14006        });
14007
14008        let editor = cx.new(|cx| {
14009            Editor::for_multibuffer(
14010                excerpt_buffer,
14011                Some(workspace.project().clone()),
14012                window,
14013                cx,
14014            )
14015        });
14016        editor.update(cx, |editor, cx| {
14017            match multibuffer_selection_mode {
14018                MultibufferSelectionMode::First => {
14019                    if let Some(first_range) = ranges.first() {
14020                        editor.change_selections(None, window, cx, |selections| {
14021                            selections.clear_disjoint();
14022                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14023                        });
14024                    }
14025                    editor.highlight_background::<Self>(
14026                        &ranges,
14027                        |theme| theme.editor_highlighted_line_background,
14028                        cx,
14029                    );
14030                }
14031                MultibufferSelectionMode::All => {
14032                    editor.change_selections(None, window, cx, |selections| {
14033                        selections.clear_disjoint();
14034                        selections.select_anchor_ranges(ranges);
14035                    });
14036                }
14037            }
14038            editor.register_buffers_with_language_servers(cx);
14039        });
14040
14041        let item = Box::new(editor);
14042        let item_id = item.item_id();
14043
14044        if split {
14045            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14046        } else {
14047            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14048                let (preview_item_id, preview_item_idx) =
14049                    workspace.active_pane().update(cx, |pane, _| {
14050                        (pane.preview_item_id(), pane.preview_item_idx())
14051                    });
14052
14053                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14054
14055                if let Some(preview_item_id) = preview_item_id {
14056                    workspace.active_pane().update(cx, |pane, cx| {
14057                        pane.remove_item(preview_item_id, false, false, window, cx);
14058                    });
14059                }
14060            } else {
14061                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14062            }
14063        }
14064        workspace.active_pane().update(cx, |pane, cx| {
14065            pane.set_preview_item_id(Some(item_id), cx);
14066        });
14067    }
14068
14069    pub fn rename(
14070        &mut self,
14071        _: &Rename,
14072        window: &mut Window,
14073        cx: &mut Context<Self>,
14074    ) -> Option<Task<Result<()>>> {
14075        use language::ToOffset as _;
14076
14077        let provider = self.semantics_provider.clone()?;
14078        let selection = self.selections.newest_anchor().clone();
14079        let (cursor_buffer, cursor_buffer_position) = self
14080            .buffer
14081            .read(cx)
14082            .text_anchor_for_position(selection.head(), cx)?;
14083        let (tail_buffer, cursor_buffer_position_end) = self
14084            .buffer
14085            .read(cx)
14086            .text_anchor_for_position(selection.tail(), cx)?;
14087        if tail_buffer != cursor_buffer {
14088            return None;
14089        }
14090
14091        let snapshot = cursor_buffer.read(cx).snapshot();
14092        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14093        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14094        let prepare_rename = provider
14095            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14096            .unwrap_or_else(|| Task::ready(Ok(None)));
14097        drop(snapshot);
14098
14099        Some(cx.spawn_in(window, async move |this, cx| {
14100            let rename_range = if let Some(range) = prepare_rename.await? {
14101                Some(range)
14102            } else {
14103                this.update(cx, |this, cx| {
14104                    let buffer = this.buffer.read(cx).snapshot(cx);
14105                    let mut buffer_highlights = this
14106                        .document_highlights_for_position(selection.head(), &buffer)
14107                        .filter(|highlight| {
14108                            highlight.start.excerpt_id == selection.head().excerpt_id
14109                                && highlight.end.excerpt_id == selection.head().excerpt_id
14110                        });
14111                    buffer_highlights
14112                        .next()
14113                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14114                })?
14115            };
14116            if let Some(rename_range) = rename_range {
14117                this.update_in(cx, |this, window, cx| {
14118                    let snapshot = cursor_buffer.read(cx).snapshot();
14119                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14120                    let cursor_offset_in_rename_range =
14121                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14122                    let cursor_offset_in_rename_range_end =
14123                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14124
14125                    this.take_rename(false, window, cx);
14126                    let buffer = this.buffer.read(cx).read(cx);
14127                    let cursor_offset = selection.head().to_offset(&buffer);
14128                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14129                    let rename_end = rename_start + rename_buffer_range.len();
14130                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14131                    let mut old_highlight_id = None;
14132                    let old_name: Arc<str> = buffer
14133                        .chunks(rename_start..rename_end, true)
14134                        .map(|chunk| {
14135                            if old_highlight_id.is_none() {
14136                                old_highlight_id = chunk.syntax_highlight_id;
14137                            }
14138                            chunk.text
14139                        })
14140                        .collect::<String>()
14141                        .into();
14142
14143                    drop(buffer);
14144
14145                    // Position the selection in the rename editor so that it matches the current selection.
14146                    this.show_local_selections = false;
14147                    let rename_editor = cx.new(|cx| {
14148                        let mut editor = Editor::single_line(window, cx);
14149                        editor.buffer.update(cx, |buffer, cx| {
14150                            buffer.edit([(0..0, old_name.clone())], None, cx)
14151                        });
14152                        let rename_selection_range = match cursor_offset_in_rename_range
14153                            .cmp(&cursor_offset_in_rename_range_end)
14154                        {
14155                            Ordering::Equal => {
14156                                editor.select_all(&SelectAll, window, cx);
14157                                return editor;
14158                            }
14159                            Ordering::Less => {
14160                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14161                            }
14162                            Ordering::Greater => {
14163                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14164                            }
14165                        };
14166                        if rename_selection_range.end > old_name.len() {
14167                            editor.select_all(&SelectAll, window, cx);
14168                        } else {
14169                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14170                                s.select_ranges([rename_selection_range]);
14171                            });
14172                        }
14173                        editor
14174                    });
14175                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14176                        if e == &EditorEvent::Focused {
14177                            cx.emit(EditorEvent::FocusedIn)
14178                        }
14179                    })
14180                    .detach();
14181
14182                    let write_highlights =
14183                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14184                    let read_highlights =
14185                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14186                    let ranges = write_highlights
14187                        .iter()
14188                        .flat_map(|(_, ranges)| ranges.iter())
14189                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14190                        .cloned()
14191                        .collect();
14192
14193                    this.highlight_text::<Rename>(
14194                        ranges,
14195                        HighlightStyle {
14196                            fade_out: Some(0.6),
14197                            ..Default::default()
14198                        },
14199                        cx,
14200                    );
14201                    let rename_focus_handle = rename_editor.focus_handle(cx);
14202                    window.focus(&rename_focus_handle);
14203                    let block_id = this.insert_blocks(
14204                        [BlockProperties {
14205                            style: BlockStyle::Flex,
14206                            placement: BlockPlacement::Below(range.start),
14207                            height: Some(1),
14208                            render: Arc::new({
14209                                let rename_editor = rename_editor.clone();
14210                                move |cx: &mut BlockContext| {
14211                                    let mut text_style = cx.editor_style.text.clone();
14212                                    if let Some(highlight_style) = old_highlight_id
14213                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14214                                    {
14215                                        text_style = text_style.highlight(highlight_style);
14216                                    }
14217                                    div()
14218                                        .block_mouse_down()
14219                                        .pl(cx.anchor_x)
14220                                        .child(EditorElement::new(
14221                                            &rename_editor,
14222                                            EditorStyle {
14223                                                background: cx.theme().system().transparent,
14224                                                local_player: cx.editor_style.local_player,
14225                                                text: text_style,
14226                                                scrollbar_width: cx.editor_style.scrollbar_width,
14227                                                syntax: cx.editor_style.syntax.clone(),
14228                                                status: cx.editor_style.status.clone(),
14229                                                inlay_hints_style: HighlightStyle {
14230                                                    font_weight: Some(FontWeight::BOLD),
14231                                                    ..make_inlay_hints_style(cx.app)
14232                                                },
14233                                                inline_completion_styles: make_suggestion_styles(
14234                                                    cx.app,
14235                                                ),
14236                                                ..EditorStyle::default()
14237                                            },
14238                                        ))
14239                                        .into_any_element()
14240                                }
14241                            }),
14242                            priority: 0,
14243                        }],
14244                        Some(Autoscroll::fit()),
14245                        cx,
14246                    )[0];
14247                    this.pending_rename = Some(RenameState {
14248                        range,
14249                        old_name,
14250                        editor: rename_editor,
14251                        block_id,
14252                    });
14253                })?;
14254            }
14255
14256            Ok(())
14257        }))
14258    }
14259
14260    pub fn confirm_rename(
14261        &mut self,
14262        _: &ConfirmRename,
14263        window: &mut Window,
14264        cx: &mut Context<Self>,
14265    ) -> Option<Task<Result<()>>> {
14266        let rename = self.take_rename(false, window, cx)?;
14267        let workspace = self.workspace()?.downgrade();
14268        let (buffer, start) = self
14269            .buffer
14270            .read(cx)
14271            .text_anchor_for_position(rename.range.start, cx)?;
14272        let (end_buffer, _) = self
14273            .buffer
14274            .read(cx)
14275            .text_anchor_for_position(rename.range.end, cx)?;
14276        if buffer != end_buffer {
14277            return None;
14278        }
14279
14280        let old_name = rename.old_name;
14281        let new_name = rename.editor.read(cx).text(cx);
14282
14283        let rename = self.semantics_provider.as_ref()?.perform_rename(
14284            &buffer,
14285            start,
14286            new_name.clone(),
14287            cx,
14288        )?;
14289
14290        Some(cx.spawn_in(window, async move |editor, cx| {
14291            let project_transaction = rename.await?;
14292            Self::open_project_transaction(
14293                &editor,
14294                workspace,
14295                project_transaction,
14296                format!("Rename: {}{}", old_name, new_name),
14297                cx,
14298            )
14299            .await?;
14300
14301            editor.update(cx, |editor, cx| {
14302                editor.refresh_document_highlights(cx);
14303            })?;
14304            Ok(())
14305        }))
14306    }
14307
14308    fn take_rename(
14309        &mut self,
14310        moving_cursor: bool,
14311        window: &mut Window,
14312        cx: &mut Context<Self>,
14313    ) -> Option<RenameState> {
14314        let rename = self.pending_rename.take()?;
14315        if rename.editor.focus_handle(cx).is_focused(window) {
14316            window.focus(&self.focus_handle);
14317        }
14318
14319        self.remove_blocks(
14320            [rename.block_id].into_iter().collect(),
14321            Some(Autoscroll::fit()),
14322            cx,
14323        );
14324        self.clear_highlights::<Rename>(cx);
14325        self.show_local_selections = true;
14326
14327        if moving_cursor {
14328            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14329                editor.selections.newest::<usize>(cx).head()
14330            });
14331
14332            // Update the selection to match the position of the selection inside
14333            // the rename editor.
14334            let snapshot = self.buffer.read(cx).read(cx);
14335            let rename_range = rename.range.to_offset(&snapshot);
14336            let cursor_in_editor = snapshot
14337                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14338                .min(rename_range.end);
14339            drop(snapshot);
14340
14341            self.change_selections(None, window, cx, |s| {
14342                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14343            });
14344        } else {
14345            self.refresh_document_highlights(cx);
14346        }
14347
14348        Some(rename)
14349    }
14350
14351    pub fn pending_rename(&self) -> Option<&RenameState> {
14352        self.pending_rename.as_ref()
14353    }
14354
14355    fn format(
14356        &mut self,
14357        _: &Format,
14358        window: &mut Window,
14359        cx: &mut Context<Self>,
14360    ) -> Option<Task<Result<()>>> {
14361        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14362
14363        let project = match &self.project {
14364            Some(project) => project.clone(),
14365            None => return None,
14366        };
14367
14368        Some(self.perform_format(
14369            project,
14370            FormatTrigger::Manual,
14371            FormatTarget::Buffers,
14372            window,
14373            cx,
14374        ))
14375    }
14376
14377    fn format_selections(
14378        &mut self,
14379        _: &FormatSelections,
14380        window: &mut Window,
14381        cx: &mut Context<Self>,
14382    ) -> Option<Task<Result<()>>> {
14383        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14384
14385        let project = match &self.project {
14386            Some(project) => project.clone(),
14387            None => return None,
14388        };
14389
14390        let ranges = self
14391            .selections
14392            .all_adjusted(cx)
14393            .into_iter()
14394            .map(|selection| selection.range())
14395            .collect_vec();
14396
14397        Some(self.perform_format(
14398            project,
14399            FormatTrigger::Manual,
14400            FormatTarget::Ranges(ranges),
14401            window,
14402            cx,
14403        ))
14404    }
14405
14406    fn perform_format(
14407        &mut self,
14408        project: Entity<Project>,
14409        trigger: FormatTrigger,
14410        target: FormatTarget,
14411        window: &mut Window,
14412        cx: &mut Context<Self>,
14413    ) -> Task<Result<()>> {
14414        let buffer = self.buffer.clone();
14415        let (buffers, target) = match target {
14416            FormatTarget::Buffers => {
14417                let mut buffers = buffer.read(cx).all_buffers();
14418                if trigger == FormatTrigger::Save {
14419                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14420                }
14421                (buffers, LspFormatTarget::Buffers)
14422            }
14423            FormatTarget::Ranges(selection_ranges) => {
14424                let multi_buffer = buffer.read(cx);
14425                let snapshot = multi_buffer.read(cx);
14426                let mut buffers = HashSet::default();
14427                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14428                    BTreeMap::new();
14429                for selection_range in selection_ranges {
14430                    for (buffer, buffer_range, _) in
14431                        snapshot.range_to_buffer_ranges(selection_range)
14432                    {
14433                        let buffer_id = buffer.remote_id();
14434                        let start = buffer.anchor_before(buffer_range.start);
14435                        let end = buffer.anchor_after(buffer_range.end);
14436                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14437                        buffer_id_to_ranges
14438                            .entry(buffer_id)
14439                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14440                            .or_insert_with(|| vec![start..end]);
14441                    }
14442                }
14443                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14444            }
14445        };
14446
14447        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14448        let selections_prev = transaction_id_prev
14449            .and_then(|transaction_id_prev| {
14450                // default to selections as they were after the last edit, if we have them,
14451                // instead of how they are now.
14452                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14453                // will take you back to where you made the last edit, instead of staying where you scrolled
14454                self.selection_history
14455                    .transaction(transaction_id_prev)
14456                    .map(|t| t.0.clone())
14457            })
14458            .unwrap_or_else(|| {
14459                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14460                self.selections.disjoint_anchors()
14461            });
14462
14463        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14464        let format = project.update(cx, |project, cx| {
14465            project.format(buffers, target, true, trigger, cx)
14466        });
14467
14468        cx.spawn_in(window, async move |editor, cx| {
14469            let transaction = futures::select_biased! {
14470                transaction = format.log_err().fuse() => transaction,
14471                () = timeout => {
14472                    log::warn!("timed out waiting for formatting");
14473                    None
14474                }
14475            };
14476
14477            buffer
14478                .update(cx, |buffer, cx| {
14479                    if let Some(transaction) = transaction {
14480                        if !buffer.is_singleton() {
14481                            buffer.push_transaction(&transaction.0, cx);
14482                        }
14483                    }
14484                    cx.notify();
14485                })
14486                .ok();
14487
14488            if let Some(transaction_id_now) =
14489                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14490            {
14491                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14492                if has_new_transaction {
14493                    _ = editor.update(cx, |editor, _| {
14494                        editor
14495                            .selection_history
14496                            .insert_transaction(transaction_id_now, selections_prev);
14497                    });
14498                }
14499            }
14500
14501            Ok(())
14502        })
14503    }
14504
14505    fn organize_imports(
14506        &mut self,
14507        _: &OrganizeImports,
14508        window: &mut Window,
14509        cx: &mut Context<Self>,
14510    ) -> Option<Task<Result<()>>> {
14511        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14512        let project = match &self.project {
14513            Some(project) => project.clone(),
14514            None => return None,
14515        };
14516        Some(self.perform_code_action_kind(
14517            project,
14518            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14519            window,
14520            cx,
14521        ))
14522    }
14523
14524    fn perform_code_action_kind(
14525        &mut self,
14526        project: Entity<Project>,
14527        kind: CodeActionKind,
14528        window: &mut Window,
14529        cx: &mut Context<Self>,
14530    ) -> Task<Result<()>> {
14531        let buffer = self.buffer.clone();
14532        let buffers = buffer.read(cx).all_buffers();
14533        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14534        let apply_action = project.update(cx, |project, cx| {
14535            project.apply_code_action_kind(buffers, kind, true, cx)
14536        });
14537        cx.spawn_in(window, async move |_, cx| {
14538            let transaction = futures::select_biased! {
14539                () = timeout => {
14540                    log::warn!("timed out waiting for executing code action");
14541                    None
14542                }
14543                transaction = apply_action.log_err().fuse() => transaction,
14544            };
14545            buffer
14546                .update(cx, |buffer, cx| {
14547                    // check if we need this
14548                    if let Some(transaction) = transaction {
14549                        if !buffer.is_singleton() {
14550                            buffer.push_transaction(&transaction.0, cx);
14551                        }
14552                    }
14553                    cx.notify();
14554                })
14555                .ok();
14556            Ok(())
14557        })
14558    }
14559
14560    fn restart_language_server(
14561        &mut self,
14562        _: &RestartLanguageServer,
14563        _: &mut Window,
14564        cx: &mut Context<Self>,
14565    ) {
14566        if let Some(project) = self.project.clone() {
14567            self.buffer.update(cx, |multi_buffer, cx| {
14568                project.update(cx, |project, cx| {
14569                    project.restart_language_servers_for_buffers(
14570                        multi_buffer.all_buffers().into_iter().collect(),
14571                        cx,
14572                    );
14573                });
14574            })
14575        }
14576    }
14577
14578    fn stop_language_server(
14579        &mut self,
14580        _: &StopLanguageServer,
14581        _: &mut Window,
14582        cx: &mut Context<Self>,
14583    ) {
14584        if let Some(project) = self.project.clone() {
14585            self.buffer.update(cx, |multi_buffer, cx| {
14586                project.update(cx, |project, cx| {
14587                    project.stop_language_servers_for_buffers(
14588                        multi_buffer.all_buffers().into_iter().collect(),
14589                        cx,
14590                    );
14591                    cx.emit(project::Event::RefreshInlayHints);
14592                });
14593            });
14594        }
14595    }
14596
14597    fn cancel_language_server_work(
14598        workspace: &mut Workspace,
14599        _: &actions::CancelLanguageServerWork,
14600        _: &mut Window,
14601        cx: &mut Context<Workspace>,
14602    ) {
14603        let project = workspace.project();
14604        let buffers = workspace
14605            .active_item(cx)
14606            .and_then(|item| item.act_as::<Editor>(cx))
14607            .map_or(HashSet::default(), |editor| {
14608                editor.read(cx).buffer.read(cx).all_buffers()
14609            });
14610        project.update(cx, |project, cx| {
14611            project.cancel_language_server_work_for_buffers(buffers, cx);
14612        });
14613    }
14614
14615    fn show_character_palette(
14616        &mut self,
14617        _: &ShowCharacterPalette,
14618        window: &mut Window,
14619        _: &mut Context<Self>,
14620    ) {
14621        window.show_character_palette();
14622    }
14623
14624    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14625        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14626            let buffer = self.buffer.read(cx).snapshot(cx);
14627            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14628            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14629            let is_valid = buffer
14630                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14631                .any(|entry| {
14632                    entry.diagnostic.is_primary
14633                        && !entry.range.is_empty()
14634                        && entry.range.start == primary_range_start
14635                        && entry.diagnostic.message == active_diagnostics.active_message
14636                });
14637
14638            if !is_valid {
14639                self.dismiss_diagnostics(cx);
14640            }
14641        }
14642    }
14643
14644    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14645        match &self.active_diagnostics {
14646            ActiveDiagnostic::Group(group) => Some(group),
14647            _ => None,
14648        }
14649    }
14650
14651    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14652        self.dismiss_diagnostics(cx);
14653        self.active_diagnostics = ActiveDiagnostic::All;
14654    }
14655
14656    fn activate_diagnostics(
14657        &mut self,
14658        buffer_id: BufferId,
14659        diagnostic: DiagnosticEntry<usize>,
14660        window: &mut Window,
14661        cx: &mut Context<Self>,
14662    ) {
14663        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14664            return;
14665        }
14666        self.dismiss_diagnostics(cx);
14667        let snapshot = self.snapshot(window, cx);
14668        let Some(diagnostic_renderer) = cx
14669            .try_global::<GlobalDiagnosticRenderer>()
14670            .map(|g| g.0.clone())
14671        else {
14672            return;
14673        };
14674        let buffer = self.buffer.read(cx).snapshot(cx);
14675
14676        let diagnostic_group = buffer
14677            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14678            .collect::<Vec<_>>();
14679
14680        let blocks = diagnostic_renderer.render_group(
14681            diagnostic_group,
14682            buffer_id,
14683            snapshot,
14684            cx.weak_entity(),
14685            cx,
14686        );
14687
14688        let blocks = self.display_map.update(cx, |display_map, cx| {
14689            display_map.insert_blocks(blocks, cx).into_iter().collect()
14690        });
14691        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14692            active_range: buffer.anchor_before(diagnostic.range.start)
14693                ..buffer.anchor_after(diagnostic.range.end),
14694            active_message: diagnostic.diagnostic.message.clone(),
14695            group_id: diagnostic.diagnostic.group_id,
14696            blocks,
14697        });
14698        cx.notify();
14699    }
14700
14701    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14702        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14703            return;
14704        };
14705
14706        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14707        if let ActiveDiagnostic::Group(group) = prev {
14708            self.display_map.update(cx, |display_map, cx| {
14709                display_map.remove_blocks(group.blocks, cx);
14710            });
14711            cx.notify();
14712        }
14713    }
14714
14715    /// Disable inline diagnostics rendering for this editor.
14716    pub fn disable_inline_diagnostics(&mut self) {
14717        self.inline_diagnostics_enabled = false;
14718        self.inline_diagnostics_update = Task::ready(());
14719        self.inline_diagnostics.clear();
14720    }
14721
14722    pub fn inline_diagnostics_enabled(&self) -> bool {
14723        self.inline_diagnostics_enabled
14724    }
14725
14726    pub fn show_inline_diagnostics(&self) -> bool {
14727        self.show_inline_diagnostics
14728    }
14729
14730    pub fn toggle_inline_diagnostics(
14731        &mut self,
14732        _: &ToggleInlineDiagnostics,
14733        window: &mut Window,
14734        cx: &mut Context<Editor>,
14735    ) {
14736        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14737        self.refresh_inline_diagnostics(false, window, cx);
14738    }
14739
14740    fn refresh_inline_diagnostics(
14741        &mut self,
14742        debounce: bool,
14743        window: &mut Window,
14744        cx: &mut Context<Self>,
14745    ) {
14746        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14747            self.inline_diagnostics_update = Task::ready(());
14748            self.inline_diagnostics.clear();
14749            return;
14750        }
14751
14752        let debounce_ms = ProjectSettings::get_global(cx)
14753            .diagnostics
14754            .inline
14755            .update_debounce_ms;
14756        let debounce = if debounce && debounce_ms > 0 {
14757            Some(Duration::from_millis(debounce_ms))
14758        } else {
14759            None
14760        };
14761        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14762            let editor = editor.upgrade().unwrap();
14763
14764            if let Some(debounce) = debounce {
14765                cx.background_executor().timer(debounce).await;
14766            }
14767            let Some(snapshot) = editor
14768                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14769                .ok()
14770            else {
14771                return;
14772            };
14773
14774            let new_inline_diagnostics = cx
14775                .background_spawn(async move {
14776                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14777                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14778                        let message = diagnostic_entry
14779                            .diagnostic
14780                            .message
14781                            .split_once('\n')
14782                            .map(|(line, _)| line)
14783                            .map(SharedString::new)
14784                            .unwrap_or_else(|| {
14785                                SharedString::from(diagnostic_entry.diagnostic.message)
14786                            });
14787                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14788                        let (Ok(i) | Err(i)) = inline_diagnostics
14789                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14790                        inline_diagnostics.insert(
14791                            i,
14792                            (
14793                                start_anchor,
14794                                InlineDiagnostic {
14795                                    message,
14796                                    group_id: diagnostic_entry.diagnostic.group_id,
14797                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14798                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14799                                    severity: diagnostic_entry.diagnostic.severity,
14800                                },
14801                            ),
14802                        );
14803                    }
14804                    inline_diagnostics
14805                })
14806                .await;
14807
14808            editor
14809                .update(cx, |editor, cx| {
14810                    editor.inline_diagnostics = new_inline_diagnostics;
14811                    cx.notify();
14812                })
14813                .ok();
14814        });
14815    }
14816
14817    pub fn set_selections_from_remote(
14818        &mut self,
14819        selections: Vec<Selection<Anchor>>,
14820        pending_selection: Option<Selection<Anchor>>,
14821        window: &mut Window,
14822        cx: &mut Context<Self>,
14823    ) {
14824        let old_cursor_position = self.selections.newest_anchor().head();
14825        self.selections.change_with(cx, |s| {
14826            s.select_anchors(selections);
14827            if let Some(pending_selection) = pending_selection {
14828                s.set_pending(pending_selection, SelectMode::Character);
14829            } else {
14830                s.clear_pending();
14831            }
14832        });
14833        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14834    }
14835
14836    fn push_to_selection_history(&mut self) {
14837        self.selection_history.push(SelectionHistoryEntry {
14838            selections: self.selections.disjoint_anchors(),
14839            select_next_state: self.select_next_state.clone(),
14840            select_prev_state: self.select_prev_state.clone(),
14841            add_selections_state: self.add_selections_state.clone(),
14842        });
14843    }
14844
14845    pub fn transact(
14846        &mut self,
14847        window: &mut Window,
14848        cx: &mut Context<Self>,
14849        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14850    ) -> Option<TransactionId> {
14851        self.start_transaction_at(Instant::now(), window, cx);
14852        update(self, window, cx);
14853        self.end_transaction_at(Instant::now(), cx)
14854    }
14855
14856    pub fn start_transaction_at(
14857        &mut self,
14858        now: Instant,
14859        window: &mut Window,
14860        cx: &mut Context<Self>,
14861    ) {
14862        self.end_selection(window, cx);
14863        if let Some(tx_id) = self
14864            .buffer
14865            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14866        {
14867            self.selection_history
14868                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14869            cx.emit(EditorEvent::TransactionBegun {
14870                transaction_id: tx_id,
14871            })
14872        }
14873    }
14874
14875    pub fn end_transaction_at(
14876        &mut self,
14877        now: Instant,
14878        cx: &mut Context<Self>,
14879    ) -> Option<TransactionId> {
14880        if let Some(transaction_id) = self
14881            .buffer
14882            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14883        {
14884            if let Some((_, end_selections)) =
14885                self.selection_history.transaction_mut(transaction_id)
14886            {
14887                *end_selections = Some(self.selections.disjoint_anchors());
14888            } else {
14889                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14890            }
14891
14892            cx.emit(EditorEvent::Edited { transaction_id });
14893            Some(transaction_id)
14894        } else {
14895            None
14896        }
14897    }
14898
14899    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14900        if self.selection_mark_mode {
14901            self.change_selections(None, window, cx, |s| {
14902                s.move_with(|_, sel| {
14903                    sel.collapse_to(sel.head(), SelectionGoal::None);
14904                });
14905            })
14906        }
14907        self.selection_mark_mode = true;
14908        cx.notify();
14909    }
14910
14911    pub fn swap_selection_ends(
14912        &mut self,
14913        _: &actions::SwapSelectionEnds,
14914        window: &mut Window,
14915        cx: &mut Context<Self>,
14916    ) {
14917        self.change_selections(None, window, cx, |s| {
14918            s.move_with(|_, sel| {
14919                if sel.start != sel.end {
14920                    sel.reversed = !sel.reversed
14921                }
14922            });
14923        });
14924        self.request_autoscroll(Autoscroll::newest(), cx);
14925        cx.notify();
14926    }
14927
14928    pub fn toggle_fold(
14929        &mut self,
14930        _: &actions::ToggleFold,
14931        window: &mut Window,
14932        cx: &mut Context<Self>,
14933    ) {
14934        if self.is_singleton(cx) {
14935            let selection = self.selections.newest::<Point>(cx);
14936
14937            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14938            let range = if selection.is_empty() {
14939                let point = selection.head().to_display_point(&display_map);
14940                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14941                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14942                    .to_point(&display_map);
14943                start..end
14944            } else {
14945                selection.range()
14946            };
14947            if display_map.folds_in_range(range).next().is_some() {
14948                self.unfold_lines(&Default::default(), window, cx)
14949            } else {
14950                self.fold(&Default::default(), window, cx)
14951            }
14952        } else {
14953            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14954            let buffer_ids: HashSet<_> = self
14955                .selections
14956                .disjoint_anchor_ranges()
14957                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14958                .collect();
14959
14960            let should_unfold = buffer_ids
14961                .iter()
14962                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14963
14964            for buffer_id in buffer_ids {
14965                if should_unfold {
14966                    self.unfold_buffer(buffer_id, cx);
14967                } else {
14968                    self.fold_buffer(buffer_id, cx);
14969                }
14970            }
14971        }
14972    }
14973
14974    pub fn toggle_fold_recursive(
14975        &mut self,
14976        _: &actions::ToggleFoldRecursive,
14977        window: &mut Window,
14978        cx: &mut Context<Self>,
14979    ) {
14980        let selection = self.selections.newest::<Point>(cx);
14981
14982        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14983        let range = if selection.is_empty() {
14984            let point = selection.head().to_display_point(&display_map);
14985            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14986            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14987                .to_point(&display_map);
14988            start..end
14989        } else {
14990            selection.range()
14991        };
14992        if display_map.folds_in_range(range).next().is_some() {
14993            self.unfold_recursive(&Default::default(), window, cx)
14994        } else {
14995            self.fold_recursive(&Default::default(), window, cx)
14996        }
14997    }
14998
14999    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15000        if self.is_singleton(cx) {
15001            let mut to_fold = Vec::new();
15002            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15003            let selections = self.selections.all_adjusted(cx);
15004
15005            for selection in selections {
15006                let range = selection.range().sorted();
15007                let buffer_start_row = range.start.row;
15008
15009                if range.start.row != range.end.row {
15010                    let mut found = false;
15011                    let mut row = range.start.row;
15012                    while row <= range.end.row {
15013                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15014                        {
15015                            found = true;
15016                            row = crease.range().end.row + 1;
15017                            to_fold.push(crease);
15018                        } else {
15019                            row += 1
15020                        }
15021                    }
15022                    if found {
15023                        continue;
15024                    }
15025                }
15026
15027                for row in (0..=range.start.row).rev() {
15028                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15029                        if crease.range().end.row >= buffer_start_row {
15030                            to_fold.push(crease);
15031                            if row <= range.start.row {
15032                                break;
15033                            }
15034                        }
15035                    }
15036                }
15037            }
15038
15039            self.fold_creases(to_fold, true, window, cx);
15040        } else {
15041            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15042            let buffer_ids = self
15043                .selections
15044                .disjoint_anchor_ranges()
15045                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15046                .collect::<HashSet<_>>();
15047            for buffer_id in buffer_ids {
15048                self.fold_buffer(buffer_id, cx);
15049            }
15050        }
15051    }
15052
15053    fn fold_at_level(
15054        &mut self,
15055        fold_at: &FoldAtLevel,
15056        window: &mut Window,
15057        cx: &mut Context<Self>,
15058    ) {
15059        if !self.buffer.read(cx).is_singleton() {
15060            return;
15061        }
15062
15063        let fold_at_level = fold_at.0;
15064        let snapshot = self.buffer.read(cx).snapshot(cx);
15065        let mut to_fold = Vec::new();
15066        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15067
15068        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15069            while start_row < end_row {
15070                match self
15071                    .snapshot(window, cx)
15072                    .crease_for_buffer_row(MultiBufferRow(start_row))
15073                {
15074                    Some(crease) => {
15075                        let nested_start_row = crease.range().start.row + 1;
15076                        let nested_end_row = crease.range().end.row;
15077
15078                        if current_level < fold_at_level {
15079                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15080                        } else if current_level == fold_at_level {
15081                            to_fold.push(crease);
15082                        }
15083
15084                        start_row = nested_end_row + 1;
15085                    }
15086                    None => start_row += 1,
15087                }
15088            }
15089        }
15090
15091        self.fold_creases(to_fold, true, window, cx);
15092    }
15093
15094    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15095        if self.buffer.read(cx).is_singleton() {
15096            let mut fold_ranges = Vec::new();
15097            let snapshot = self.buffer.read(cx).snapshot(cx);
15098
15099            for row in 0..snapshot.max_row().0 {
15100                if let Some(foldable_range) = self
15101                    .snapshot(window, cx)
15102                    .crease_for_buffer_row(MultiBufferRow(row))
15103                {
15104                    fold_ranges.push(foldable_range);
15105                }
15106            }
15107
15108            self.fold_creases(fold_ranges, true, window, cx);
15109        } else {
15110            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15111                editor
15112                    .update_in(cx, |editor, _, cx| {
15113                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15114                            editor.fold_buffer(buffer_id, cx);
15115                        }
15116                    })
15117                    .ok();
15118            });
15119        }
15120    }
15121
15122    pub fn fold_function_bodies(
15123        &mut self,
15124        _: &actions::FoldFunctionBodies,
15125        window: &mut Window,
15126        cx: &mut Context<Self>,
15127    ) {
15128        let snapshot = self.buffer.read(cx).snapshot(cx);
15129
15130        let ranges = snapshot
15131            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15132            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15133            .collect::<Vec<_>>();
15134
15135        let creases = ranges
15136            .into_iter()
15137            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15138            .collect();
15139
15140        self.fold_creases(creases, true, window, cx);
15141    }
15142
15143    pub fn fold_recursive(
15144        &mut self,
15145        _: &actions::FoldRecursive,
15146        window: &mut Window,
15147        cx: &mut Context<Self>,
15148    ) {
15149        let mut to_fold = Vec::new();
15150        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15151        let selections = self.selections.all_adjusted(cx);
15152
15153        for selection in selections {
15154            let range = selection.range().sorted();
15155            let buffer_start_row = range.start.row;
15156
15157            if range.start.row != range.end.row {
15158                let mut found = false;
15159                for row in range.start.row..=range.end.row {
15160                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15161                        found = true;
15162                        to_fold.push(crease);
15163                    }
15164                }
15165                if found {
15166                    continue;
15167                }
15168            }
15169
15170            for row in (0..=range.start.row).rev() {
15171                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15172                    if crease.range().end.row >= buffer_start_row {
15173                        to_fold.push(crease);
15174                    } else {
15175                        break;
15176                    }
15177                }
15178            }
15179        }
15180
15181        self.fold_creases(to_fold, true, window, cx);
15182    }
15183
15184    pub fn fold_at(
15185        &mut self,
15186        buffer_row: MultiBufferRow,
15187        window: &mut Window,
15188        cx: &mut Context<Self>,
15189    ) {
15190        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15191
15192        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15193            let autoscroll = self
15194                .selections
15195                .all::<Point>(cx)
15196                .iter()
15197                .any(|selection| crease.range().overlaps(&selection.range()));
15198
15199            self.fold_creases(vec![crease], autoscroll, window, cx);
15200        }
15201    }
15202
15203    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15204        if self.is_singleton(cx) {
15205            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15206            let buffer = &display_map.buffer_snapshot;
15207            let selections = self.selections.all::<Point>(cx);
15208            let ranges = selections
15209                .iter()
15210                .map(|s| {
15211                    let range = s.display_range(&display_map).sorted();
15212                    let mut start = range.start.to_point(&display_map);
15213                    let mut end = range.end.to_point(&display_map);
15214                    start.column = 0;
15215                    end.column = buffer.line_len(MultiBufferRow(end.row));
15216                    start..end
15217                })
15218                .collect::<Vec<_>>();
15219
15220            self.unfold_ranges(&ranges, true, true, cx);
15221        } else {
15222            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15223            let buffer_ids = self
15224                .selections
15225                .disjoint_anchor_ranges()
15226                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15227                .collect::<HashSet<_>>();
15228            for buffer_id in buffer_ids {
15229                self.unfold_buffer(buffer_id, cx);
15230            }
15231        }
15232    }
15233
15234    pub fn unfold_recursive(
15235        &mut self,
15236        _: &UnfoldRecursive,
15237        _window: &mut Window,
15238        cx: &mut Context<Self>,
15239    ) {
15240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15241        let selections = self.selections.all::<Point>(cx);
15242        let ranges = selections
15243            .iter()
15244            .map(|s| {
15245                let mut range = s.display_range(&display_map).sorted();
15246                *range.start.column_mut() = 0;
15247                *range.end.column_mut() = display_map.line_len(range.end.row());
15248                let start = range.start.to_point(&display_map);
15249                let end = range.end.to_point(&display_map);
15250                start..end
15251            })
15252            .collect::<Vec<_>>();
15253
15254        self.unfold_ranges(&ranges, true, true, cx);
15255    }
15256
15257    pub fn unfold_at(
15258        &mut self,
15259        buffer_row: MultiBufferRow,
15260        _window: &mut Window,
15261        cx: &mut Context<Self>,
15262    ) {
15263        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15264
15265        let intersection_range = Point::new(buffer_row.0, 0)
15266            ..Point::new(
15267                buffer_row.0,
15268                display_map.buffer_snapshot.line_len(buffer_row),
15269            );
15270
15271        let autoscroll = self
15272            .selections
15273            .all::<Point>(cx)
15274            .iter()
15275            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15276
15277        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15278    }
15279
15280    pub fn unfold_all(
15281        &mut self,
15282        _: &actions::UnfoldAll,
15283        _window: &mut Window,
15284        cx: &mut Context<Self>,
15285    ) {
15286        if self.buffer.read(cx).is_singleton() {
15287            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15288            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15289        } else {
15290            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15291                editor
15292                    .update(cx, |editor, cx| {
15293                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15294                            editor.unfold_buffer(buffer_id, cx);
15295                        }
15296                    })
15297                    .ok();
15298            });
15299        }
15300    }
15301
15302    pub fn fold_selected_ranges(
15303        &mut self,
15304        _: &FoldSelectedRanges,
15305        window: &mut Window,
15306        cx: &mut Context<Self>,
15307    ) {
15308        let selections = self.selections.all_adjusted(cx);
15309        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15310        let ranges = selections
15311            .into_iter()
15312            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15313            .collect::<Vec<_>>();
15314        self.fold_creases(ranges, true, window, cx);
15315    }
15316
15317    pub fn fold_ranges<T: ToOffset + Clone>(
15318        &mut self,
15319        ranges: Vec<Range<T>>,
15320        auto_scroll: bool,
15321        window: &mut Window,
15322        cx: &mut Context<Self>,
15323    ) {
15324        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15325        let ranges = ranges
15326            .into_iter()
15327            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15328            .collect::<Vec<_>>();
15329        self.fold_creases(ranges, auto_scroll, window, cx);
15330    }
15331
15332    pub fn fold_creases<T: ToOffset + Clone>(
15333        &mut self,
15334        creases: Vec<Crease<T>>,
15335        auto_scroll: bool,
15336        _window: &mut Window,
15337        cx: &mut Context<Self>,
15338    ) {
15339        if creases.is_empty() {
15340            return;
15341        }
15342
15343        let mut buffers_affected = HashSet::default();
15344        let multi_buffer = self.buffer().read(cx);
15345        for crease in &creases {
15346            if let Some((_, buffer, _)) =
15347                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15348            {
15349                buffers_affected.insert(buffer.read(cx).remote_id());
15350            };
15351        }
15352
15353        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15354
15355        if auto_scroll {
15356            self.request_autoscroll(Autoscroll::fit(), cx);
15357        }
15358
15359        cx.notify();
15360
15361        self.scrollbar_marker_state.dirty = true;
15362        self.folds_did_change(cx);
15363    }
15364
15365    /// Removes any folds whose ranges intersect any of the given ranges.
15366    pub fn unfold_ranges<T: ToOffset + Clone>(
15367        &mut self,
15368        ranges: &[Range<T>],
15369        inclusive: bool,
15370        auto_scroll: bool,
15371        cx: &mut Context<Self>,
15372    ) {
15373        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15374            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15375        });
15376        self.folds_did_change(cx);
15377    }
15378
15379    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15380        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15381            return;
15382        }
15383        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15384        self.display_map.update(cx, |display_map, cx| {
15385            display_map.fold_buffers([buffer_id], cx)
15386        });
15387        cx.emit(EditorEvent::BufferFoldToggled {
15388            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15389            folded: true,
15390        });
15391        cx.notify();
15392    }
15393
15394    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15395        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15396            return;
15397        }
15398        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15399        self.display_map.update(cx, |display_map, cx| {
15400            display_map.unfold_buffers([buffer_id], cx);
15401        });
15402        cx.emit(EditorEvent::BufferFoldToggled {
15403            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15404            folded: false,
15405        });
15406        cx.notify();
15407    }
15408
15409    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15410        self.display_map.read(cx).is_buffer_folded(buffer)
15411    }
15412
15413    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15414        self.display_map.read(cx).folded_buffers()
15415    }
15416
15417    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15418        self.display_map.update(cx, |display_map, cx| {
15419            display_map.disable_header_for_buffer(buffer_id, cx);
15420        });
15421        cx.notify();
15422    }
15423
15424    /// Removes any folds with the given ranges.
15425    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15426        &mut self,
15427        ranges: &[Range<T>],
15428        type_id: TypeId,
15429        auto_scroll: bool,
15430        cx: &mut Context<Self>,
15431    ) {
15432        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15433            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15434        });
15435        self.folds_did_change(cx);
15436    }
15437
15438    fn remove_folds_with<T: ToOffset + Clone>(
15439        &mut self,
15440        ranges: &[Range<T>],
15441        auto_scroll: bool,
15442        cx: &mut Context<Self>,
15443        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15444    ) {
15445        if ranges.is_empty() {
15446            return;
15447        }
15448
15449        let mut buffers_affected = HashSet::default();
15450        let multi_buffer = self.buffer().read(cx);
15451        for range in ranges {
15452            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15453                buffers_affected.insert(buffer.read(cx).remote_id());
15454            };
15455        }
15456
15457        self.display_map.update(cx, update);
15458
15459        if auto_scroll {
15460            self.request_autoscroll(Autoscroll::fit(), cx);
15461        }
15462
15463        cx.notify();
15464        self.scrollbar_marker_state.dirty = true;
15465        self.active_indent_guides_state.dirty = true;
15466    }
15467
15468    pub fn update_fold_widths(
15469        &mut self,
15470        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15471        cx: &mut Context<Self>,
15472    ) -> bool {
15473        self.display_map
15474            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15475    }
15476
15477    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15478        self.display_map.read(cx).fold_placeholder.clone()
15479    }
15480
15481    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15482        self.buffer.update(cx, |buffer, cx| {
15483            buffer.set_all_diff_hunks_expanded(cx);
15484        });
15485    }
15486
15487    pub fn expand_all_diff_hunks(
15488        &mut self,
15489        _: &ExpandAllDiffHunks,
15490        _window: &mut Window,
15491        cx: &mut Context<Self>,
15492    ) {
15493        self.buffer.update(cx, |buffer, cx| {
15494            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15495        });
15496    }
15497
15498    pub fn toggle_selected_diff_hunks(
15499        &mut self,
15500        _: &ToggleSelectedDiffHunks,
15501        _window: &mut Window,
15502        cx: &mut Context<Self>,
15503    ) {
15504        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15505        self.toggle_diff_hunks_in_ranges(ranges, cx);
15506    }
15507
15508    pub fn diff_hunks_in_ranges<'a>(
15509        &'a self,
15510        ranges: &'a [Range<Anchor>],
15511        buffer: &'a MultiBufferSnapshot,
15512    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15513        ranges.iter().flat_map(move |range| {
15514            let end_excerpt_id = range.end.excerpt_id;
15515            let range = range.to_point(buffer);
15516            let mut peek_end = range.end;
15517            if range.end.row < buffer.max_row().0 {
15518                peek_end = Point::new(range.end.row + 1, 0);
15519            }
15520            buffer
15521                .diff_hunks_in_range(range.start..peek_end)
15522                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15523        })
15524    }
15525
15526    pub fn has_stageable_diff_hunks_in_ranges(
15527        &self,
15528        ranges: &[Range<Anchor>],
15529        snapshot: &MultiBufferSnapshot,
15530    ) -> bool {
15531        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15532        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15533    }
15534
15535    pub fn toggle_staged_selected_diff_hunks(
15536        &mut self,
15537        _: &::git::ToggleStaged,
15538        _: &mut Window,
15539        cx: &mut Context<Self>,
15540    ) {
15541        let snapshot = self.buffer.read(cx).snapshot(cx);
15542        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15543        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15544        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15545    }
15546
15547    pub fn set_render_diff_hunk_controls(
15548        &mut self,
15549        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15550        cx: &mut Context<Self>,
15551    ) {
15552        self.render_diff_hunk_controls = render_diff_hunk_controls;
15553        cx.notify();
15554    }
15555
15556    pub fn stage_and_next(
15557        &mut self,
15558        _: &::git::StageAndNext,
15559        window: &mut Window,
15560        cx: &mut Context<Self>,
15561    ) {
15562        self.do_stage_or_unstage_and_next(true, window, cx);
15563    }
15564
15565    pub fn unstage_and_next(
15566        &mut self,
15567        _: &::git::UnstageAndNext,
15568        window: &mut Window,
15569        cx: &mut Context<Self>,
15570    ) {
15571        self.do_stage_or_unstage_and_next(false, window, cx);
15572    }
15573
15574    pub fn stage_or_unstage_diff_hunks(
15575        &mut self,
15576        stage: bool,
15577        ranges: Vec<Range<Anchor>>,
15578        cx: &mut Context<Self>,
15579    ) {
15580        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15581        cx.spawn(async move |this, cx| {
15582            task.await?;
15583            this.update(cx, |this, cx| {
15584                let snapshot = this.buffer.read(cx).snapshot(cx);
15585                let chunk_by = this
15586                    .diff_hunks_in_ranges(&ranges, &snapshot)
15587                    .chunk_by(|hunk| hunk.buffer_id);
15588                for (buffer_id, hunks) in &chunk_by {
15589                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15590                }
15591            })
15592        })
15593        .detach_and_log_err(cx);
15594    }
15595
15596    fn save_buffers_for_ranges_if_needed(
15597        &mut self,
15598        ranges: &[Range<Anchor>],
15599        cx: &mut Context<Editor>,
15600    ) -> Task<Result<()>> {
15601        let multibuffer = self.buffer.read(cx);
15602        let snapshot = multibuffer.read(cx);
15603        let buffer_ids: HashSet<_> = ranges
15604            .iter()
15605            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15606            .collect();
15607        drop(snapshot);
15608
15609        let mut buffers = HashSet::default();
15610        for buffer_id in buffer_ids {
15611            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15612                let buffer = buffer_entity.read(cx);
15613                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15614                {
15615                    buffers.insert(buffer_entity);
15616                }
15617            }
15618        }
15619
15620        if let Some(project) = &self.project {
15621            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15622        } else {
15623            Task::ready(Ok(()))
15624        }
15625    }
15626
15627    fn do_stage_or_unstage_and_next(
15628        &mut self,
15629        stage: bool,
15630        window: &mut Window,
15631        cx: &mut Context<Self>,
15632    ) {
15633        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15634
15635        if ranges.iter().any(|range| range.start != range.end) {
15636            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15637            return;
15638        }
15639
15640        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15641        let snapshot = self.snapshot(window, cx);
15642        let position = self.selections.newest::<Point>(cx).head();
15643        let mut row = snapshot
15644            .buffer_snapshot
15645            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15646            .find(|hunk| hunk.row_range.start.0 > position.row)
15647            .map(|hunk| hunk.row_range.start);
15648
15649        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15650        // Outside of the project diff editor, wrap around to the beginning.
15651        if !all_diff_hunks_expanded {
15652            row = row.or_else(|| {
15653                snapshot
15654                    .buffer_snapshot
15655                    .diff_hunks_in_range(Point::zero()..position)
15656                    .find(|hunk| hunk.row_range.end.0 < position.row)
15657                    .map(|hunk| hunk.row_range.start)
15658            });
15659        }
15660
15661        if let Some(row) = row {
15662            let destination = Point::new(row.0, 0);
15663            let autoscroll = Autoscroll::center();
15664
15665            self.unfold_ranges(&[destination..destination], false, false, cx);
15666            self.change_selections(Some(autoscroll), window, cx, |s| {
15667                s.select_ranges([destination..destination]);
15668            });
15669        }
15670    }
15671
15672    fn do_stage_or_unstage(
15673        &self,
15674        stage: bool,
15675        buffer_id: BufferId,
15676        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15677        cx: &mut App,
15678    ) -> Option<()> {
15679        let project = self.project.as_ref()?;
15680        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15681        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15682        let buffer_snapshot = buffer.read(cx).snapshot();
15683        let file_exists = buffer_snapshot
15684            .file()
15685            .is_some_and(|file| file.disk_state().exists());
15686        diff.update(cx, |diff, cx| {
15687            diff.stage_or_unstage_hunks(
15688                stage,
15689                &hunks
15690                    .map(|hunk| buffer_diff::DiffHunk {
15691                        buffer_range: hunk.buffer_range,
15692                        diff_base_byte_range: hunk.diff_base_byte_range,
15693                        secondary_status: hunk.secondary_status,
15694                        range: Point::zero()..Point::zero(), // unused
15695                    })
15696                    .collect::<Vec<_>>(),
15697                &buffer_snapshot,
15698                file_exists,
15699                cx,
15700            )
15701        });
15702        None
15703    }
15704
15705    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15706        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15707        self.buffer
15708            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15709    }
15710
15711    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15712        self.buffer.update(cx, |buffer, cx| {
15713            let ranges = vec![Anchor::min()..Anchor::max()];
15714            if !buffer.all_diff_hunks_expanded()
15715                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15716            {
15717                buffer.collapse_diff_hunks(ranges, cx);
15718                true
15719            } else {
15720                false
15721            }
15722        })
15723    }
15724
15725    fn toggle_diff_hunks_in_ranges(
15726        &mut self,
15727        ranges: Vec<Range<Anchor>>,
15728        cx: &mut Context<Editor>,
15729    ) {
15730        self.buffer.update(cx, |buffer, cx| {
15731            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15732            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15733        })
15734    }
15735
15736    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15737        self.buffer.update(cx, |buffer, cx| {
15738            let snapshot = buffer.snapshot(cx);
15739            let excerpt_id = range.end.excerpt_id;
15740            let point_range = range.to_point(&snapshot);
15741            let expand = !buffer.single_hunk_is_expanded(range, cx);
15742            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15743        })
15744    }
15745
15746    pub(crate) fn apply_all_diff_hunks(
15747        &mut self,
15748        _: &ApplyAllDiffHunks,
15749        window: &mut Window,
15750        cx: &mut Context<Self>,
15751    ) {
15752        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15753
15754        let buffers = self.buffer.read(cx).all_buffers();
15755        for branch_buffer in buffers {
15756            branch_buffer.update(cx, |branch_buffer, cx| {
15757                branch_buffer.merge_into_base(Vec::new(), cx);
15758            });
15759        }
15760
15761        if let Some(project) = self.project.clone() {
15762            self.save(true, project, window, cx).detach_and_log_err(cx);
15763        }
15764    }
15765
15766    pub(crate) fn apply_selected_diff_hunks(
15767        &mut self,
15768        _: &ApplyDiffHunk,
15769        window: &mut Window,
15770        cx: &mut Context<Self>,
15771    ) {
15772        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15773        let snapshot = self.snapshot(window, cx);
15774        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15775        let mut ranges_by_buffer = HashMap::default();
15776        self.transact(window, cx, |editor, _window, cx| {
15777            for hunk in hunks {
15778                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15779                    ranges_by_buffer
15780                        .entry(buffer.clone())
15781                        .or_insert_with(Vec::new)
15782                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15783                }
15784            }
15785
15786            for (buffer, ranges) in ranges_by_buffer {
15787                buffer.update(cx, |buffer, cx| {
15788                    buffer.merge_into_base(ranges, cx);
15789                });
15790            }
15791        });
15792
15793        if let Some(project) = self.project.clone() {
15794            self.save(true, project, window, cx).detach_and_log_err(cx);
15795        }
15796    }
15797
15798    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15799        if hovered != self.gutter_hovered {
15800            self.gutter_hovered = hovered;
15801            cx.notify();
15802        }
15803    }
15804
15805    pub fn insert_blocks(
15806        &mut self,
15807        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15808        autoscroll: Option<Autoscroll>,
15809        cx: &mut Context<Self>,
15810    ) -> Vec<CustomBlockId> {
15811        let blocks = self
15812            .display_map
15813            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15814        if let Some(autoscroll) = autoscroll {
15815            self.request_autoscroll(autoscroll, cx);
15816        }
15817        cx.notify();
15818        blocks
15819    }
15820
15821    pub fn resize_blocks(
15822        &mut self,
15823        heights: HashMap<CustomBlockId, u32>,
15824        autoscroll: Option<Autoscroll>,
15825        cx: &mut Context<Self>,
15826    ) {
15827        self.display_map
15828            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15829        if let Some(autoscroll) = autoscroll {
15830            self.request_autoscroll(autoscroll, cx);
15831        }
15832        cx.notify();
15833    }
15834
15835    pub fn replace_blocks(
15836        &mut self,
15837        renderers: HashMap<CustomBlockId, RenderBlock>,
15838        autoscroll: Option<Autoscroll>,
15839        cx: &mut Context<Self>,
15840    ) {
15841        self.display_map
15842            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15843        if let Some(autoscroll) = autoscroll {
15844            self.request_autoscroll(autoscroll, cx);
15845        }
15846        cx.notify();
15847    }
15848
15849    pub fn remove_blocks(
15850        &mut self,
15851        block_ids: HashSet<CustomBlockId>,
15852        autoscroll: Option<Autoscroll>,
15853        cx: &mut Context<Self>,
15854    ) {
15855        self.display_map.update(cx, |display_map, cx| {
15856            display_map.remove_blocks(block_ids, cx)
15857        });
15858        if let Some(autoscroll) = autoscroll {
15859            self.request_autoscroll(autoscroll, cx);
15860        }
15861        cx.notify();
15862    }
15863
15864    pub fn row_for_block(
15865        &self,
15866        block_id: CustomBlockId,
15867        cx: &mut Context<Self>,
15868    ) -> Option<DisplayRow> {
15869        self.display_map
15870            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15871    }
15872
15873    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15874        self.focused_block = Some(focused_block);
15875    }
15876
15877    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15878        self.focused_block.take()
15879    }
15880
15881    pub fn insert_creases(
15882        &mut self,
15883        creases: impl IntoIterator<Item = Crease<Anchor>>,
15884        cx: &mut Context<Self>,
15885    ) -> Vec<CreaseId> {
15886        self.display_map
15887            .update(cx, |map, cx| map.insert_creases(creases, cx))
15888    }
15889
15890    pub fn remove_creases(
15891        &mut self,
15892        ids: impl IntoIterator<Item = CreaseId>,
15893        cx: &mut Context<Self>,
15894    ) {
15895        self.display_map
15896            .update(cx, |map, cx| map.remove_creases(ids, cx));
15897    }
15898
15899    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15900        self.display_map
15901            .update(cx, |map, cx| map.snapshot(cx))
15902            .longest_row()
15903    }
15904
15905    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15906        self.display_map
15907            .update(cx, |map, cx| map.snapshot(cx))
15908            .max_point()
15909    }
15910
15911    pub fn text(&self, cx: &App) -> String {
15912        self.buffer.read(cx).read(cx).text()
15913    }
15914
15915    pub fn is_empty(&self, cx: &App) -> bool {
15916        self.buffer.read(cx).read(cx).is_empty()
15917    }
15918
15919    pub fn text_option(&self, cx: &App) -> Option<String> {
15920        let text = self.text(cx);
15921        let text = text.trim();
15922
15923        if text.is_empty() {
15924            return None;
15925        }
15926
15927        Some(text.to_string())
15928    }
15929
15930    pub fn set_text(
15931        &mut self,
15932        text: impl Into<Arc<str>>,
15933        window: &mut Window,
15934        cx: &mut Context<Self>,
15935    ) {
15936        self.transact(window, cx, |this, _, cx| {
15937            this.buffer
15938                .read(cx)
15939                .as_singleton()
15940                .expect("you can only call set_text on editors for singleton buffers")
15941                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15942        });
15943    }
15944
15945    pub fn display_text(&self, cx: &mut App) -> String {
15946        self.display_map
15947            .update(cx, |map, cx| map.snapshot(cx))
15948            .text()
15949    }
15950
15951    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15952        let mut wrap_guides = smallvec::smallvec![];
15953
15954        if self.show_wrap_guides == Some(false) {
15955            return wrap_guides;
15956        }
15957
15958        let settings = self.buffer.read(cx).language_settings(cx);
15959        if settings.show_wrap_guides {
15960            match self.soft_wrap_mode(cx) {
15961                SoftWrap::Column(soft_wrap) => {
15962                    wrap_guides.push((soft_wrap as usize, true));
15963                }
15964                SoftWrap::Bounded(soft_wrap) => {
15965                    wrap_guides.push((soft_wrap as usize, true));
15966                }
15967                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15968            }
15969            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15970        }
15971
15972        wrap_guides
15973    }
15974
15975    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15976        let settings = self.buffer.read(cx).language_settings(cx);
15977        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15978        match mode {
15979            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15980                SoftWrap::None
15981            }
15982            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15983            language_settings::SoftWrap::PreferredLineLength => {
15984                SoftWrap::Column(settings.preferred_line_length)
15985            }
15986            language_settings::SoftWrap::Bounded => {
15987                SoftWrap::Bounded(settings.preferred_line_length)
15988            }
15989        }
15990    }
15991
15992    pub fn set_soft_wrap_mode(
15993        &mut self,
15994        mode: language_settings::SoftWrap,
15995
15996        cx: &mut Context<Self>,
15997    ) {
15998        self.soft_wrap_mode_override = Some(mode);
15999        cx.notify();
16000    }
16001
16002    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16003        self.hard_wrap = hard_wrap;
16004        cx.notify();
16005    }
16006
16007    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16008        self.text_style_refinement = Some(style);
16009    }
16010
16011    /// called by the Element so we know what style we were most recently rendered with.
16012    pub(crate) fn set_style(
16013        &mut self,
16014        style: EditorStyle,
16015        window: &mut Window,
16016        cx: &mut Context<Self>,
16017    ) {
16018        let rem_size = window.rem_size();
16019        self.display_map.update(cx, |map, cx| {
16020            map.set_font(
16021                style.text.font(),
16022                style.text.font_size.to_pixels(rem_size),
16023                cx,
16024            )
16025        });
16026        self.style = Some(style);
16027    }
16028
16029    pub fn style(&self) -> Option<&EditorStyle> {
16030        self.style.as_ref()
16031    }
16032
16033    // Called by the element. This method is not designed to be called outside of the editor
16034    // element's layout code because it does not notify when rewrapping is computed synchronously.
16035    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16036        self.display_map
16037            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16038    }
16039
16040    pub fn set_soft_wrap(&mut self) {
16041        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16042    }
16043
16044    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16045        if self.soft_wrap_mode_override.is_some() {
16046            self.soft_wrap_mode_override.take();
16047        } else {
16048            let soft_wrap = match self.soft_wrap_mode(cx) {
16049                SoftWrap::GitDiff => return,
16050                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16051                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16052                    language_settings::SoftWrap::None
16053                }
16054            };
16055            self.soft_wrap_mode_override = Some(soft_wrap);
16056        }
16057        cx.notify();
16058    }
16059
16060    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16061        let Some(workspace) = self.workspace() else {
16062            return;
16063        };
16064        let fs = workspace.read(cx).app_state().fs.clone();
16065        let current_show = TabBarSettings::get_global(cx).show;
16066        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16067            setting.show = Some(!current_show);
16068        });
16069    }
16070
16071    pub fn toggle_indent_guides(
16072        &mut self,
16073        _: &ToggleIndentGuides,
16074        _: &mut Window,
16075        cx: &mut Context<Self>,
16076    ) {
16077        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16078            self.buffer
16079                .read(cx)
16080                .language_settings(cx)
16081                .indent_guides
16082                .enabled
16083        });
16084        self.show_indent_guides = Some(!currently_enabled);
16085        cx.notify();
16086    }
16087
16088    fn should_show_indent_guides(&self) -> Option<bool> {
16089        self.show_indent_guides
16090    }
16091
16092    pub fn toggle_line_numbers(
16093        &mut self,
16094        _: &ToggleLineNumbers,
16095        _: &mut Window,
16096        cx: &mut Context<Self>,
16097    ) {
16098        let mut editor_settings = EditorSettings::get_global(cx).clone();
16099        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16100        EditorSettings::override_global(editor_settings, cx);
16101    }
16102
16103    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16104        if let Some(show_line_numbers) = self.show_line_numbers {
16105            return show_line_numbers;
16106        }
16107        EditorSettings::get_global(cx).gutter.line_numbers
16108    }
16109
16110    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16111        self.use_relative_line_numbers
16112            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16113    }
16114
16115    pub fn toggle_relative_line_numbers(
16116        &mut self,
16117        _: &ToggleRelativeLineNumbers,
16118        _: &mut Window,
16119        cx: &mut Context<Self>,
16120    ) {
16121        let is_relative = self.should_use_relative_line_numbers(cx);
16122        self.set_relative_line_number(Some(!is_relative), cx)
16123    }
16124
16125    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16126        self.use_relative_line_numbers = is_relative;
16127        cx.notify();
16128    }
16129
16130    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16131        self.show_gutter = show_gutter;
16132        cx.notify();
16133    }
16134
16135    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16136        self.show_scrollbars = show_scrollbars;
16137        cx.notify();
16138    }
16139
16140    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16141        self.show_line_numbers = Some(show_line_numbers);
16142        cx.notify();
16143    }
16144
16145    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16146        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16147        cx.notify();
16148    }
16149
16150    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16151        self.show_code_actions = Some(show_code_actions);
16152        cx.notify();
16153    }
16154
16155    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16156        self.show_runnables = Some(show_runnables);
16157        cx.notify();
16158    }
16159
16160    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16161        self.show_breakpoints = Some(show_breakpoints);
16162        cx.notify();
16163    }
16164
16165    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16166        if self.display_map.read(cx).masked != masked {
16167            self.display_map.update(cx, |map, _| map.masked = masked);
16168        }
16169        cx.notify()
16170    }
16171
16172    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16173        self.show_wrap_guides = Some(show_wrap_guides);
16174        cx.notify();
16175    }
16176
16177    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16178        self.show_indent_guides = Some(show_indent_guides);
16179        cx.notify();
16180    }
16181
16182    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16183        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16184            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16185                if let Some(dir) = file.abs_path(cx).parent() {
16186                    return Some(dir.to_owned());
16187                }
16188            }
16189
16190            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16191                return Some(project_path.path.to_path_buf());
16192            }
16193        }
16194
16195        None
16196    }
16197
16198    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16199        self.active_excerpt(cx)?
16200            .1
16201            .read(cx)
16202            .file()
16203            .and_then(|f| f.as_local())
16204    }
16205
16206    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16207        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16208            let buffer = buffer.read(cx);
16209            if let Some(project_path) = buffer.project_path(cx) {
16210                let project = self.project.as_ref()?.read(cx);
16211                project.absolute_path(&project_path, cx)
16212            } else {
16213                buffer
16214                    .file()
16215                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16216            }
16217        })
16218    }
16219
16220    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16221        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16222            let project_path = buffer.read(cx).project_path(cx)?;
16223            let project = self.project.as_ref()?.read(cx);
16224            let entry = project.entry_for_path(&project_path, cx)?;
16225            let path = entry.path.to_path_buf();
16226            Some(path)
16227        })
16228    }
16229
16230    pub fn reveal_in_finder(
16231        &mut self,
16232        _: &RevealInFileManager,
16233        _window: &mut Window,
16234        cx: &mut Context<Self>,
16235    ) {
16236        if let Some(target) = self.target_file(cx) {
16237            cx.reveal_path(&target.abs_path(cx));
16238        }
16239    }
16240
16241    pub fn copy_path(
16242        &mut self,
16243        _: &zed_actions::workspace::CopyPath,
16244        _window: &mut Window,
16245        cx: &mut Context<Self>,
16246    ) {
16247        if let Some(path) = self.target_file_abs_path(cx) {
16248            if let Some(path) = path.to_str() {
16249                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16250            }
16251        }
16252    }
16253
16254    pub fn copy_relative_path(
16255        &mut self,
16256        _: &zed_actions::workspace::CopyRelativePath,
16257        _window: &mut Window,
16258        cx: &mut Context<Self>,
16259    ) {
16260        if let Some(path) = self.target_file_path(cx) {
16261            if let Some(path) = path.to_str() {
16262                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16263            }
16264        }
16265    }
16266
16267    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16268        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16269            buffer.read(cx).project_path(cx)
16270        } else {
16271            None
16272        }
16273    }
16274
16275    // Returns true if the editor handled a go-to-line request
16276    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16277        maybe!({
16278            let breakpoint_store = self.breakpoint_store.as_ref()?;
16279
16280            let Some((_, _, active_position)) =
16281                breakpoint_store.read(cx).active_position().cloned()
16282            else {
16283                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16284                return None;
16285            };
16286
16287            let snapshot = self
16288                .project
16289                .as_ref()?
16290                .read(cx)
16291                .buffer_for_id(active_position.buffer_id?, cx)?
16292                .read(cx)
16293                .snapshot();
16294
16295            let mut handled = false;
16296            for (id, ExcerptRange { context, .. }) in self
16297                .buffer
16298                .read(cx)
16299                .excerpts_for_buffer(active_position.buffer_id?, cx)
16300            {
16301                if context.start.cmp(&active_position, &snapshot).is_ge()
16302                    || context.end.cmp(&active_position, &snapshot).is_lt()
16303                {
16304                    continue;
16305                }
16306                let snapshot = self.buffer.read(cx).snapshot(cx);
16307                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16308
16309                handled = true;
16310                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16311                self.go_to_line::<DebugCurrentRowHighlight>(
16312                    multibuffer_anchor,
16313                    Some(cx.theme().colors().editor_debugger_active_line_background),
16314                    window,
16315                    cx,
16316                );
16317
16318                cx.notify();
16319            }
16320            handled.then_some(())
16321        })
16322        .is_some()
16323    }
16324
16325    pub fn copy_file_name_without_extension(
16326        &mut self,
16327        _: &CopyFileNameWithoutExtension,
16328        _: &mut Window,
16329        cx: &mut Context<Self>,
16330    ) {
16331        if let Some(file) = self.target_file(cx) {
16332            if let Some(file_stem) = file.path().file_stem() {
16333                if let Some(name) = file_stem.to_str() {
16334                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16335                }
16336            }
16337        }
16338    }
16339
16340    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16341        if let Some(file) = self.target_file(cx) {
16342            if let Some(file_name) = file.path().file_name() {
16343                if let Some(name) = file_name.to_str() {
16344                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16345                }
16346            }
16347        }
16348    }
16349
16350    pub fn toggle_git_blame(
16351        &mut self,
16352        _: &::git::Blame,
16353        window: &mut Window,
16354        cx: &mut Context<Self>,
16355    ) {
16356        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16357
16358        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16359            self.start_git_blame(true, window, cx);
16360        }
16361
16362        cx.notify();
16363    }
16364
16365    pub fn toggle_git_blame_inline(
16366        &mut self,
16367        _: &ToggleGitBlameInline,
16368        window: &mut Window,
16369        cx: &mut Context<Self>,
16370    ) {
16371        self.toggle_git_blame_inline_internal(true, window, cx);
16372        cx.notify();
16373    }
16374
16375    pub fn open_git_blame_commit(
16376        &mut self,
16377        _: &OpenGitBlameCommit,
16378        window: &mut Window,
16379        cx: &mut Context<Self>,
16380    ) {
16381        self.open_git_blame_commit_internal(window, cx);
16382    }
16383
16384    fn open_git_blame_commit_internal(
16385        &mut self,
16386        window: &mut Window,
16387        cx: &mut Context<Self>,
16388    ) -> Option<()> {
16389        let blame = self.blame.as_ref()?;
16390        let snapshot = self.snapshot(window, cx);
16391        let cursor = self.selections.newest::<Point>(cx).head();
16392        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16393        let blame_entry = blame
16394            .update(cx, |blame, cx| {
16395                blame
16396                    .blame_for_rows(
16397                        &[RowInfo {
16398                            buffer_id: Some(buffer.remote_id()),
16399                            buffer_row: Some(point.row),
16400                            ..Default::default()
16401                        }],
16402                        cx,
16403                    )
16404                    .next()
16405            })
16406            .flatten()?;
16407        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16408        let repo = blame.read(cx).repository(cx)?;
16409        let workspace = self.workspace()?.downgrade();
16410        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16411        None
16412    }
16413
16414    pub fn git_blame_inline_enabled(&self) -> bool {
16415        self.git_blame_inline_enabled
16416    }
16417
16418    pub fn toggle_selection_menu(
16419        &mut self,
16420        _: &ToggleSelectionMenu,
16421        _: &mut Window,
16422        cx: &mut Context<Self>,
16423    ) {
16424        self.show_selection_menu = self
16425            .show_selection_menu
16426            .map(|show_selections_menu| !show_selections_menu)
16427            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16428
16429        cx.notify();
16430    }
16431
16432    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16433        self.show_selection_menu
16434            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16435    }
16436
16437    fn start_git_blame(
16438        &mut self,
16439        user_triggered: bool,
16440        window: &mut Window,
16441        cx: &mut Context<Self>,
16442    ) {
16443        if let Some(project) = self.project.as_ref() {
16444            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16445                return;
16446            };
16447
16448            if buffer.read(cx).file().is_none() {
16449                return;
16450            }
16451
16452            let focused = self.focus_handle(cx).contains_focused(window, cx);
16453
16454            let project = project.clone();
16455            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16456            self.blame_subscription =
16457                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16458            self.blame = Some(blame);
16459        }
16460    }
16461
16462    fn toggle_git_blame_inline_internal(
16463        &mut self,
16464        user_triggered: bool,
16465        window: &mut Window,
16466        cx: &mut Context<Self>,
16467    ) {
16468        if self.git_blame_inline_enabled {
16469            self.git_blame_inline_enabled = false;
16470            self.show_git_blame_inline = false;
16471            self.show_git_blame_inline_delay_task.take();
16472        } else {
16473            self.git_blame_inline_enabled = true;
16474            self.start_git_blame_inline(user_triggered, window, cx);
16475        }
16476
16477        cx.notify();
16478    }
16479
16480    fn start_git_blame_inline(
16481        &mut self,
16482        user_triggered: bool,
16483        window: &mut Window,
16484        cx: &mut Context<Self>,
16485    ) {
16486        self.start_git_blame(user_triggered, window, cx);
16487
16488        if ProjectSettings::get_global(cx)
16489            .git
16490            .inline_blame_delay()
16491            .is_some()
16492        {
16493            self.start_inline_blame_timer(window, cx);
16494        } else {
16495            self.show_git_blame_inline = true
16496        }
16497    }
16498
16499    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16500        self.blame.as_ref()
16501    }
16502
16503    pub fn show_git_blame_gutter(&self) -> bool {
16504        self.show_git_blame_gutter
16505    }
16506
16507    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16508        self.show_git_blame_gutter && self.has_blame_entries(cx)
16509    }
16510
16511    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16512        self.show_git_blame_inline
16513            && (self.focus_handle.is_focused(window)
16514                || self
16515                    .git_blame_inline_tooltip
16516                    .as_ref()
16517                    .and_then(|t| t.upgrade())
16518                    .is_some())
16519            && !self.newest_selection_head_on_empty_line(cx)
16520            && self.has_blame_entries(cx)
16521    }
16522
16523    fn has_blame_entries(&self, cx: &App) -> bool {
16524        self.blame()
16525            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16526    }
16527
16528    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16529        let cursor_anchor = self.selections.newest_anchor().head();
16530
16531        let snapshot = self.buffer.read(cx).snapshot(cx);
16532        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16533
16534        snapshot.line_len(buffer_row) == 0
16535    }
16536
16537    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16538        let buffer_and_selection = maybe!({
16539            let selection = self.selections.newest::<Point>(cx);
16540            let selection_range = selection.range();
16541
16542            let multi_buffer = self.buffer().read(cx);
16543            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16544            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16545
16546            let (buffer, range, _) = if selection.reversed {
16547                buffer_ranges.first()
16548            } else {
16549                buffer_ranges.last()
16550            }?;
16551
16552            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16553                ..text::ToPoint::to_point(&range.end, &buffer).row;
16554            Some((
16555                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16556                selection,
16557            ))
16558        });
16559
16560        let Some((buffer, selection)) = buffer_and_selection else {
16561            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16562        };
16563
16564        let Some(project) = self.project.as_ref() else {
16565            return Task::ready(Err(anyhow!("editor does not have project")));
16566        };
16567
16568        project.update(cx, |project, cx| {
16569            project.get_permalink_to_line(&buffer, selection, cx)
16570        })
16571    }
16572
16573    pub fn copy_permalink_to_line(
16574        &mut self,
16575        _: &CopyPermalinkToLine,
16576        window: &mut Window,
16577        cx: &mut Context<Self>,
16578    ) {
16579        let permalink_task = self.get_permalink_to_line(cx);
16580        let workspace = self.workspace();
16581
16582        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16583            Ok(permalink) => {
16584                cx.update(|_, cx| {
16585                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16586                })
16587                .ok();
16588            }
16589            Err(err) => {
16590                let message = format!("Failed to copy permalink: {err}");
16591
16592                Err::<(), anyhow::Error>(err).log_err();
16593
16594                if let Some(workspace) = workspace {
16595                    workspace
16596                        .update_in(cx, |workspace, _, cx| {
16597                            struct CopyPermalinkToLine;
16598
16599                            workspace.show_toast(
16600                                Toast::new(
16601                                    NotificationId::unique::<CopyPermalinkToLine>(),
16602                                    message,
16603                                ),
16604                                cx,
16605                            )
16606                        })
16607                        .ok();
16608                }
16609            }
16610        })
16611        .detach();
16612    }
16613
16614    pub fn copy_file_location(
16615        &mut self,
16616        _: &CopyFileLocation,
16617        _: &mut Window,
16618        cx: &mut Context<Self>,
16619    ) {
16620        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16621        if let Some(file) = self.target_file(cx) {
16622            if let Some(path) = file.path().to_str() {
16623                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16624            }
16625        }
16626    }
16627
16628    pub fn open_permalink_to_line(
16629        &mut self,
16630        _: &OpenPermalinkToLine,
16631        window: &mut Window,
16632        cx: &mut Context<Self>,
16633    ) {
16634        let permalink_task = self.get_permalink_to_line(cx);
16635        let workspace = self.workspace();
16636
16637        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16638            Ok(permalink) => {
16639                cx.update(|_, cx| {
16640                    cx.open_url(permalink.as_ref());
16641                })
16642                .ok();
16643            }
16644            Err(err) => {
16645                let message = format!("Failed to open permalink: {err}");
16646
16647                Err::<(), anyhow::Error>(err).log_err();
16648
16649                if let Some(workspace) = workspace {
16650                    workspace
16651                        .update(cx, |workspace, cx| {
16652                            struct OpenPermalinkToLine;
16653
16654                            workspace.show_toast(
16655                                Toast::new(
16656                                    NotificationId::unique::<OpenPermalinkToLine>(),
16657                                    message,
16658                                ),
16659                                cx,
16660                            )
16661                        })
16662                        .ok();
16663                }
16664            }
16665        })
16666        .detach();
16667    }
16668
16669    pub fn insert_uuid_v4(
16670        &mut self,
16671        _: &InsertUuidV4,
16672        window: &mut Window,
16673        cx: &mut Context<Self>,
16674    ) {
16675        self.insert_uuid(UuidVersion::V4, window, cx);
16676    }
16677
16678    pub fn insert_uuid_v7(
16679        &mut self,
16680        _: &InsertUuidV7,
16681        window: &mut Window,
16682        cx: &mut Context<Self>,
16683    ) {
16684        self.insert_uuid(UuidVersion::V7, window, cx);
16685    }
16686
16687    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16688        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16689        self.transact(window, cx, |this, window, cx| {
16690            let edits = this
16691                .selections
16692                .all::<Point>(cx)
16693                .into_iter()
16694                .map(|selection| {
16695                    let uuid = match version {
16696                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16697                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16698                    };
16699
16700                    (selection.range(), uuid.to_string())
16701                });
16702            this.edit(edits, cx);
16703            this.refresh_inline_completion(true, false, window, cx);
16704        });
16705    }
16706
16707    pub fn open_selections_in_multibuffer(
16708        &mut self,
16709        _: &OpenSelectionsInMultibuffer,
16710        window: &mut Window,
16711        cx: &mut Context<Self>,
16712    ) {
16713        let multibuffer = self.buffer.read(cx);
16714
16715        let Some(buffer) = multibuffer.as_singleton() else {
16716            return;
16717        };
16718
16719        let Some(workspace) = self.workspace() else {
16720            return;
16721        };
16722
16723        let locations = self
16724            .selections
16725            .disjoint_anchors()
16726            .iter()
16727            .map(|range| Location {
16728                buffer: buffer.clone(),
16729                range: range.start.text_anchor..range.end.text_anchor,
16730            })
16731            .collect::<Vec<_>>();
16732
16733        let title = multibuffer.title(cx).to_string();
16734
16735        cx.spawn_in(window, async move |_, cx| {
16736            workspace.update_in(cx, |workspace, window, cx| {
16737                Self::open_locations_in_multibuffer(
16738                    workspace,
16739                    locations,
16740                    format!("Selections for '{title}'"),
16741                    false,
16742                    MultibufferSelectionMode::All,
16743                    window,
16744                    cx,
16745                );
16746            })
16747        })
16748        .detach();
16749    }
16750
16751    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16752    /// last highlight added will be used.
16753    ///
16754    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16755    pub fn highlight_rows<T: 'static>(
16756        &mut self,
16757        range: Range<Anchor>,
16758        color: Hsla,
16759        should_autoscroll: bool,
16760        cx: &mut Context<Self>,
16761    ) {
16762        let snapshot = self.buffer().read(cx).snapshot(cx);
16763        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16764        let ix = row_highlights.binary_search_by(|highlight| {
16765            Ordering::Equal
16766                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16767                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16768        });
16769
16770        if let Err(mut ix) = ix {
16771            let index = post_inc(&mut self.highlight_order);
16772
16773            // If this range intersects with the preceding highlight, then merge it with
16774            // the preceding highlight. Otherwise insert a new highlight.
16775            let mut merged = false;
16776            if ix > 0 {
16777                let prev_highlight = &mut row_highlights[ix - 1];
16778                if prev_highlight
16779                    .range
16780                    .end
16781                    .cmp(&range.start, &snapshot)
16782                    .is_ge()
16783                {
16784                    ix -= 1;
16785                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16786                        prev_highlight.range.end = range.end;
16787                    }
16788                    merged = true;
16789                    prev_highlight.index = index;
16790                    prev_highlight.color = color;
16791                    prev_highlight.should_autoscroll = should_autoscroll;
16792                }
16793            }
16794
16795            if !merged {
16796                row_highlights.insert(
16797                    ix,
16798                    RowHighlight {
16799                        range: range.clone(),
16800                        index,
16801                        color,
16802                        should_autoscroll,
16803                    },
16804                );
16805            }
16806
16807            // If any of the following highlights intersect with this one, merge them.
16808            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16809                let highlight = &row_highlights[ix];
16810                if next_highlight
16811                    .range
16812                    .start
16813                    .cmp(&highlight.range.end, &snapshot)
16814                    .is_le()
16815                {
16816                    if next_highlight
16817                        .range
16818                        .end
16819                        .cmp(&highlight.range.end, &snapshot)
16820                        .is_gt()
16821                    {
16822                        row_highlights[ix].range.end = next_highlight.range.end;
16823                    }
16824                    row_highlights.remove(ix + 1);
16825                } else {
16826                    break;
16827                }
16828            }
16829        }
16830    }
16831
16832    /// Remove any highlighted row ranges of the given type that intersect the
16833    /// given ranges.
16834    pub fn remove_highlighted_rows<T: 'static>(
16835        &mut self,
16836        ranges_to_remove: Vec<Range<Anchor>>,
16837        cx: &mut Context<Self>,
16838    ) {
16839        let snapshot = self.buffer().read(cx).snapshot(cx);
16840        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16841        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16842        row_highlights.retain(|highlight| {
16843            while let Some(range_to_remove) = ranges_to_remove.peek() {
16844                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16845                    Ordering::Less | Ordering::Equal => {
16846                        ranges_to_remove.next();
16847                    }
16848                    Ordering::Greater => {
16849                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16850                            Ordering::Less | Ordering::Equal => {
16851                                return false;
16852                            }
16853                            Ordering::Greater => break,
16854                        }
16855                    }
16856                }
16857            }
16858
16859            true
16860        })
16861    }
16862
16863    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16864    pub fn clear_row_highlights<T: 'static>(&mut self) {
16865        self.highlighted_rows.remove(&TypeId::of::<T>());
16866    }
16867
16868    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16869    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16870        self.highlighted_rows
16871            .get(&TypeId::of::<T>())
16872            .map_or(&[] as &[_], |vec| vec.as_slice())
16873            .iter()
16874            .map(|highlight| (highlight.range.clone(), highlight.color))
16875    }
16876
16877    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16878    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16879    /// Allows to ignore certain kinds of highlights.
16880    pub fn highlighted_display_rows(
16881        &self,
16882        window: &mut Window,
16883        cx: &mut App,
16884    ) -> BTreeMap<DisplayRow, LineHighlight> {
16885        let snapshot = self.snapshot(window, cx);
16886        let mut used_highlight_orders = HashMap::default();
16887        self.highlighted_rows
16888            .iter()
16889            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16890            .fold(
16891                BTreeMap::<DisplayRow, LineHighlight>::new(),
16892                |mut unique_rows, highlight| {
16893                    let start = highlight.range.start.to_display_point(&snapshot);
16894                    let end = highlight.range.end.to_display_point(&snapshot);
16895                    let start_row = start.row().0;
16896                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16897                        && end.column() == 0
16898                    {
16899                        end.row().0.saturating_sub(1)
16900                    } else {
16901                        end.row().0
16902                    };
16903                    for row in start_row..=end_row {
16904                        let used_index =
16905                            used_highlight_orders.entry(row).or_insert(highlight.index);
16906                        if highlight.index >= *used_index {
16907                            *used_index = highlight.index;
16908                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16909                        }
16910                    }
16911                    unique_rows
16912                },
16913            )
16914    }
16915
16916    pub fn highlighted_display_row_for_autoscroll(
16917        &self,
16918        snapshot: &DisplaySnapshot,
16919    ) -> Option<DisplayRow> {
16920        self.highlighted_rows
16921            .values()
16922            .flat_map(|highlighted_rows| highlighted_rows.iter())
16923            .filter_map(|highlight| {
16924                if highlight.should_autoscroll {
16925                    Some(highlight.range.start.to_display_point(snapshot).row())
16926                } else {
16927                    None
16928                }
16929            })
16930            .min()
16931    }
16932
16933    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16934        self.highlight_background::<SearchWithinRange>(
16935            ranges,
16936            |colors| colors.editor_document_highlight_read_background,
16937            cx,
16938        )
16939    }
16940
16941    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16942        self.breadcrumb_header = Some(new_header);
16943    }
16944
16945    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16946        self.clear_background_highlights::<SearchWithinRange>(cx);
16947    }
16948
16949    pub fn highlight_background<T: 'static>(
16950        &mut self,
16951        ranges: &[Range<Anchor>],
16952        color_fetcher: fn(&ThemeColors) -> Hsla,
16953        cx: &mut Context<Self>,
16954    ) {
16955        self.background_highlights
16956            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16957        self.scrollbar_marker_state.dirty = true;
16958        cx.notify();
16959    }
16960
16961    pub fn clear_background_highlights<T: 'static>(
16962        &mut self,
16963        cx: &mut Context<Self>,
16964    ) -> Option<BackgroundHighlight> {
16965        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16966        if !text_highlights.1.is_empty() {
16967            self.scrollbar_marker_state.dirty = true;
16968            cx.notify();
16969        }
16970        Some(text_highlights)
16971    }
16972
16973    pub fn highlight_gutter<T: 'static>(
16974        &mut self,
16975        ranges: &[Range<Anchor>],
16976        color_fetcher: fn(&App) -> Hsla,
16977        cx: &mut Context<Self>,
16978    ) {
16979        self.gutter_highlights
16980            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16981        cx.notify();
16982    }
16983
16984    pub fn clear_gutter_highlights<T: 'static>(
16985        &mut self,
16986        cx: &mut Context<Self>,
16987    ) -> Option<GutterHighlight> {
16988        cx.notify();
16989        self.gutter_highlights.remove(&TypeId::of::<T>())
16990    }
16991
16992    #[cfg(feature = "test-support")]
16993    pub fn all_text_background_highlights(
16994        &self,
16995        window: &mut Window,
16996        cx: &mut Context<Self>,
16997    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16998        let snapshot = self.snapshot(window, cx);
16999        let buffer = &snapshot.buffer_snapshot;
17000        let start = buffer.anchor_before(0);
17001        let end = buffer.anchor_after(buffer.len());
17002        let theme = cx.theme().colors();
17003        self.background_highlights_in_range(start..end, &snapshot, theme)
17004    }
17005
17006    #[cfg(feature = "test-support")]
17007    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17008        let snapshot = self.buffer().read(cx).snapshot(cx);
17009
17010        let highlights = self
17011            .background_highlights
17012            .get(&TypeId::of::<items::BufferSearchHighlights>());
17013
17014        if let Some((_color, ranges)) = highlights {
17015            ranges
17016                .iter()
17017                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17018                .collect_vec()
17019        } else {
17020            vec![]
17021        }
17022    }
17023
17024    fn document_highlights_for_position<'a>(
17025        &'a self,
17026        position: Anchor,
17027        buffer: &'a MultiBufferSnapshot,
17028    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17029        let read_highlights = self
17030            .background_highlights
17031            .get(&TypeId::of::<DocumentHighlightRead>())
17032            .map(|h| &h.1);
17033        let write_highlights = self
17034            .background_highlights
17035            .get(&TypeId::of::<DocumentHighlightWrite>())
17036            .map(|h| &h.1);
17037        let left_position = position.bias_left(buffer);
17038        let right_position = position.bias_right(buffer);
17039        read_highlights
17040            .into_iter()
17041            .chain(write_highlights)
17042            .flat_map(move |ranges| {
17043                let start_ix = match ranges.binary_search_by(|probe| {
17044                    let cmp = probe.end.cmp(&left_position, buffer);
17045                    if cmp.is_ge() {
17046                        Ordering::Greater
17047                    } else {
17048                        Ordering::Less
17049                    }
17050                }) {
17051                    Ok(i) | Err(i) => i,
17052                };
17053
17054                ranges[start_ix..]
17055                    .iter()
17056                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17057            })
17058    }
17059
17060    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17061        self.background_highlights
17062            .get(&TypeId::of::<T>())
17063            .map_or(false, |(_, highlights)| !highlights.is_empty())
17064    }
17065
17066    pub fn background_highlights_in_range(
17067        &self,
17068        search_range: Range<Anchor>,
17069        display_snapshot: &DisplaySnapshot,
17070        theme: &ThemeColors,
17071    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17072        let mut results = Vec::new();
17073        for (color_fetcher, ranges) in self.background_highlights.values() {
17074            let color = color_fetcher(theme);
17075            let start_ix = match ranges.binary_search_by(|probe| {
17076                let cmp = probe
17077                    .end
17078                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17079                if cmp.is_gt() {
17080                    Ordering::Greater
17081                } else {
17082                    Ordering::Less
17083                }
17084            }) {
17085                Ok(i) | Err(i) => i,
17086            };
17087            for range in &ranges[start_ix..] {
17088                if range
17089                    .start
17090                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17091                    .is_ge()
17092                {
17093                    break;
17094                }
17095
17096                let start = range.start.to_display_point(display_snapshot);
17097                let end = range.end.to_display_point(display_snapshot);
17098                results.push((start..end, color))
17099            }
17100        }
17101        results
17102    }
17103
17104    pub fn background_highlight_row_ranges<T: 'static>(
17105        &self,
17106        search_range: Range<Anchor>,
17107        display_snapshot: &DisplaySnapshot,
17108        count: usize,
17109    ) -> Vec<RangeInclusive<DisplayPoint>> {
17110        let mut results = Vec::new();
17111        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17112            return vec![];
17113        };
17114
17115        let start_ix = match ranges.binary_search_by(|probe| {
17116            let cmp = probe
17117                .end
17118                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17119            if cmp.is_gt() {
17120                Ordering::Greater
17121            } else {
17122                Ordering::Less
17123            }
17124        }) {
17125            Ok(i) | Err(i) => i,
17126        };
17127        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17128            if let (Some(start_display), Some(end_display)) = (start, end) {
17129                results.push(
17130                    start_display.to_display_point(display_snapshot)
17131                        ..=end_display.to_display_point(display_snapshot),
17132                );
17133            }
17134        };
17135        let mut start_row: Option<Point> = None;
17136        let mut end_row: Option<Point> = None;
17137        if ranges.len() > count {
17138            return Vec::new();
17139        }
17140        for range in &ranges[start_ix..] {
17141            if range
17142                .start
17143                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17144                .is_ge()
17145            {
17146                break;
17147            }
17148            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17149            if let Some(current_row) = &end_row {
17150                if end.row == current_row.row {
17151                    continue;
17152                }
17153            }
17154            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17155            if start_row.is_none() {
17156                assert_eq!(end_row, None);
17157                start_row = Some(start);
17158                end_row = Some(end);
17159                continue;
17160            }
17161            if let Some(current_end) = end_row.as_mut() {
17162                if start.row > current_end.row + 1 {
17163                    push_region(start_row, end_row);
17164                    start_row = Some(start);
17165                    end_row = Some(end);
17166                } else {
17167                    // Merge two hunks.
17168                    *current_end = end;
17169                }
17170            } else {
17171                unreachable!();
17172            }
17173        }
17174        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17175        push_region(start_row, end_row);
17176        results
17177    }
17178
17179    pub fn gutter_highlights_in_range(
17180        &self,
17181        search_range: Range<Anchor>,
17182        display_snapshot: &DisplaySnapshot,
17183        cx: &App,
17184    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17185        let mut results = Vec::new();
17186        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17187            let color = color_fetcher(cx);
17188            let start_ix = match ranges.binary_search_by(|probe| {
17189                let cmp = probe
17190                    .end
17191                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17192                if cmp.is_gt() {
17193                    Ordering::Greater
17194                } else {
17195                    Ordering::Less
17196                }
17197            }) {
17198                Ok(i) | Err(i) => i,
17199            };
17200            for range in &ranges[start_ix..] {
17201                if range
17202                    .start
17203                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17204                    .is_ge()
17205                {
17206                    break;
17207                }
17208
17209                let start = range.start.to_display_point(display_snapshot);
17210                let end = range.end.to_display_point(display_snapshot);
17211                results.push((start..end, color))
17212            }
17213        }
17214        results
17215    }
17216
17217    /// Get the text ranges corresponding to the redaction query
17218    pub fn redacted_ranges(
17219        &self,
17220        search_range: Range<Anchor>,
17221        display_snapshot: &DisplaySnapshot,
17222        cx: &App,
17223    ) -> Vec<Range<DisplayPoint>> {
17224        display_snapshot
17225            .buffer_snapshot
17226            .redacted_ranges(search_range, |file| {
17227                if let Some(file) = file {
17228                    file.is_private()
17229                        && EditorSettings::get(
17230                            Some(SettingsLocation {
17231                                worktree_id: file.worktree_id(cx),
17232                                path: file.path().as_ref(),
17233                            }),
17234                            cx,
17235                        )
17236                        .redact_private_values
17237                } else {
17238                    false
17239                }
17240            })
17241            .map(|range| {
17242                range.start.to_display_point(display_snapshot)
17243                    ..range.end.to_display_point(display_snapshot)
17244            })
17245            .collect()
17246    }
17247
17248    pub fn highlight_text<T: 'static>(
17249        &mut self,
17250        ranges: Vec<Range<Anchor>>,
17251        style: HighlightStyle,
17252        cx: &mut Context<Self>,
17253    ) {
17254        self.display_map.update(cx, |map, _| {
17255            map.highlight_text(TypeId::of::<T>(), ranges, style)
17256        });
17257        cx.notify();
17258    }
17259
17260    pub(crate) fn highlight_inlays<T: 'static>(
17261        &mut self,
17262        highlights: Vec<InlayHighlight>,
17263        style: HighlightStyle,
17264        cx: &mut Context<Self>,
17265    ) {
17266        self.display_map.update(cx, |map, _| {
17267            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17268        });
17269        cx.notify();
17270    }
17271
17272    pub fn text_highlights<'a, T: 'static>(
17273        &'a self,
17274        cx: &'a App,
17275    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17276        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17277    }
17278
17279    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17280        let cleared = self
17281            .display_map
17282            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17283        if cleared {
17284            cx.notify();
17285        }
17286    }
17287
17288    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17289        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17290            && self.focus_handle.is_focused(window)
17291    }
17292
17293    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17294        self.show_cursor_when_unfocused = is_enabled;
17295        cx.notify();
17296    }
17297
17298    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17299        cx.notify();
17300    }
17301
17302    fn on_buffer_event(
17303        &mut self,
17304        multibuffer: &Entity<MultiBuffer>,
17305        event: &multi_buffer::Event,
17306        window: &mut Window,
17307        cx: &mut Context<Self>,
17308    ) {
17309        match event {
17310            multi_buffer::Event::Edited {
17311                singleton_buffer_edited,
17312                edited_buffer: buffer_edited,
17313            } => {
17314                self.scrollbar_marker_state.dirty = true;
17315                self.active_indent_guides_state.dirty = true;
17316                self.refresh_active_diagnostics(cx);
17317                self.refresh_code_actions(window, cx);
17318                if self.has_active_inline_completion() {
17319                    self.update_visible_inline_completion(window, cx);
17320                }
17321                if let Some(buffer) = buffer_edited {
17322                    let buffer_id = buffer.read(cx).remote_id();
17323                    if !self.registered_buffers.contains_key(&buffer_id) {
17324                        if let Some(project) = self.project.as_ref() {
17325                            project.update(cx, |project, cx| {
17326                                self.registered_buffers.insert(
17327                                    buffer_id,
17328                                    project.register_buffer_with_language_servers(&buffer, cx),
17329                                );
17330                            })
17331                        }
17332                    }
17333                }
17334                cx.emit(EditorEvent::BufferEdited);
17335                cx.emit(SearchEvent::MatchesInvalidated);
17336                if *singleton_buffer_edited {
17337                    if let Some(project) = &self.project {
17338                        #[allow(clippy::mutable_key_type)]
17339                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17340                            multibuffer
17341                                .all_buffers()
17342                                .into_iter()
17343                                .filter_map(|buffer| {
17344                                    buffer.update(cx, |buffer, cx| {
17345                                        let language = buffer.language()?;
17346                                        let should_discard = project.update(cx, |project, cx| {
17347                                            project.is_local()
17348                                                && !project.has_language_servers_for(buffer, cx)
17349                                        });
17350                                        should_discard.not().then_some(language.clone())
17351                                    })
17352                                })
17353                                .collect::<HashSet<_>>()
17354                        });
17355                        if !languages_affected.is_empty() {
17356                            self.refresh_inlay_hints(
17357                                InlayHintRefreshReason::BufferEdited(languages_affected),
17358                                cx,
17359                            );
17360                        }
17361                    }
17362                }
17363
17364                let Some(project) = &self.project else { return };
17365                let (telemetry, is_via_ssh) = {
17366                    let project = project.read(cx);
17367                    let telemetry = project.client().telemetry().clone();
17368                    let is_via_ssh = project.is_via_ssh();
17369                    (telemetry, is_via_ssh)
17370                };
17371                refresh_linked_ranges(self, window, cx);
17372                telemetry.log_edit_event("editor", is_via_ssh);
17373            }
17374            multi_buffer::Event::ExcerptsAdded {
17375                buffer,
17376                predecessor,
17377                excerpts,
17378            } => {
17379                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17380                let buffer_id = buffer.read(cx).remote_id();
17381                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17382                    if let Some(project) = &self.project {
17383                        get_uncommitted_diff_for_buffer(
17384                            project,
17385                            [buffer.clone()],
17386                            self.buffer.clone(),
17387                            cx,
17388                        )
17389                        .detach();
17390                    }
17391                }
17392                cx.emit(EditorEvent::ExcerptsAdded {
17393                    buffer: buffer.clone(),
17394                    predecessor: *predecessor,
17395                    excerpts: excerpts.clone(),
17396                });
17397                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17398            }
17399            multi_buffer::Event::ExcerptsRemoved { ids } => {
17400                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17401                let buffer = self.buffer.read(cx);
17402                self.registered_buffers
17403                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17404                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17405                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17406            }
17407            multi_buffer::Event::ExcerptsEdited {
17408                excerpt_ids,
17409                buffer_ids,
17410            } => {
17411                self.display_map.update(cx, |map, cx| {
17412                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17413                });
17414                cx.emit(EditorEvent::ExcerptsEdited {
17415                    ids: excerpt_ids.clone(),
17416                })
17417            }
17418            multi_buffer::Event::ExcerptsExpanded { ids } => {
17419                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17420                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17421            }
17422            multi_buffer::Event::Reparsed(buffer_id) => {
17423                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17424                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17425
17426                cx.emit(EditorEvent::Reparsed(*buffer_id));
17427            }
17428            multi_buffer::Event::DiffHunksToggled => {
17429                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17430            }
17431            multi_buffer::Event::LanguageChanged(buffer_id) => {
17432                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17433                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17434                cx.emit(EditorEvent::Reparsed(*buffer_id));
17435                cx.notify();
17436            }
17437            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17438            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17439            multi_buffer::Event::FileHandleChanged
17440            | multi_buffer::Event::Reloaded
17441            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17442            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17443            multi_buffer::Event::DiagnosticsUpdated => {
17444                self.refresh_active_diagnostics(cx);
17445                self.refresh_inline_diagnostics(true, window, cx);
17446                self.scrollbar_marker_state.dirty = true;
17447                cx.notify();
17448            }
17449            _ => {}
17450        };
17451    }
17452
17453    fn on_display_map_changed(
17454        &mut self,
17455        _: Entity<DisplayMap>,
17456        _: &mut Window,
17457        cx: &mut Context<Self>,
17458    ) {
17459        cx.notify();
17460    }
17461
17462    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17463        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17464        self.update_edit_prediction_settings(cx);
17465        self.refresh_inline_completion(true, false, window, cx);
17466        self.refresh_inlay_hints(
17467            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17468                self.selections.newest_anchor().head(),
17469                &self.buffer.read(cx).snapshot(cx),
17470                cx,
17471            )),
17472            cx,
17473        );
17474
17475        let old_cursor_shape = self.cursor_shape;
17476
17477        {
17478            let editor_settings = EditorSettings::get_global(cx);
17479            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17480            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17481            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17482            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17483        }
17484
17485        if old_cursor_shape != self.cursor_shape {
17486            cx.emit(EditorEvent::CursorShapeChanged);
17487        }
17488
17489        let project_settings = ProjectSettings::get_global(cx);
17490        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17491
17492        if self.mode.is_full() {
17493            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17494            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17495            if self.show_inline_diagnostics != show_inline_diagnostics {
17496                self.show_inline_diagnostics = show_inline_diagnostics;
17497                self.refresh_inline_diagnostics(false, window, cx);
17498            }
17499
17500            if self.git_blame_inline_enabled != inline_blame_enabled {
17501                self.toggle_git_blame_inline_internal(false, window, cx);
17502            }
17503        }
17504
17505        cx.notify();
17506    }
17507
17508    pub fn set_searchable(&mut self, searchable: bool) {
17509        self.searchable = searchable;
17510    }
17511
17512    pub fn searchable(&self) -> bool {
17513        self.searchable
17514    }
17515
17516    fn open_proposed_changes_editor(
17517        &mut self,
17518        _: &OpenProposedChangesEditor,
17519        window: &mut Window,
17520        cx: &mut Context<Self>,
17521    ) {
17522        let Some(workspace) = self.workspace() else {
17523            cx.propagate();
17524            return;
17525        };
17526
17527        let selections = self.selections.all::<usize>(cx);
17528        let multi_buffer = self.buffer.read(cx);
17529        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17530        let mut new_selections_by_buffer = HashMap::default();
17531        for selection in selections {
17532            for (buffer, range, _) in
17533                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17534            {
17535                let mut range = range.to_point(buffer);
17536                range.start.column = 0;
17537                range.end.column = buffer.line_len(range.end.row);
17538                new_selections_by_buffer
17539                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17540                    .or_insert(Vec::new())
17541                    .push(range)
17542            }
17543        }
17544
17545        let proposed_changes_buffers = new_selections_by_buffer
17546            .into_iter()
17547            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17548            .collect::<Vec<_>>();
17549        let proposed_changes_editor = cx.new(|cx| {
17550            ProposedChangesEditor::new(
17551                "Proposed changes",
17552                proposed_changes_buffers,
17553                self.project.clone(),
17554                window,
17555                cx,
17556            )
17557        });
17558
17559        window.defer(cx, move |window, cx| {
17560            workspace.update(cx, |workspace, cx| {
17561                workspace.active_pane().update(cx, |pane, cx| {
17562                    pane.add_item(
17563                        Box::new(proposed_changes_editor),
17564                        true,
17565                        true,
17566                        None,
17567                        window,
17568                        cx,
17569                    );
17570                });
17571            });
17572        });
17573    }
17574
17575    pub fn open_excerpts_in_split(
17576        &mut self,
17577        _: &OpenExcerptsSplit,
17578        window: &mut Window,
17579        cx: &mut Context<Self>,
17580    ) {
17581        self.open_excerpts_common(None, true, window, cx)
17582    }
17583
17584    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17585        self.open_excerpts_common(None, false, window, cx)
17586    }
17587
17588    fn open_excerpts_common(
17589        &mut self,
17590        jump_data: Option<JumpData>,
17591        split: bool,
17592        window: &mut Window,
17593        cx: &mut Context<Self>,
17594    ) {
17595        let Some(workspace) = self.workspace() else {
17596            cx.propagate();
17597            return;
17598        };
17599
17600        if self.buffer.read(cx).is_singleton() {
17601            cx.propagate();
17602            return;
17603        }
17604
17605        let mut new_selections_by_buffer = HashMap::default();
17606        match &jump_data {
17607            Some(JumpData::MultiBufferPoint {
17608                excerpt_id,
17609                position,
17610                anchor,
17611                line_offset_from_top,
17612            }) => {
17613                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17614                if let Some(buffer) = multi_buffer_snapshot
17615                    .buffer_id_for_excerpt(*excerpt_id)
17616                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17617                {
17618                    let buffer_snapshot = buffer.read(cx).snapshot();
17619                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17620                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17621                    } else {
17622                        buffer_snapshot.clip_point(*position, Bias::Left)
17623                    };
17624                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17625                    new_selections_by_buffer.insert(
17626                        buffer,
17627                        (
17628                            vec![jump_to_offset..jump_to_offset],
17629                            Some(*line_offset_from_top),
17630                        ),
17631                    );
17632                }
17633            }
17634            Some(JumpData::MultiBufferRow {
17635                row,
17636                line_offset_from_top,
17637            }) => {
17638                let point = MultiBufferPoint::new(row.0, 0);
17639                if let Some((buffer, buffer_point, _)) =
17640                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17641                {
17642                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17643                    new_selections_by_buffer
17644                        .entry(buffer)
17645                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17646                        .0
17647                        .push(buffer_offset..buffer_offset)
17648                }
17649            }
17650            None => {
17651                let selections = self.selections.all::<usize>(cx);
17652                let multi_buffer = self.buffer.read(cx);
17653                for selection in selections {
17654                    for (snapshot, range, _, anchor) in multi_buffer
17655                        .snapshot(cx)
17656                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17657                    {
17658                        if let Some(anchor) = anchor {
17659                            // selection is in a deleted hunk
17660                            let Some(buffer_id) = anchor.buffer_id else {
17661                                continue;
17662                            };
17663                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17664                                continue;
17665                            };
17666                            let offset = text::ToOffset::to_offset(
17667                                &anchor.text_anchor,
17668                                &buffer_handle.read(cx).snapshot(),
17669                            );
17670                            let range = offset..offset;
17671                            new_selections_by_buffer
17672                                .entry(buffer_handle)
17673                                .or_insert((Vec::new(), None))
17674                                .0
17675                                .push(range)
17676                        } else {
17677                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17678                            else {
17679                                continue;
17680                            };
17681                            new_selections_by_buffer
17682                                .entry(buffer_handle)
17683                                .or_insert((Vec::new(), None))
17684                                .0
17685                                .push(range)
17686                        }
17687                    }
17688                }
17689            }
17690        }
17691
17692        new_selections_by_buffer
17693            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17694
17695        if new_selections_by_buffer.is_empty() {
17696            return;
17697        }
17698
17699        // We defer the pane interaction because we ourselves are a workspace item
17700        // and activating a new item causes the pane to call a method on us reentrantly,
17701        // which panics if we're on the stack.
17702        window.defer(cx, move |window, cx| {
17703            workspace.update(cx, |workspace, cx| {
17704                let pane = if split {
17705                    workspace.adjacent_pane(window, cx)
17706                } else {
17707                    workspace.active_pane().clone()
17708                };
17709
17710                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17711                    let editor = buffer
17712                        .read(cx)
17713                        .file()
17714                        .is_none()
17715                        .then(|| {
17716                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17717                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17718                            // Instead, we try to activate the existing editor in the pane first.
17719                            let (editor, pane_item_index) =
17720                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17721                                    let editor = item.downcast::<Editor>()?;
17722                                    let singleton_buffer =
17723                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17724                                    if singleton_buffer == buffer {
17725                                        Some((editor, i))
17726                                    } else {
17727                                        None
17728                                    }
17729                                })?;
17730                            pane.update(cx, |pane, cx| {
17731                                pane.activate_item(pane_item_index, true, true, window, cx)
17732                            });
17733                            Some(editor)
17734                        })
17735                        .flatten()
17736                        .unwrap_or_else(|| {
17737                            workspace.open_project_item::<Self>(
17738                                pane.clone(),
17739                                buffer,
17740                                true,
17741                                true,
17742                                window,
17743                                cx,
17744                            )
17745                        });
17746
17747                    editor.update(cx, |editor, cx| {
17748                        let autoscroll = match scroll_offset {
17749                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17750                            None => Autoscroll::newest(),
17751                        };
17752                        let nav_history = editor.nav_history.take();
17753                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17754                            s.select_ranges(ranges);
17755                        });
17756                        editor.nav_history = nav_history;
17757                    });
17758                }
17759            })
17760        });
17761    }
17762
17763    // For now, don't allow opening excerpts in buffers that aren't backed by
17764    // regular project files.
17765    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17766        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17767    }
17768
17769    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17770        let snapshot = self.buffer.read(cx).read(cx);
17771        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17772        Some(
17773            ranges
17774                .iter()
17775                .map(move |range| {
17776                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17777                })
17778                .collect(),
17779        )
17780    }
17781
17782    fn selection_replacement_ranges(
17783        &self,
17784        range: Range<OffsetUtf16>,
17785        cx: &mut App,
17786    ) -> Vec<Range<OffsetUtf16>> {
17787        let selections = self.selections.all::<OffsetUtf16>(cx);
17788        let newest_selection = selections
17789            .iter()
17790            .max_by_key(|selection| selection.id)
17791            .unwrap();
17792        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17793        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17794        let snapshot = self.buffer.read(cx).read(cx);
17795        selections
17796            .into_iter()
17797            .map(|mut selection| {
17798                selection.start.0 =
17799                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17800                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17801                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17802                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17803            })
17804            .collect()
17805    }
17806
17807    fn report_editor_event(
17808        &self,
17809        event_type: &'static str,
17810        file_extension: Option<String>,
17811        cx: &App,
17812    ) {
17813        if cfg!(any(test, feature = "test-support")) {
17814            return;
17815        }
17816
17817        let Some(project) = &self.project else { return };
17818
17819        // If None, we are in a file without an extension
17820        let file = self
17821            .buffer
17822            .read(cx)
17823            .as_singleton()
17824            .and_then(|b| b.read(cx).file());
17825        let file_extension = file_extension.or(file
17826            .as_ref()
17827            .and_then(|file| Path::new(file.file_name(cx)).extension())
17828            .and_then(|e| e.to_str())
17829            .map(|a| a.to_string()));
17830
17831        let vim_mode = vim_enabled(cx);
17832
17833        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17834        let copilot_enabled = edit_predictions_provider
17835            == language::language_settings::EditPredictionProvider::Copilot;
17836        let copilot_enabled_for_language = self
17837            .buffer
17838            .read(cx)
17839            .language_settings(cx)
17840            .show_edit_predictions;
17841
17842        let project = project.read(cx);
17843        telemetry::event!(
17844            event_type,
17845            file_extension,
17846            vim_mode,
17847            copilot_enabled,
17848            copilot_enabled_for_language,
17849            edit_predictions_provider,
17850            is_via_ssh = project.is_via_ssh(),
17851        );
17852    }
17853
17854    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17855    /// with each line being an array of {text, highlight} objects.
17856    fn copy_highlight_json(
17857        &mut self,
17858        _: &CopyHighlightJson,
17859        window: &mut Window,
17860        cx: &mut Context<Self>,
17861    ) {
17862        #[derive(Serialize)]
17863        struct Chunk<'a> {
17864            text: String,
17865            highlight: Option<&'a str>,
17866        }
17867
17868        let snapshot = self.buffer.read(cx).snapshot(cx);
17869        let range = self
17870            .selected_text_range(false, window, cx)
17871            .and_then(|selection| {
17872                if selection.range.is_empty() {
17873                    None
17874                } else {
17875                    Some(selection.range)
17876                }
17877            })
17878            .unwrap_or_else(|| 0..snapshot.len());
17879
17880        let chunks = snapshot.chunks(range, true);
17881        let mut lines = Vec::new();
17882        let mut line: VecDeque<Chunk> = VecDeque::new();
17883
17884        let Some(style) = self.style.as_ref() else {
17885            return;
17886        };
17887
17888        for chunk in chunks {
17889            let highlight = chunk
17890                .syntax_highlight_id
17891                .and_then(|id| id.name(&style.syntax));
17892            let mut chunk_lines = chunk.text.split('\n').peekable();
17893            while let Some(text) = chunk_lines.next() {
17894                let mut merged_with_last_token = false;
17895                if let Some(last_token) = line.back_mut() {
17896                    if last_token.highlight == highlight {
17897                        last_token.text.push_str(text);
17898                        merged_with_last_token = true;
17899                    }
17900                }
17901
17902                if !merged_with_last_token {
17903                    line.push_back(Chunk {
17904                        text: text.into(),
17905                        highlight,
17906                    });
17907                }
17908
17909                if chunk_lines.peek().is_some() {
17910                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17911                        line.pop_front();
17912                    }
17913                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17914                        line.pop_back();
17915                    }
17916
17917                    lines.push(mem::take(&mut line));
17918                }
17919            }
17920        }
17921
17922        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17923            return;
17924        };
17925        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17926    }
17927
17928    pub fn open_context_menu(
17929        &mut self,
17930        _: &OpenContextMenu,
17931        window: &mut Window,
17932        cx: &mut Context<Self>,
17933    ) {
17934        self.request_autoscroll(Autoscroll::newest(), cx);
17935        let position = self.selections.newest_display(cx).start;
17936        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17937    }
17938
17939    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17940        &self.inlay_hint_cache
17941    }
17942
17943    pub fn replay_insert_event(
17944        &mut self,
17945        text: &str,
17946        relative_utf16_range: Option<Range<isize>>,
17947        window: &mut Window,
17948        cx: &mut Context<Self>,
17949    ) {
17950        if !self.input_enabled {
17951            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17952            return;
17953        }
17954        if let Some(relative_utf16_range) = relative_utf16_range {
17955            let selections = self.selections.all::<OffsetUtf16>(cx);
17956            self.change_selections(None, window, cx, |s| {
17957                let new_ranges = selections.into_iter().map(|range| {
17958                    let start = OffsetUtf16(
17959                        range
17960                            .head()
17961                            .0
17962                            .saturating_add_signed(relative_utf16_range.start),
17963                    );
17964                    let end = OffsetUtf16(
17965                        range
17966                            .head()
17967                            .0
17968                            .saturating_add_signed(relative_utf16_range.end),
17969                    );
17970                    start..end
17971                });
17972                s.select_ranges(new_ranges);
17973            });
17974        }
17975
17976        self.handle_input(text, window, cx);
17977    }
17978
17979    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17980        let Some(provider) = self.semantics_provider.as_ref() else {
17981            return false;
17982        };
17983
17984        let mut supports = false;
17985        self.buffer().update(cx, |this, cx| {
17986            this.for_each_buffer(|buffer| {
17987                supports |= provider.supports_inlay_hints(buffer, cx);
17988            });
17989        });
17990
17991        supports
17992    }
17993
17994    pub fn is_focused(&self, window: &Window) -> bool {
17995        self.focus_handle.is_focused(window)
17996    }
17997
17998    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17999        cx.emit(EditorEvent::Focused);
18000
18001        if let Some(descendant) = self
18002            .last_focused_descendant
18003            .take()
18004            .and_then(|descendant| descendant.upgrade())
18005        {
18006            window.focus(&descendant);
18007        } else {
18008            if let Some(blame) = self.blame.as_ref() {
18009                blame.update(cx, GitBlame::focus)
18010            }
18011
18012            self.blink_manager.update(cx, BlinkManager::enable);
18013            self.show_cursor_names(window, cx);
18014            self.buffer.update(cx, |buffer, cx| {
18015                buffer.finalize_last_transaction(cx);
18016                if self.leader_peer_id.is_none() {
18017                    buffer.set_active_selections(
18018                        &self.selections.disjoint_anchors(),
18019                        self.selections.line_mode,
18020                        self.cursor_shape,
18021                        cx,
18022                    );
18023                }
18024            });
18025        }
18026    }
18027
18028    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18029        cx.emit(EditorEvent::FocusedIn)
18030    }
18031
18032    fn handle_focus_out(
18033        &mut self,
18034        event: FocusOutEvent,
18035        _window: &mut Window,
18036        cx: &mut Context<Self>,
18037    ) {
18038        if event.blurred != self.focus_handle {
18039            self.last_focused_descendant = Some(event.blurred);
18040        }
18041        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18042    }
18043
18044    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18045        self.blink_manager.update(cx, BlinkManager::disable);
18046        self.buffer
18047            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18048
18049        if let Some(blame) = self.blame.as_ref() {
18050            blame.update(cx, GitBlame::blur)
18051        }
18052        if !self.hover_state.focused(window, cx) {
18053            hide_hover(self, cx);
18054        }
18055        if !self
18056            .context_menu
18057            .borrow()
18058            .as_ref()
18059            .is_some_and(|context_menu| context_menu.focused(window, cx))
18060        {
18061            self.hide_context_menu(window, cx);
18062        }
18063        self.discard_inline_completion(false, cx);
18064        cx.emit(EditorEvent::Blurred);
18065        cx.notify();
18066    }
18067
18068    pub fn register_action<A: Action>(
18069        &mut self,
18070        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18071    ) -> Subscription {
18072        let id = self.next_editor_action_id.post_inc();
18073        let listener = Arc::new(listener);
18074        self.editor_actions.borrow_mut().insert(
18075            id,
18076            Box::new(move |window, _| {
18077                let listener = listener.clone();
18078                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18079                    let action = action.downcast_ref().unwrap();
18080                    if phase == DispatchPhase::Bubble {
18081                        listener(action, window, cx)
18082                    }
18083                })
18084            }),
18085        );
18086
18087        let editor_actions = self.editor_actions.clone();
18088        Subscription::new(move || {
18089            editor_actions.borrow_mut().remove(&id);
18090        })
18091    }
18092
18093    pub fn file_header_size(&self) -> u32 {
18094        FILE_HEADER_HEIGHT
18095    }
18096
18097    pub fn restore(
18098        &mut self,
18099        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18100        window: &mut Window,
18101        cx: &mut Context<Self>,
18102    ) {
18103        let workspace = self.workspace();
18104        let project = self.project.as_ref();
18105        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18106            let mut tasks = Vec::new();
18107            for (buffer_id, changes) in revert_changes {
18108                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18109                    buffer.update(cx, |buffer, cx| {
18110                        buffer.edit(
18111                            changes
18112                                .into_iter()
18113                                .map(|(range, text)| (range, text.to_string())),
18114                            None,
18115                            cx,
18116                        );
18117                    });
18118
18119                    if let Some(project) =
18120                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18121                    {
18122                        project.update(cx, |project, cx| {
18123                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18124                        })
18125                    }
18126                }
18127            }
18128            tasks
18129        });
18130        cx.spawn_in(window, async move |_, cx| {
18131            for (buffer, task) in save_tasks {
18132                let result = task.await;
18133                if result.is_err() {
18134                    let Some(path) = buffer
18135                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18136                        .ok()
18137                    else {
18138                        continue;
18139                    };
18140                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18141                        let Some(task) = cx
18142                            .update_window_entity(&workspace, |workspace, window, cx| {
18143                                workspace
18144                                    .open_path_preview(path, None, false, false, false, window, cx)
18145                            })
18146                            .ok()
18147                        else {
18148                            continue;
18149                        };
18150                        task.await.log_err();
18151                    }
18152                }
18153            }
18154        })
18155        .detach();
18156        self.change_selections(None, window, cx, |selections| selections.refresh());
18157    }
18158
18159    pub fn to_pixel_point(
18160        &self,
18161        source: multi_buffer::Anchor,
18162        editor_snapshot: &EditorSnapshot,
18163        window: &mut Window,
18164    ) -> Option<gpui::Point<Pixels>> {
18165        let source_point = source.to_display_point(editor_snapshot);
18166        self.display_to_pixel_point(source_point, editor_snapshot, window)
18167    }
18168
18169    pub fn display_to_pixel_point(
18170        &self,
18171        source: DisplayPoint,
18172        editor_snapshot: &EditorSnapshot,
18173        window: &mut Window,
18174    ) -> Option<gpui::Point<Pixels>> {
18175        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18176        let text_layout_details = self.text_layout_details(window);
18177        let scroll_top = text_layout_details
18178            .scroll_anchor
18179            .scroll_position(editor_snapshot)
18180            .y;
18181
18182        if source.row().as_f32() < scroll_top.floor() {
18183            return None;
18184        }
18185        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18186        let source_y = line_height * (source.row().as_f32() - scroll_top);
18187        Some(gpui::Point::new(source_x, source_y))
18188    }
18189
18190    pub fn has_visible_completions_menu(&self) -> bool {
18191        !self.edit_prediction_preview_is_active()
18192            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18193                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18194            })
18195    }
18196
18197    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18198        self.addons
18199            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18200    }
18201
18202    pub fn unregister_addon<T: Addon>(&mut self) {
18203        self.addons.remove(&std::any::TypeId::of::<T>());
18204    }
18205
18206    pub fn addon<T: Addon>(&self) -> Option<&T> {
18207        let type_id = std::any::TypeId::of::<T>();
18208        self.addons
18209            .get(&type_id)
18210            .and_then(|item| item.to_any().downcast_ref::<T>())
18211    }
18212
18213    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18214        let text_layout_details = self.text_layout_details(window);
18215        let style = &text_layout_details.editor_style;
18216        let font_id = window.text_system().resolve_font(&style.text.font());
18217        let font_size = style.text.font_size.to_pixels(window.rem_size());
18218        let line_height = style.text.line_height_in_pixels(window.rem_size());
18219        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18220
18221        gpui::Size::new(em_width, line_height)
18222    }
18223
18224    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18225        self.load_diff_task.clone()
18226    }
18227
18228    fn read_metadata_from_db(
18229        &mut self,
18230        item_id: u64,
18231        workspace_id: WorkspaceId,
18232        window: &mut Window,
18233        cx: &mut Context<Editor>,
18234    ) {
18235        if self.is_singleton(cx)
18236            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18237        {
18238            let buffer_snapshot = OnceCell::new();
18239
18240            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18241                if !folds.is_empty() {
18242                    let snapshot =
18243                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18244                    self.fold_ranges(
18245                        folds
18246                            .into_iter()
18247                            .map(|(start, end)| {
18248                                snapshot.clip_offset(start, Bias::Left)
18249                                    ..snapshot.clip_offset(end, Bias::Right)
18250                            })
18251                            .collect(),
18252                        false,
18253                        window,
18254                        cx,
18255                    );
18256                }
18257            }
18258
18259            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18260                if !selections.is_empty() {
18261                    let snapshot =
18262                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18263                    self.change_selections(None, window, cx, |s| {
18264                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18265                            snapshot.clip_offset(start, Bias::Left)
18266                                ..snapshot.clip_offset(end, Bias::Right)
18267                        }));
18268                    });
18269                }
18270            };
18271        }
18272
18273        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18274    }
18275}
18276
18277fn vim_enabled(cx: &App) -> bool {
18278    cx.global::<SettingsStore>()
18279        .raw_user_settings()
18280        .get("vim_mode")
18281        == Some(&serde_json::Value::Bool(true))
18282}
18283
18284// Consider user intent and default settings
18285fn choose_completion_range(
18286    completion: &Completion,
18287    intent: CompletionIntent,
18288    buffer: &Entity<Buffer>,
18289    cx: &mut Context<Editor>,
18290) -> Range<usize> {
18291    fn should_replace(
18292        completion: &Completion,
18293        insert_range: &Range<text::Anchor>,
18294        intent: CompletionIntent,
18295        completion_mode_setting: LspInsertMode,
18296        buffer: &Buffer,
18297    ) -> bool {
18298        // specific actions take precedence over settings
18299        match intent {
18300            CompletionIntent::CompleteWithInsert => return false,
18301            CompletionIntent::CompleteWithReplace => return true,
18302            CompletionIntent::Complete | CompletionIntent::Compose => {}
18303        }
18304
18305        match completion_mode_setting {
18306            LspInsertMode::Insert => false,
18307            LspInsertMode::Replace => true,
18308            LspInsertMode::ReplaceSubsequence => {
18309                let mut text_to_replace = buffer.chars_for_range(
18310                    buffer.anchor_before(completion.replace_range.start)
18311                        ..buffer.anchor_after(completion.replace_range.end),
18312                );
18313                let mut completion_text = completion.new_text.chars();
18314
18315                // is `text_to_replace` a subsequence of `completion_text`
18316                text_to_replace
18317                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18318            }
18319            LspInsertMode::ReplaceSuffix => {
18320                let range_after_cursor = insert_range.end..completion.replace_range.end;
18321
18322                let text_after_cursor = buffer
18323                    .text_for_range(
18324                        buffer.anchor_before(range_after_cursor.start)
18325                            ..buffer.anchor_after(range_after_cursor.end),
18326                    )
18327                    .collect::<String>();
18328                completion.new_text.ends_with(&text_after_cursor)
18329            }
18330        }
18331    }
18332
18333    let buffer = buffer.read(cx);
18334
18335    if let CompletionSource::Lsp {
18336        insert_range: Some(insert_range),
18337        ..
18338    } = &completion.source
18339    {
18340        let completion_mode_setting =
18341            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18342                .completions
18343                .lsp_insert_mode;
18344
18345        if !should_replace(
18346            completion,
18347            &insert_range,
18348            intent,
18349            completion_mode_setting,
18350            buffer,
18351        ) {
18352            return insert_range.to_offset(buffer);
18353        }
18354    }
18355
18356    completion.replace_range.to_offset(buffer)
18357}
18358
18359fn insert_extra_newline_brackets(
18360    buffer: &MultiBufferSnapshot,
18361    range: Range<usize>,
18362    language: &language::LanguageScope,
18363) -> bool {
18364    let leading_whitespace_len = buffer
18365        .reversed_chars_at(range.start)
18366        .take_while(|c| c.is_whitespace() && *c != '\n')
18367        .map(|c| c.len_utf8())
18368        .sum::<usize>();
18369    let trailing_whitespace_len = buffer
18370        .chars_at(range.end)
18371        .take_while(|c| c.is_whitespace() && *c != '\n')
18372        .map(|c| c.len_utf8())
18373        .sum::<usize>();
18374    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18375
18376    language.brackets().any(|(pair, enabled)| {
18377        let pair_start = pair.start.trim_end();
18378        let pair_end = pair.end.trim_start();
18379
18380        enabled
18381            && pair.newline
18382            && buffer.contains_str_at(range.end, pair_end)
18383            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18384    })
18385}
18386
18387fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18388    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18389        [(buffer, range, _)] => (*buffer, range.clone()),
18390        _ => return false,
18391    };
18392    let pair = {
18393        let mut result: Option<BracketMatch> = None;
18394
18395        for pair in buffer
18396            .all_bracket_ranges(range.clone())
18397            .filter(move |pair| {
18398                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18399            })
18400        {
18401            let len = pair.close_range.end - pair.open_range.start;
18402
18403            if let Some(existing) = &result {
18404                let existing_len = existing.close_range.end - existing.open_range.start;
18405                if len > existing_len {
18406                    continue;
18407                }
18408            }
18409
18410            result = Some(pair);
18411        }
18412
18413        result
18414    };
18415    let Some(pair) = pair else {
18416        return false;
18417    };
18418    pair.newline_only
18419        && buffer
18420            .chars_for_range(pair.open_range.end..range.start)
18421            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18422            .all(|c| c.is_whitespace() && c != '\n')
18423}
18424
18425fn get_uncommitted_diff_for_buffer(
18426    project: &Entity<Project>,
18427    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18428    buffer: Entity<MultiBuffer>,
18429    cx: &mut App,
18430) -> Task<()> {
18431    let mut tasks = Vec::new();
18432    project.update(cx, |project, cx| {
18433        for buffer in buffers {
18434            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18435                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18436            }
18437        }
18438    });
18439    cx.spawn(async move |cx| {
18440        let diffs = future::join_all(tasks).await;
18441        buffer
18442            .update(cx, |buffer, cx| {
18443                for diff in diffs.into_iter().flatten() {
18444                    buffer.add_diff(diff, cx);
18445                }
18446            })
18447            .ok();
18448    })
18449}
18450
18451fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18452    let tab_size = tab_size.get() as usize;
18453    let mut width = offset;
18454
18455    for ch in text.chars() {
18456        width += if ch == '\t' {
18457            tab_size - (width % tab_size)
18458        } else {
18459            1
18460        };
18461    }
18462
18463    width - offset
18464}
18465
18466#[cfg(test)]
18467mod tests {
18468    use super::*;
18469
18470    #[test]
18471    fn test_string_size_with_expanded_tabs() {
18472        let nz = |val| NonZeroU32::new(val).unwrap();
18473        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18474        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18475        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18476        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18477        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18478        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18479        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18480        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18481    }
18482}
18483
18484/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18485struct WordBreakingTokenizer<'a> {
18486    input: &'a str,
18487}
18488
18489impl<'a> WordBreakingTokenizer<'a> {
18490    fn new(input: &'a str) -> Self {
18491        Self { input }
18492    }
18493}
18494
18495fn is_char_ideographic(ch: char) -> bool {
18496    use unicode_script::Script::*;
18497    use unicode_script::UnicodeScript;
18498    matches!(ch.script(), Han | Tangut | Yi)
18499}
18500
18501fn is_grapheme_ideographic(text: &str) -> bool {
18502    text.chars().any(is_char_ideographic)
18503}
18504
18505fn is_grapheme_whitespace(text: &str) -> bool {
18506    text.chars().any(|x| x.is_whitespace())
18507}
18508
18509fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18510    text.chars().next().map_or(false, |ch| {
18511        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18512    })
18513}
18514
18515#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18516enum WordBreakToken<'a> {
18517    Word { token: &'a str, grapheme_len: usize },
18518    InlineWhitespace { token: &'a str, grapheme_len: usize },
18519    Newline,
18520}
18521
18522impl<'a> Iterator for WordBreakingTokenizer<'a> {
18523    /// Yields a span, the count of graphemes in the token, and whether it was
18524    /// whitespace. Note that it also breaks at word boundaries.
18525    type Item = WordBreakToken<'a>;
18526
18527    fn next(&mut self) -> Option<Self::Item> {
18528        use unicode_segmentation::UnicodeSegmentation;
18529        if self.input.is_empty() {
18530            return None;
18531        }
18532
18533        let mut iter = self.input.graphemes(true).peekable();
18534        let mut offset = 0;
18535        let mut grapheme_len = 0;
18536        if let Some(first_grapheme) = iter.next() {
18537            let is_newline = first_grapheme == "\n";
18538            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18539            offset += first_grapheme.len();
18540            grapheme_len += 1;
18541            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18542                if let Some(grapheme) = iter.peek().copied() {
18543                    if should_stay_with_preceding_ideograph(grapheme) {
18544                        offset += grapheme.len();
18545                        grapheme_len += 1;
18546                    }
18547                }
18548            } else {
18549                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18550                let mut next_word_bound = words.peek().copied();
18551                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18552                    next_word_bound = words.next();
18553                }
18554                while let Some(grapheme) = iter.peek().copied() {
18555                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18556                        break;
18557                    };
18558                    if is_grapheme_whitespace(grapheme) != is_whitespace
18559                        || (grapheme == "\n") != is_newline
18560                    {
18561                        break;
18562                    };
18563                    offset += grapheme.len();
18564                    grapheme_len += 1;
18565                    iter.next();
18566                }
18567            }
18568            let token = &self.input[..offset];
18569            self.input = &self.input[offset..];
18570            if token == "\n" {
18571                Some(WordBreakToken::Newline)
18572            } else if is_whitespace {
18573                Some(WordBreakToken::InlineWhitespace {
18574                    token,
18575                    grapheme_len,
18576                })
18577            } else {
18578                Some(WordBreakToken::Word {
18579                    token,
18580                    grapheme_len,
18581                })
18582            }
18583        } else {
18584            None
18585        }
18586    }
18587}
18588
18589#[test]
18590fn test_word_breaking_tokenizer() {
18591    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18592        ("", &[]),
18593        ("  ", &[whitespace("  ", 2)]),
18594        ("Ʒ", &[word("Ʒ", 1)]),
18595        ("Ǽ", &[word("Ǽ", 1)]),
18596        ("", &[word("", 1)]),
18597        ("⋑⋑", &[word("⋑⋑", 2)]),
18598        (
18599            "原理,进而",
18600            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18601        ),
18602        (
18603            "hello world",
18604            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18605        ),
18606        (
18607            "hello, world",
18608            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18609        ),
18610        (
18611            "  hello world",
18612            &[
18613                whitespace("  ", 2),
18614                word("hello", 5),
18615                whitespace(" ", 1),
18616                word("world", 5),
18617            ],
18618        ),
18619        (
18620            "这是什么 \n 钢笔",
18621            &[
18622                word("", 1),
18623                word("", 1),
18624                word("", 1),
18625                word("", 1),
18626                whitespace(" ", 1),
18627                newline(),
18628                whitespace(" ", 1),
18629                word("", 1),
18630                word("", 1),
18631            ],
18632        ),
18633        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18634    ];
18635
18636    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18637        WordBreakToken::Word {
18638            token,
18639            grapheme_len,
18640        }
18641    }
18642
18643    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18644        WordBreakToken::InlineWhitespace {
18645            token,
18646            grapheme_len,
18647        }
18648    }
18649
18650    fn newline() -> WordBreakToken<'static> {
18651        WordBreakToken::Newline
18652    }
18653
18654    for (input, result) in tests {
18655        assert_eq!(
18656            WordBreakingTokenizer::new(input)
18657                .collect::<Vec<_>>()
18658                .as_slice(),
18659            *result,
18660        );
18661    }
18662}
18663
18664fn wrap_with_prefix(
18665    line_prefix: String,
18666    unwrapped_text: String,
18667    wrap_column: usize,
18668    tab_size: NonZeroU32,
18669    preserve_existing_whitespace: bool,
18670) -> String {
18671    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18672    let mut wrapped_text = String::new();
18673    let mut current_line = line_prefix.clone();
18674
18675    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18676    let mut current_line_len = line_prefix_len;
18677    let mut in_whitespace = false;
18678    for token in tokenizer {
18679        let have_preceding_whitespace = in_whitespace;
18680        match token {
18681            WordBreakToken::Word {
18682                token,
18683                grapheme_len,
18684            } => {
18685                in_whitespace = false;
18686                if current_line_len + grapheme_len > wrap_column
18687                    && current_line_len != line_prefix_len
18688                {
18689                    wrapped_text.push_str(current_line.trim_end());
18690                    wrapped_text.push('\n');
18691                    current_line.truncate(line_prefix.len());
18692                    current_line_len = line_prefix_len;
18693                }
18694                current_line.push_str(token);
18695                current_line_len += grapheme_len;
18696            }
18697            WordBreakToken::InlineWhitespace {
18698                mut token,
18699                mut grapheme_len,
18700            } => {
18701                in_whitespace = true;
18702                if have_preceding_whitespace && !preserve_existing_whitespace {
18703                    continue;
18704                }
18705                if !preserve_existing_whitespace {
18706                    token = " ";
18707                    grapheme_len = 1;
18708                }
18709                if current_line_len + grapheme_len > wrap_column {
18710                    wrapped_text.push_str(current_line.trim_end());
18711                    wrapped_text.push('\n');
18712                    current_line.truncate(line_prefix.len());
18713                    current_line_len = line_prefix_len;
18714                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18715                    current_line.push_str(token);
18716                    current_line_len += grapheme_len;
18717                }
18718            }
18719            WordBreakToken::Newline => {
18720                in_whitespace = true;
18721                if preserve_existing_whitespace {
18722                    wrapped_text.push_str(current_line.trim_end());
18723                    wrapped_text.push('\n');
18724                    current_line.truncate(line_prefix.len());
18725                    current_line_len = line_prefix_len;
18726                } else if have_preceding_whitespace {
18727                    continue;
18728                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18729                {
18730                    wrapped_text.push_str(current_line.trim_end());
18731                    wrapped_text.push('\n');
18732                    current_line.truncate(line_prefix.len());
18733                    current_line_len = line_prefix_len;
18734                } else if current_line_len != line_prefix_len {
18735                    current_line.push(' ');
18736                    current_line_len += 1;
18737                }
18738            }
18739        }
18740    }
18741
18742    if !current_line.is_empty() {
18743        wrapped_text.push_str(&current_line);
18744    }
18745    wrapped_text
18746}
18747
18748#[test]
18749fn test_wrap_with_prefix() {
18750    assert_eq!(
18751        wrap_with_prefix(
18752            "# ".to_string(),
18753            "abcdefg".to_string(),
18754            4,
18755            NonZeroU32::new(4).unwrap(),
18756            false,
18757        ),
18758        "# abcdefg"
18759    );
18760    assert_eq!(
18761        wrap_with_prefix(
18762            "".to_string(),
18763            "\thello world".to_string(),
18764            8,
18765            NonZeroU32::new(4).unwrap(),
18766            false,
18767        ),
18768        "hello\nworld"
18769    );
18770    assert_eq!(
18771        wrap_with_prefix(
18772            "// ".to_string(),
18773            "xx \nyy zz aa bb cc".to_string(),
18774            12,
18775            NonZeroU32::new(4).unwrap(),
18776            false,
18777        ),
18778        "// xx yy zz\n// aa bb cc"
18779    );
18780    assert_eq!(
18781        wrap_with_prefix(
18782            String::new(),
18783            "这是什么 \n 钢笔".to_string(),
18784            3,
18785            NonZeroU32::new(4).unwrap(),
18786            false,
18787        ),
18788        "这是什\n么 钢\n"
18789    );
18790}
18791
18792pub trait CollaborationHub {
18793    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18794    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18795    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18796}
18797
18798impl CollaborationHub for Entity<Project> {
18799    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18800        self.read(cx).collaborators()
18801    }
18802
18803    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18804        self.read(cx).user_store().read(cx).participant_indices()
18805    }
18806
18807    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18808        let this = self.read(cx);
18809        let user_ids = this.collaborators().values().map(|c| c.user_id);
18810        this.user_store().read_with(cx, |user_store, cx| {
18811            user_store.participant_names(user_ids, cx)
18812        })
18813    }
18814}
18815
18816pub trait SemanticsProvider {
18817    fn hover(
18818        &self,
18819        buffer: &Entity<Buffer>,
18820        position: text::Anchor,
18821        cx: &mut App,
18822    ) -> Option<Task<Vec<project::Hover>>>;
18823
18824    fn inlay_hints(
18825        &self,
18826        buffer_handle: Entity<Buffer>,
18827        range: Range<text::Anchor>,
18828        cx: &mut App,
18829    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18830
18831    fn resolve_inlay_hint(
18832        &self,
18833        hint: InlayHint,
18834        buffer_handle: Entity<Buffer>,
18835        server_id: LanguageServerId,
18836        cx: &mut App,
18837    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18838
18839    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18840
18841    fn document_highlights(
18842        &self,
18843        buffer: &Entity<Buffer>,
18844        position: text::Anchor,
18845        cx: &mut App,
18846    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18847
18848    fn definitions(
18849        &self,
18850        buffer: &Entity<Buffer>,
18851        position: text::Anchor,
18852        kind: GotoDefinitionKind,
18853        cx: &mut App,
18854    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18855
18856    fn range_for_rename(
18857        &self,
18858        buffer: &Entity<Buffer>,
18859        position: text::Anchor,
18860        cx: &mut App,
18861    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18862
18863    fn perform_rename(
18864        &self,
18865        buffer: &Entity<Buffer>,
18866        position: text::Anchor,
18867        new_name: String,
18868        cx: &mut App,
18869    ) -> Option<Task<Result<ProjectTransaction>>>;
18870}
18871
18872pub trait CompletionProvider {
18873    fn completions(
18874        &self,
18875        excerpt_id: ExcerptId,
18876        buffer: &Entity<Buffer>,
18877        buffer_position: text::Anchor,
18878        trigger: CompletionContext,
18879        window: &mut Window,
18880        cx: &mut Context<Editor>,
18881    ) -> Task<Result<Option<Vec<Completion>>>>;
18882
18883    fn resolve_completions(
18884        &self,
18885        buffer: Entity<Buffer>,
18886        completion_indices: Vec<usize>,
18887        completions: Rc<RefCell<Box<[Completion]>>>,
18888        cx: &mut Context<Editor>,
18889    ) -> Task<Result<bool>>;
18890
18891    fn apply_additional_edits_for_completion(
18892        &self,
18893        _buffer: Entity<Buffer>,
18894        _completions: Rc<RefCell<Box<[Completion]>>>,
18895        _completion_index: usize,
18896        _push_to_history: bool,
18897        _cx: &mut Context<Editor>,
18898    ) -> Task<Result<Option<language::Transaction>>> {
18899        Task::ready(Ok(None))
18900    }
18901
18902    fn is_completion_trigger(
18903        &self,
18904        buffer: &Entity<Buffer>,
18905        position: language::Anchor,
18906        text: &str,
18907        trigger_in_words: bool,
18908        cx: &mut Context<Editor>,
18909    ) -> bool;
18910
18911    fn sort_completions(&self) -> bool {
18912        true
18913    }
18914
18915    fn filter_completions(&self) -> bool {
18916        true
18917    }
18918}
18919
18920pub trait CodeActionProvider {
18921    fn id(&self) -> Arc<str>;
18922
18923    fn code_actions(
18924        &self,
18925        buffer: &Entity<Buffer>,
18926        range: Range<text::Anchor>,
18927        window: &mut Window,
18928        cx: &mut App,
18929    ) -> Task<Result<Vec<CodeAction>>>;
18930
18931    fn apply_code_action(
18932        &self,
18933        buffer_handle: Entity<Buffer>,
18934        action: CodeAction,
18935        excerpt_id: ExcerptId,
18936        push_to_history: bool,
18937        window: &mut Window,
18938        cx: &mut App,
18939    ) -> Task<Result<ProjectTransaction>>;
18940}
18941
18942impl CodeActionProvider for Entity<Project> {
18943    fn id(&self) -> Arc<str> {
18944        "project".into()
18945    }
18946
18947    fn code_actions(
18948        &self,
18949        buffer: &Entity<Buffer>,
18950        range: Range<text::Anchor>,
18951        _window: &mut Window,
18952        cx: &mut App,
18953    ) -> Task<Result<Vec<CodeAction>>> {
18954        self.update(cx, |project, cx| {
18955            let code_lens = project.code_lens(buffer, range.clone(), cx);
18956            let code_actions = project.code_actions(buffer, range, None, cx);
18957            cx.background_spawn(async move {
18958                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18959                Ok(code_lens
18960                    .context("code lens fetch")?
18961                    .into_iter()
18962                    .chain(code_actions.context("code action fetch")?)
18963                    .collect())
18964            })
18965        })
18966    }
18967
18968    fn apply_code_action(
18969        &self,
18970        buffer_handle: Entity<Buffer>,
18971        action: CodeAction,
18972        _excerpt_id: ExcerptId,
18973        push_to_history: bool,
18974        _window: &mut Window,
18975        cx: &mut App,
18976    ) -> Task<Result<ProjectTransaction>> {
18977        self.update(cx, |project, cx| {
18978            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18979        })
18980    }
18981}
18982
18983fn snippet_completions(
18984    project: &Project,
18985    buffer: &Entity<Buffer>,
18986    buffer_position: text::Anchor,
18987    cx: &mut App,
18988) -> Task<Result<Vec<Completion>>> {
18989    let languages = buffer.read(cx).languages_at(buffer_position);
18990    let snippet_store = project.snippets().read(cx);
18991
18992    let scopes: Vec<_> = languages
18993        .iter()
18994        .filter_map(|language| {
18995            let language_name = language.lsp_id();
18996            let snippets = snippet_store.snippets_for(Some(language_name), cx);
18997
18998            if snippets.is_empty() {
18999                None
19000            } else {
19001                Some((language.default_scope(), snippets))
19002            }
19003        })
19004        .collect();
19005
19006    if scopes.is_empty() {
19007        return Task::ready(Ok(vec![]));
19008    }
19009
19010    let snapshot = buffer.read(cx).text_snapshot();
19011    let chars: String = snapshot
19012        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19013        .collect();
19014    let executor = cx.background_executor().clone();
19015
19016    cx.background_spawn(async move {
19017        let mut all_results: Vec<Completion> = Vec::new();
19018        for (scope, snippets) in scopes.into_iter() {
19019            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19020            let mut last_word = chars
19021                .chars()
19022                .take_while(|c| classifier.is_word(*c))
19023                .collect::<String>();
19024            last_word = last_word.chars().rev().collect();
19025
19026            if last_word.is_empty() {
19027                return Ok(vec![]);
19028            }
19029
19030            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19031            let to_lsp = |point: &text::Anchor| {
19032                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19033                point_to_lsp(end)
19034            };
19035            let lsp_end = to_lsp(&buffer_position);
19036
19037            let candidates = snippets
19038                .iter()
19039                .enumerate()
19040                .flat_map(|(ix, snippet)| {
19041                    snippet
19042                        .prefix
19043                        .iter()
19044                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19045                })
19046                .collect::<Vec<StringMatchCandidate>>();
19047
19048            let mut matches = fuzzy::match_strings(
19049                &candidates,
19050                &last_word,
19051                last_word.chars().any(|c| c.is_uppercase()),
19052                100,
19053                &Default::default(),
19054                executor.clone(),
19055            )
19056            .await;
19057
19058            // Remove all candidates where the query's start does not match the start of any word in the candidate
19059            if let Some(query_start) = last_word.chars().next() {
19060                matches.retain(|string_match| {
19061                    split_words(&string_match.string).any(|word| {
19062                        // Check that the first codepoint of the word as lowercase matches the first
19063                        // codepoint of the query as lowercase
19064                        word.chars()
19065                            .flat_map(|codepoint| codepoint.to_lowercase())
19066                            .zip(query_start.to_lowercase())
19067                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19068                    })
19069                });
19070            }
19071
19072            let matched_strings = matches
19073                .into_iter()
19074                .map(|m| m.string)
19075                .collect::<HashSet<_>>();
19076
19077            let mut result: Vec<Completion> = snippets
19078                .iter()
19079                .filter_map(|snippet| {
19080                    let matching_prefix = snippet
19081                        .prefix
19082                        .iter()
19083                        .find(|prefix| matched_strings.contains(*prefix))?;
19084                    let start = as_offset - last_word.len();
19085                    let start = snapshot.anchor_before(start);
19086                    let range = start..buffer_position;
19087                    let lsp_start = to_lsp(&start);
19088                    let lsp_range = lsp::Range {
19089                        start: lsp_start,
19090                        end: lsp_end,
19091                    };
19092                    Some(Completion {
19093                        replace_range: range,
19094                        new_text: snippet.body.clone(),
19095                        source: CompletionSource::Lsp {
19096                            insert_range: None,
19097                            server_id: LanguageServerId(usize::MAX),
19098                            resolved: true,
19099                            lsp_completion: Box::new(lsp::CompletionItem {
19100                                label: snippet.prefix.first().unwrap().clone(),
19101                                kind: Some(CompletionItemKind::SNIPPET),
19102                                label_details: snippet.description.as_ref().map(|description| {
19103                                    lsp::CompletionItemLabelDetails {
19104                                        detail: Some(description.clone()),
19105                                        description: None,
19106                                    }
19107                                }),
19108                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19109                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19110                                    lsp::InsertReplaceEdit {
19111                                        new_text: snippet.body.clone(),
19112                                        insert: lsp_range,
19113                                        replace: lsp_range,
19114                                    },
19115                                )),
19116                                filter_text: Some(snippet.body.clone()),
19117                                sort_text: Some(char::MAX.to_string()),
19118                                ..lsp::CompletionItem::default()
19119                            }),
19120                            lsp_defaults: None,
19121                        },
19122                        label: CodeLabel {
19123                            text: matching_prefix.clone(),
19124                            runs: Vec::new(),
19125                            filter_range: 0..matching_prefix.len(),
19126                        },
19127                        icon_path: None,
19128                        documentation: snippet.description.clone().map(|description| {
19129                            CompletionDocumentation::SingleLine(description.into())
19130                        }),
19131                        insert_text_mode: None,
19132                        confirm: None,
19133                    })
19134                })
19135                .collect();
19136
19137            all_results.append(&mut result);
19138        }
19139
19140        Ok(all_results)
19141    })
19142}
19143
19144impl CompletionProvider for Entity<Project> {
19145    fn completions(
19146        &self,
19147        _excerpt_id: ExcerptId,
19148        buffer: &Entity<Buffer>,
19149        buffer_position: text::Anchor,
19150        options: CompletionContext,
19151        _window: &mut Window,
19152        cx: &mut Context<Editor>,
19153    ) -> Task<Result<Option<Vec<Completion>>>> {
19154        self.update(cx, |project, cx| {
19155            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19156            let project_completions = project.completions(buffer, buffer_position, options, cx);
19157            cx.background_spawn(async move {
19158                let snippets_completions = snippets.await?;
19159                match project_completions.await? {
19160                    Some(mut completions) => {
19161                        completions.extend(snippets_completions);
19162                        Ok(Some(completions))
19163                    }
19164                    None => {
19165                        if snippets_completions.is_empty() {
19166                            Ok(None)
19167                        } else {
19168                            Ok(Some(snippets_completions))
19169                        }
19170                    }
19171                }
19172            })
19173        })
19174    }
19175
19176    fn resolve_completions(
19177        &self,
19178        buffer: Entity<Buffer>,
19179        completion_indices: Vec<usize>,
19180        completions: Rc<RefCell<Box<[Completion]>>>,
19181        cx: &mut Context<Editor>,
19182    ) -> Task<Result<bool>> {
19183        self.update(cx, |project, cx| {
19184            project.lsp_store().update(cx, |lsp_store, cx| {
19185                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19186            })
19187        })
19188    }
19189
19190    fn apply_additional_edits_for_completion(
19191        &self,
19192        buffer: Entity<Buffer>,
19193        completions: Rc<RefCell<Box<[Completion]>>>,
19194        completion_index: usize,
19195        push_to_history: bool,
19196        cx: &mut Context<Editor>,
19197    ) -> Task<Result<Option<language::Transaction>>> {
19198        self.update(cx, |project, cx| {
19199            project.lsp_store().update(cx, |lsp_store, cx| {
19200                lsp_store.apply_additional_edits_for_completion(
19201                    buffer,
19202                    completions,
19203                    completion_index,
19204                    push_to_history,
19205                    cx,
19206                )
19207            })
19208        })
19209    }
19210
19211    fn is_completion_trigger(
19212        &self,
19213        buffer: &Entity<Buffer>,
19214        position: language::Anchor,
19215        text: &str,
19216        trigger_in_words: bool,
19217        cx: &mut Context<Editor>,
19218    ) -> bool {
19219        let mut chars = text.chars();
19220        let char = if let Some(char) = chars.next() {
19221            char
19222        } else {
19223            return false;
19224        };
19225        if chars.next().is_some() {
19226            return false;
19227        }
19228
19229        let buffer = buffer.read(cx);
19230        let snapshot = buffer.snapshot();
19231        if !snapshot.settings_at(position, cx).show_completions_on_input {
19232            return false;
19233        }
19234        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19235        if trigger_in_words && classifier.is_word(char) {
19236            return true;
19237        }
19238
19239        buffer.completion_triggers().contains(text)
19240    }
19241}
19242
19243impl SemanticsProvider for Entity<Project> {
19244    fn hover(
19245        &self,
19246        buffer: &Entity<Buffer>,
19247        position: text::Anchor,
19248        cx: &mut App,
19249    ) -> Option<Task<Vec<project::Hover>>> {
19250        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19251    }
19252
19253    fn document_highlights(
19254        &self,
19255        buffer: &Entity<Buffer>,
19256        position: text::Anchor,
19257        cx: &mut App,
19258    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19259        Some(self.update(cx, |project, cx| {
19260            project.document_highlights(buffer, position, cx)
19261        }))
19262    }
19263
19264    fn definitions(
19265        &self,
19266        buffer: &Entity<Buffer>,
19267        position: text::Anchor,
19268        kind: GotoDefinitionKind,
19269        cx: &mut App,
19270    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19271        Some(self.update(cx, |project, cx| match kind {
19272            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19273            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19274            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19275            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19276        }))
19277    }
19278
19279    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19280        // TODO: make this work for remote projects
19281        self.update(cx, |this, cx| {
19282            buffer.update(cx, |buffer, cx| {
19283                this.any_language_server_supports_inlay_hints(buffer, cx)
19284            })
19285        })
19286    }
19287
19288    fn inlay_hints(
19289        &self,
19290        buffer_handle: Entity<Buffer>,
19291        range: Range<text::Anchor>,
19292        cx: &mut App,
19293    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19294        Some(self.update(cx, |project, cx| {
19295            project.inlay_hints(buffer_handle, range, cx)
19296        }))
19297    }
19298
19299    fn resolve_inlay_hint(
19300        &self,
19301        hint: InlayHint,
19302        buffer_handle: Entity<Buffer>,
19303        server_id: LanguageServerId,
19304        cx: &mut App,
19305    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19306        Some(self.update(cx, |project, cx| {
19307            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19308        }))
19309    }
19310
19311    fn range_for_rename(
19312        &self,
19313        buffer: &Entity<Buffer>,
19314        position: text::Anchor,
19315        cx: &mut App,
19316    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19317        Some(self.update(cx, |project, cx| {
19318            let buffer = buffer.clone();
19319            let task = project.prepare_rename(buffer.clone(), position, cx);
19320            cx.spawn(async move |_, cx| {
19321                Ok(match task.await? {
19322                    PrepareRenameResponse::Success(range) => Some(range),
19323                    PrepareRenameResponse::InvalidPosition => None,
19324                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19325                        // Fallback on using TreeSitter info to determine identifier range
19326                        buffer.update(cx, |buffer, _| {
19327                            let snapshot = buffer.snapshot();
19328                            let (range, kind) = snapshot.surrounding_word(position);
19329                            if kind != Some(CharKind::Word) {
19330                                return None;
19331                            }
19332                            Some(
19333                                snapshot.anchor_before(range.start)
19334                                    ..snapshot.anchor_after(range.end),
19335                            )
19336                        })?
19337                    }
19338                })
19339            })
19340        }))
19341    }
19342
19343    fn perform_rename(
19344        &self,
19345        buffer: &Entity<Buffer>,
19346        position: text::Anchor,
19347        new_name: String,
19348        cx: &mut App,
19349    ) -> Option<Task<Result<ProjectTransaction>>> {
19350        Some(self.update(cx, |project, cx| {
19351            project.perform_rename(buffer.clone(), position, new_name, cx)
19352        }))
19353    }
19354}
19355
19356fn inlay_hint_settings(
19357    location: Anchor,
19358    snapshot: &MultiBufferSnapshot,
19359    cx: &mut Context<Editor>,
19360) -> InlayHintSettings {
19361    let file = snapshot.file_at(location);
19362    let language = snapshot.language_at(location).map(|l| l.name());
19363    language_settings(language, file, cx).inlay_hints
19364}
19365
19366fn consume_contiguous_rows(
19367    contiguous_row_selections: &mut Vec<Selection<Point>>,
19368    selection: &Selection<Point>,
19369    display_map: &DisplaySnapshot,
19370    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19371) -> (MultiBufferRow, MultiBufferRow) {
19372    contiguous_row_selections.push(selection.clone());
19373    let start_row = MultiBufferRow(selection.start.row);
19374    let mut end_row = ending_row(selection, display_map);
19375
19376    while let Some(next_selection) = selections.peek() {
19377        if next_selection.start.row <= end_row.0 {
19378            end_row = ending_row(next_selection, display_map);
19379            contiguous_row_selections.push(selections.next().unwrap().clone());
19380        } else {
19381            break;
19382        }
19383    }
19384    (start_row, end_row)
19385}
19386
19387fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19388    if next_selection.end.column > 0 || next_selection.is_empty() {
19389        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19390    } else {
19391        MultiBufferRow(next_selection.end.row)
19392    }
19393}
19394
19395impl EditorSnapshot {
19396    pub fn remote_selections_in_range<'a>(
19397        &'a self,
19398        range: &'a Range<Anchor>,
19399        collaboration_hub: &dyn CollaborationHub,
19400        cx: &'a App,
19401    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19402        let participant_names = collaboration_hub.user_names(cx);
19403        let participant_indices = collaboration_hub.user_participant_indices(cx);
19404        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19405        let collaborators_by_replica_id = collaborators_by_peer_id
19406            .iter()
19407            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19408            .collect::<HashMap<_, _>>();
19409        self.buffer_snapshot
19410            .selections_in_range(range, false)
19411            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19412                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19413                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19414                let user_name = participant_names.get(&collaborator.user_id).cloned();
19415                Some(RemoteSelection {
19416                    replica_id,
19417                    selection,
19418                    cursor_shape,
19419                    line_mode,
19420                    participant_index,
19421                    peer_id: collaborator.peer_id,
19422                    user_name,
19423                })
19424            })
19425    }
19426
19427    pub fn hunks_for_ranges(
19428        &self,
19429        ranges: impl IntoIterator<Item = Range<Point>>,
19430    ) -> Vec<MultiBufferDiffHunk> {
19431        let mut hunks = Vec::new();
19432        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19433            HashMap::default();
19434        for query_range in ranges {
19435            let query_rows =
19436                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19437            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19438                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19439            ) {
19440                // Include deleted hunks that are adjacent to the query range, because
19441                // otherwise they would be missed.
19442                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19443                if hunk.status().is_deleted() {
19444                    intersects_range |= hunk.row_range.start == query_rows.end;
19445                    intersects_range |= hunk.row_range.end == query_rows.start;
19446                }
19447                if intersects_range {
19448                    if !processed_buffer_rows
19449                        .entry(hunk.buffer_id)
19450                        .or_default()
19451                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19452                    {
19453                        continue;
19454                    }
19455                    hunks.push(hunk);
19456                }
19457            }
19458        }
19459
19460        hunks
19461    }
19462
19463    fn display_diff_hunks_for_rows<'a>(
19464        &'a self,
19465        display_rows: Range<DisplayRow>,
19466        folded_buffers: &'a HashSet<BufferId>,
19467    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19468        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19469        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19470
19471        self.buffer_snapshot
19472            .diff_hunks_in_range(buffer_start..buffer_end)
19473            .filter_map(|hunk| {
19474                if folded_buffers.contains(&hunk.buffer_id) {
19475                    return None;
19476                }
19477
19478                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19479                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19480
19481                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19482                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19483
19484                let display_hunk = if hunk_display_start.column() != 0 {
19485                    DisplayDiffHunk::Folded {
19486                        display_row: hunk_display_start.row(),
19487                    }
19488                } else {
19489                    let mut end_row = hunk_display_end.row();
19490                    if hunk_display_end.column() > 0 {
19491                        end_row.0 += 1;
19492                    }
19493                    let is_created_file = hunk.is_created_file();
19494                    DisplayDiffHunk::Unfolded {
19495                        status: hunk.status(),
19496                        diff_base_byte_range: hunk.diff_base_byte_range,
19497                        display_row_range: hunk_display_start.row()..end_row,
19498                        multi_buffer_range: Anchor::range_in_buffer(
19499                            hunk.excerpt_id,
19500                            hunk.buffer_id,
19501                            hunk.buffer_range,
19502                        ),
19503                        is_created_file,
19504                    }
19505                };
19506
19507                Some(display_hunk)
19508            })
19509    }
19510
19511    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19512        self.display_snapshot.buffer_snapshot.language_at(position)
19513    }
19514
19515    pub fn is_focused(&self) -> bool {
19516        self.is_focused
19517    }
19518
19519    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19520        self.placeholder_text.as_ref()
19521    }
19522
19523    pub fn scroll_position(&self) -> gpui::Point<f32> {
19524        self.scroll_anchor.scroll_position(&self.display_snapshot)
19525    }
19526
19527    fn gutter_dimensions(
19528        &self,
19529        font_id: FontId,
19530        font_size: Pixels,
19531        max_line_number_width: Pixels,
19532        cx: &App,
19533    ) -> Option<GutterDimensions> {
19534        if !self.show_gutter {
19535            return None;
19536        }
19537
19538        let descent = cx.text_system().descent(font_id, font_size);
19539        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19540        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19541
19542        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19543            matches!(
19544                ProjectSettings::get_global(cx).git.git_gutter,
19545                Some(GitGutterSetting::TrackedFiles)
19546            )
19547        });
19548        let gutter_settings = EditorSettings::get_global(cx).gutter;
19549        let show_line_numbers = self
19550            .show_line_numbers
19551            .unwrap_or(gutter_settings.line_numbers);
19552        let line_gutter_width = if show_line_numbers {
19553            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19554            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19555            max_line_number_width.max(min_width_for_number_on_gutter)
19556        } else {
19557            0.0.into()
19558        };
19559
19560        let show_code_actions = self
19561            .show_code_actions
19562            .unwrap_or(gutter_settings.code_actions);
19563
19564        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19565        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19566
19567        let git_blame_entries_width =
19568            self.git_blame_gutter_max_author_length
19569                .map(|max_author_length| {
19570                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19571                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19572
19573                    /// The number of characters to dedicate to gaps and margins.
19574                    const SPACING_WIDTH: usize = 4;
19575
19576                    let max_char_count = max_author_length.min(renderer.max_author_length())
19577                        + ::git::SHORT_SHA_LENGTH
19578                        + MAX_RELATIVE_TIMESTAMP.len()
19579                        + SPACING_WIDTH;
19580
19581                    em_advance * max_char_count
19582                });
19583
19584        let is_singleton = self.buffer_snapshot.is_singleton();
19585
19586        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19587        left_padding += if !is_singleton {
19588            em_width * 4.0
19589        } else if show_code_actions || show_runnables || show_breakpoints {
19590            em_width * 3.0
19591        } else if show_git_gutter && show_line_numbers {
19592            em_width * 2.0
19593        } else if show_git_gutter || show_line_numbers {
19594            em_width
19595        } else {
19596            px(0.)
19597        };
19598
19599        let shows_folds = is_singleton && gutter_settings.folds;
19600
19601        let right_padding = if shows_folds && show_line_numbers {
19602            em_width * 4.0
19603        } else if shows_folds || (!is_singleton && show_line_numbers) {
19604            em_width * 3.0
19605        } else if show_line_numbers {
19606            em_width
19607        } else {
19608            px(0.)
19609        };
19610
19611        Some(GutterDimensions {
19612            left_padding,
19613            right_padding,
19614            width: line_gutter_width + left_padding + right_padding,
19615            margin: -descent,
19616            git_blame_entries_width,
19617        })
19618    }
19619
19620    pub fn render_crease_toggle(
19621        &self,
19622        buffer_row: MultiBufferRow,
19623        row_contains_cursor: bool,
19624        editor: Entity<Editor>,
19625        window: &mut Window,
19626        cx: &mut App,
19627    ) -> Option<AnyElement> {
19628        let folded = self.is_line_folded(buffer_row);
19629        let mut is_foldable = false;
19630
19631        if let Some(crease) = self
19632            .crease_snapshot
19633            .query_row(buffer_row, &self.buffer_snapshot)
19634        {
19635            is_foldable = true;
19636            match crease {
19637                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19638                    if let Some(render_toggle) = render_toggle {
19639                        let toggle_callback =
19640                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19641                                if folded {
19642                                    editor.update(cx, |editor, cx| {
19643                                        editor.fold_at(buffer_row, window, cx)
19644                                    });
19645                                } else {
19646                                    editor.update(cx, |editor, cx| {
19647                                        editor.unfold_at(buffer_row, window, cx)
19648                                    });
19649                                }
19650                            });
19651                        return Some((render_toggle)(
19652                            buffer_row,
19653                            folded,
19654                            toggle_callback,
19655                            window,
19656                            cx,
19657                        ));
19658                    }
19659                }
19660            }
19661        }
19662
19663        is_foldable |= self.starts_indent(buffer_row);
19664
19665        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19666            Some(
19667                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19668                    .toggle_state(folded)
19669                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19670                        if folded {
19671                            this.unfold_at(buffer_row, window, cx);
19672                        } else {
19673                            this.fold_at(buffer_row, window, cx);
19674                        }
19675                    }))
19676                    .into_any_element(),
19677            )
19678        } else {
19679            None
19680        }
19681    }
19682
19683    pub fn render_crease_trailer(
19684        &self,
19685        buffer_row: MultiBufferRow,
19686        window: &mut Window,
19687        cx: &mut App,
19688    ) -> Option<AnyElement> {
19689        let folded = self.is_line_folded(buffer_row);
19690        if let Crease::Inline { render_trailer, .. } = self
19691            .crease_snapshot
19692            .query_row(buffer_row, &self.buffer_snapshot)?
19693        {
19694            let render_trailer = render_trailer.as_ref()?;
19695            Some(render_trailer(buffer_row, folded, window, cx))
19696        } else {
19697            None
19698        }
19699    }
19700}
19701
19702impl Deref for EditorSnapshot {
19703    type Target = DisplaySnapshot;
19704
19705    fn deref(&self) -> &Self::Target {
19706        &self.display_snapshot
19707    }
19708}
19709
19710#[derive(Clone, Debug, PartialEq, Eq)]
19711pub enum EditorEvent {
19712    InputIgnored {
19713        text: Arc<str>,
19714    },
19715    InputHandled {
19716        utf16_range_to_replace: Option<Range<isize>>,
19717        text: Arc<str>,
19718    },
19719    ExcerptsAdded {
19720        buffer: Entity<Buffer>,
19721        predecessor: ExcerptId,
19722        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19723    },
19724    ExcerptsRemoved {
19725        ids: Vec<ExcerptId>,
19726    },
19727    BufferFoldToggled {
19728        ids: Vec<ExcerptId>,
19729        folded: bool,
19730    },
19731    ExcerptsEdited {
19732        ids: Vec<ExcerptId>,
19733    },
19734    ExcerptsExpanded {
19735        ids: Vec<ExcerptId>,
19736    },
19737    BufferEdited,
19738    Edited {
19739        transaction_id: clock::Lamport,
19740    },
19741    Reparsed(BufferId),
19742    Focused,
19743    FocusedIn,
19744    Blurred,
19745    DirtyChanged,
19746    Saved,
19747    TitleChanged,
19748    DiffBaseChanged,
19749    SelectionsChanged {
19750        local: bool,
19751    },
19752    ScrollPositionChanged {
19753        local: bool,
19754        autoscroll: bool,
19755    },
19756    Closed,
19757    TransactionUndone {
19758        transaction_id: clock::Lamport,
19759    },
19760    TransactionBegun {
19761        transaction_id: clock::Lamport,
19762    },
19763    Reloaded,
19764    CursorShapeChanged,
19765    PushedToNavHistory {
19766        anchor: Anchor,
19767        is_deactivate: bool,
19768    },
19769}
19770
19771impl EventEmitter<EditorEvent> for Editor {}
19772
19773impl Focusable for Editor {
19774    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19775        self.focus_handle.clone()
19776    }
19777}
19778
19779impl Render for Editor {
19780    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19781        let settings = ThemeSettings::get_global(cx);
19782
19783        let mut text_style = match self.mode {
19784            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19785                color: cx.theme().colors().editor_foreground,
19786                font_family: settings.ui_font.family.clone(),
19787                font_features: settings.ui_font.features.clone(),
19788                font_fallbacks: settings.ui_font.fallbacks.clone(),
19789                font_size: rems(0.875).into(),
19790                font_weight: settings.ui_font.weight,
19791                line_height: relative(settings.buffer_line_height.value()),
19792                ..Default::default()
19793            },
19794            EditorMode::Full { .. } => TextStyle {
19795                color: cx.theme().colors().editor_foreground,
19796                font_family: settings.buffer_font.family.clone(),
19797                font_features: settings.buffer_font.features.clone(),
19798                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19799                font_size: settings.buffer_font_size(cx).into(),
19800                font_weight: settings.buffer_font.weight,
19801                line_height: relative(settings.buffer_line_height.value()),
19802                ..Default::default()
19803            },
19804        };
19805        if let Some(text_style_refinement) = &self.text_style_refinement {
19806            text_style.refine(text_style_refinement)
19807        }
19808
19809        let background = match self.mode {
19810            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19811            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19812            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19813        };
19814
19815        EditorElement::new(
19816            &cx.entity(),
19817            EditorStyle {
19818                background,
19819                local_player: cx.theme().players().local(),
19820                text: text_style,
19821                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19822                syntax: cx.theme().syntax().clone(),
19823                status: cx.theme().status().clone(),
19824                inlay_hints_style: make_inlay_hints_style(cx),
19825                inline_completion_styles: make_suggestion_styles(cx),
19826                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19827            },
19828        )
19829    }
19830}
19831
19832impl EntityInputHandler for Editor {
19833    fn text_for_range(
19834        &mut self,
19835        range_utf16: Range<usize>,
19836        adjusted_range: &mut Option<Range<usize>>,
19837        _: &mut Window,
19838        cx: &mut Context<Self>,
19839    ) -> Option<String> {
19840        let snapshot = self.buffer.read(cx).read(cx);
19841        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19842        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19843        if (start.0..end.0) != range_utf16 {
19844            adjusted_range.replace(start.0..end.0);
19845        }
19846        Some(snapshot.text_for_range(start..end).collect())
19847    }
19848
19849    fn selected_text_range(
19850        &mut self,
19851        ignore_disabled_input: bool,
19852        _: &mut Window,
19853        cx: &mut Context<Self>,
19854    ) -> Option<UTF16Selection> {
19855        // Prevent the IME menu from appearing when holding down an alphabetic key
19856        // while input is disabled.
19857        if !ignore_disabled_input && !self.input_enabled {
19858            return None;
19859        }
19860
19861        let selection = self.selections.newest::<OffsetUtf16>(cx);
19862        let range = selection.range();
19863
19864        Some(UTF16Selection {
19865            range: range.start.0..range.end.0,
19866            reversed: selection.reversed,
19867        })
19868    }
19869
19870    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19871        let snapshot = self.buffer.read(cx).read(cx);
19872        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19873        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19874    }
19875
19876    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19877        self.clear_highlights::<InputComposition>(cx);
19878        self.ime_transaction.take();
19879    }
19880
19881    fn replace_text_in_range(
19882        &mut self,
19883        range_utf16: Option<Range<usize>>,
19884        text: &str,
19885        window: &mut Window,
19886        cx: &mut Context<Self>,
19887    ) {
19888        if !self.input_enabled {
19889            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19890            return;
19891        }
19892
19893        self.transact(window, cx, |this, window, cx| {
19894            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19895                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19896                Some(this.selection_replacement_ranges(range_utf16, cx))
19897            } else {
19898                this.marked_text_ranges(cx)
19899            };
19900
19901            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19902                let newest_selection_id = this.selections.newest_anchor().id;
19903                this.selections
19904                    .all::<OffsetUtf16>(cx)
19905                    .iter()
19906                    .zip(ranges_to_replace.iter())
19907                    .find_map(|(selection, range)| {
19908                        if selection.id == newest_selection_id {
19909                            Some(
19910                                (range.start.0 as isize - selection.head().0 as isize)
19911                                    ..(range.end.0 as isize - selection.head().0 as isize),
19912                            )
19913                        } else {
19914                            None
19915                        }
19916                    })
19917            });
19918
19919            cx.emit(EditorEvent::InputHandled {
19920                utf16_range_to_replace: range_to_replace,
19921                text: text.into(),
19922            });
19923
19924            if let Some(new_selected_ranges) = new_selected_ranges {
19925                this.change_selections(None, window, cx, |selections| {
19926                    selections.select_ranges(new_selected_ranges)
19927                });
19928                this.backspace(&Default::default(), window, cx);
19929            }
19930
19931            this.handle_input(text, window, cx);
19932        });
19933
19934        if let Some(transaction) = self.ime_transaction {
19935            self.buffer.update(cx, |buffer, cx| {
19936                buffer.group_until_transaction(transaction, cx);
19937            });
19938        }
19939
19940        self.unmark_text(window, cx);
19941    }
19942
19943    fn replace_and_mark_text_in_range(
19944        &mut self,
19945        range_utf16: Option<Range<usize>>,
19946        text: &str,
19947        new_selected_range_utf16: Option<Range<usize>>,
19948        window: &mut Window,
19949        cx: &mut Context<Self>,
19950    ) {
19951        if !self.input_enabled {
19952            return;
19953        }
19954
19955        let transaction = self.transact(window, cx, |this, window, cx| {
19956            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19957                let snapshot = this.buffer.read(cx).read(cx);
19958                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19959                    for marked_range in &mut marked_ranges {
19960                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19961                        marked_range.start.0 += relative_range_utf16.start;
19962                        marked_range.start =
19963                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19964                        marked_range.end =
19965                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19966                    }
19967                }
19968                Some(marked_ranges)
19969            } else if let Some(range_utf16) = range_utf16 {
19970                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19971                Some(this.selection_replacement_ranges(range_utf16, cx))
19972            } else {
19973                None
19974            };
19975
19976            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19977                let newest_selection_id = this.selections.newest_anchor().id;
19978                this.selections
19979                    .all::<OffsetUtf16>(cx)
19980                    .iter()
19981                    .zip(ranges_to_replace.iter())
19982                    .find_map(|(selection, range)| {
19983                        if selection.id == newest_selection_id {
19984                            Some(
19985                                (range.start.0 as isize - selection.head().0 as isize)
19986                                    ..(range.end.0 as isize - selection.head().0 as isize),
19987                            )
19988                        } else {
19989                            None
19990                        }
19991                    })
19992            });
19993
19994            cx.emit(EditorEvent::InputHandled {
19995                utf16_range_to_replace: range_to_replace,
19996                text: text.into(),
19997            });
19998
19999            if let Some(ranges) = ranges_to_replace {
20000                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20001            }
20002
20003            let marked_ranges = {
20004                let snapshot = this.buffer.read(cx).read(cx);
20005                this.selections
20006                    .disjoint_anchors()
20007                    .iter()
20008                    .map(|selection| {
20009                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20010                    })
20011                    .collect::<Vec<_>>()
20012            };
20013
20014            if text.is_empty() {
20015                this.unmark_text(window, cx);
20016            } else {
20017                this.highlight_text::<InputComposition>(
20018                    marked_ranges.clone(),
20019                    HighlightStyle {
20020                        underline: Some(UnderlineStyle {
20021                            thickness: px(1.),
20022                            color: None,
20023                            wavy: false,
20024                        }),
20025                        ..Default::default()
20026                    },
20027                    cx,
20028                );
20029            }
20030
20031            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20032            let use_autoclose = this.use_autoclose;
20033            let use_auto_surround = this.use_auto_surround;
20034            this.set_use_autoclose(false);
20035            this.set_use_auto_surround(false);
20036            this.handle_input(text, window, cx);
20037            this.set_use_autoclose(use_autoclose);
20038            this.set_use_auto_surround(use_auto_surround);
20039
20040            if let Some(new_selected_range) = new_selected_range_utf16 {
20041                let snapshot = this.buffer.read(cx).read(cx);
20042                let new_selected_ranges = marked_ranges
20043                    .into_iter()
20044                    .map(|marked_range| {
20045                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20046                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20047                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20048                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20049                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20050                    })
20051                    .collect::<Vec<_>>();
20052
20053                drop(snapshot);
20054                this.change_selections(None, window, cx, |selections| {
20055                    selections.select_ranges(new_selected_ranges)
20056                });
20057            }
20058        });
20059
20060        self.ime_transaction = self.ime_transaction.or(transaction);
20061        if let Some(transaction) = self.ime_transaction {
20062            self.buffer.update(cx, |buffer, cx| {
20063                buffer.group_until_transaction(transaction, cx);
20064            });
20065        }
20066
20067        if self.text_highlights::<InputComposition>(cx).is_none() {
20068            self.ime_transaction.take();
20069        }
20070    }
20071
20072    fn bounds_for_range(
20073        &mut self,
20074        range_utf16: Range<usize>,
20075        element_bounds: gpui::Bounds<Pixels>,
20076        window: &mut Window,
20077        cx: &mut Context<Self>,
20078    ) -> Option<gpui::Bounds<Pixels>> {
20079        let text_layout_details = self.text_layout_details(window);
20080        let gpui::Size {
20081            width: em_width,
20082            height: line_height,
20083        } = self.character_size(window);
20084
20085        let snapshot = self.snapshot(window, cx);
20086        let scroll_position = snapshot.scroll_position();
20087        let scroll_left = scroll_position.x * em_width;
20088
20089        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20090        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20091            + self.gutter_dimensions.width
20092            + self.gutter_dimensions.margin;
20093        let y = line_height * (start.row().as_f32() - scroll_position.y);
20094
20095        Some(Bounds {
20096            origin: element_bounds.origin + point(x, y),
20097            size: size(em_width, line_height),
20098        })
20099    }
20100
20101    fn character_index_for_point(
20102        &mut self,
20103        point: gpui::Point<Pixels>,
20104        _window: &mut Window,
20105        _cx: &mut Context<Self>,
20106    ) -> Option<usize> {
20107        let position_map = self.last_position_map.as_ref()?;
20108        if !position_map.text_hitbox.contains(&point) {
20109            return None;
20110        }
20111        let display_point = position_map.point_for_position(point).previous_valid;
20112        let anchor = position_map
20113            .snapshot
20114            .display_point_to_anchor(display_point, Bias::Left);
20115        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20116        Some(utf16_offset.0)
20117    }
20118}
20119
20120trait SelectionExt {
20121    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20122    fn spanned_rows(
20123        &self,
20124        include_end_if_at_line_start: bool,
20125        map: &DisplaySnapshot,
20126    ) -> Range<MultiBufferRow>;
20127}
20128
20129impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20130    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20131        let start = self
20132            .start
20133            .to_point(&map.buffer_snapshot)
20134            .to_display_point(map);
20135        let end = self
20136            .end
20137            .to_point(&map.buffer_snapshot)
20138            .to_display_point(map);
20139        if self.reversed {
20140            end..start
20141        } else {
20142            start..end
20143        }
20144    }
20145
20146    fn spanned_rows(
20147        &self,
20148        include_end_if_at_line_start: bool,
20149        map: &DisplaySnapshot,
20150    ) -> Range<MultiBufferRow> {
20151        let start = self.start.to_point(&map.buffer_snapshot);
20152        let mut end = self.end.to_point(&map.buffer_snapshot);
20153        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20154            end.row -= 1;
20155        }
20156
20157        let buffer_start = map.prev_line_boundary(start).0;
20158        let buffer_end = map.next_line_boundary(end).0;
20159        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20160    }
20161}
20162
20163impl<T: InvalidationRegion> InvalidationStack<T> {
20164    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20165    where
20166        S: Clone + ToOffset,
20167    {
20168        while let Some(region) = self.last() {
20169            let all_selections_inside_invalidation_ranges =
20170                if selections.len() == region.ranges().len() {
20171                    selections
20172                        .iter()
20173                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20174                        .all(|(selection, invalidation_range)| {
20175                            let head = selection.head().to_offset(buffer);
20176                            invalidation_range.start <= head && invalidation_range.end >= head
20177                        })
20178                } else {
20179                    false
20180                };
20181
20182            if all_selections_inside_invalidation_ranges {
20183                break;
20184            } else {
20185                self.pop();
20186            }
20187        }
20188    }
20189}
20190
20191impl<T> Default for InvalidationStack<T> {
20192    fn default() -> Self {
20193        Self(Default::default())
20194    }
20195}
20196
20197impl<T> Deref for InvalidationStack<T> {
20198    type Target = Vec<T>;
20199
20200    fn deref(&self) -> &Self::Target {
20201        &self.0
20202    }
20203}
20204
20205impl<T> DerefMut for InvalidationStack<T> {
20206    fn deref_mut(&mut self) -> &mut Self::Target {
20207        &mut self.0
20208    }
20209}
20210
20211impl InvalidationRegion for SnippetState {
20212    fn ranges(&self) -> &[Range<Anchor>] {
20213        &self.ranges[self.active_index]
20214    }
20215}
20216
20217fn inline_completion_edit_text(
20218    current_snapshot: &BufferSnapshot,
20219    edits: &[(Range<Anchor>, String)],
20220    edit_preview: &EditPreview,
20221    include_deletions: bool,
20222    cx: &App,
20223) -> HighlightedText {
20224    let edits = edits
20225        .iter()
20226        .map(|(anchor, text)| {
20227            (
20228                anchor.start.text_anchor..anchor.end.text_anchor,
20229                text.clone(),
20230            )
20231        })
20232        .collect::<Vec<_>>();
20233
20234    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20235}
20236
20237pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20238    match severity {
20239        DiagnosticSeverity::ERROR => colors.error,
20240        DiagnosticSeverity::WARNING => colors.warning,
20241        DiagnosticSeverity::INFORMATION => colors.info,
20242        DiagnosticSeverity::HINT => colors.info,
20243        _ => colors.ignored,
20244    }
20245}
20246
20247pub fn styled_runs_for_code_label<'a>(
20248    label: &'a CodeLabel,
20249    syntax_theme: &'a theme::SyntaxTheme,
20250) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20251    let fade_out = HighlightStyle {
20252        fade_out: Some(0.35),
20253        ..Default::default()
20254    };
20255
20256    let mut prev_end = label.filter_range.end;
20257    label
20258        .runs
20259        .iter()
20260        .enumerate()
20261        .flat_map(move |(ix, (range, highlight_id))| {
20262            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20263                style
20264            } else {
20265                return Default::default();
20266            };
20267            let mut muted_style = style;
20268            muted_style.highlight(fade_out);
20269
20270            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20271            if range.start >= label.filter_range.end {
20272                if range.start > prev_end {
20273                    runs.push((prev_end..range.start, fade_out));
20274                }
20275                runs.push((range.clone(), muted_style));
20276            } else if range.end <= label.filter_range.end {
20277                runs.push((range.clone(), style));
20278            } else {
20279                runs.push((range.start..label.filter_range.end, style));
20280                runs.push((label.filter_range.end..range.end, muted_style));
20281            }
20282            prev_end = cmp::max(prev_end, range.end);
20283
20284            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20285                runs.push((prev_end..label.text.len(), fade_out));
20286            }
20287
20288            runs
20289        })
20290}
20291
20292pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20293    let mut prev_index = 0;
20294    let mut prev_codepoint: Option<char> = None;
20295    text.char_indices()
20296        .chain([(text.len(), '\0')])
20297        .filter_map(move |(index, codepoint)| {
20298            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20299            let is_boundary = index == text.len()
20300                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20301                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20302            if is_boundary {
20303                let chunk = &text[prev_index..index];
20304                prev_index = index;
20305                Some(chunk)
20306            } else {
20307                None
20308            }
20309        })
20310}
20311
20312pub trait RangeToAnchorExt: Sized {
20313    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20314
20315    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20316        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20317        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20318    }
20319}
20320
20321impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20322    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20323        let start_offset = self.start.to_offset(snapshot);
20324        let end_offset = self.end.to_offset(snapshot);
20325        if start_offset == end_offset {
20326            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20327        } else {
20328            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20329        }
20330    }
20331}
20332
20333pub trait RowExt {
20334    fn as_f32(&self) -> f32;
20335
20336    fn next_row(&self) -> Self;
20337
20338    fn previous_row(&self) -> Self;
20339
20340    fn minus(&self, other: Self) -> u32;
20341}
20342
20343impl RowExt for DisplayRow {
20344    fn as_f32(&self) -> f32 {
20345        self.0 as f32
20346    }
20347
20348    fn next_row(&self) -> Self {
20349        Self(self.0 + 1)
20350    }
20351
20352    fn previous_row(&self) -> Self {
20353        Self(self.0.saturating_sub(1))
20354    }
20355
20356    fn minus(&self, other: Self) -> u32 {
20357        self.0 - other.0
20358    }
20359}
20360
20361impl RowExt for MultiBufferRow {
20362    fn as_f32(&self) -> f32 {
20363        self.0 as f32
20364    }
20365
20366    fn next_row(&self) -> Self {
20367        Self(self.0 + 1)
20368    }
20369
20370    fn previous_row(&self) -> Self {
20371        Self(self.0.saturating_sub(1))
20372    }
20373
20374    fn minus(&self, other: Self) -> u32 {
20375        self.0 - other.0
20376    }
20377}
20378
20379trait RowRangeExt {
20380    type Row;
20381
20382    fn len(&self) -> usize;
20383
20384    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20385}
20386
20387impl RowRangeExt for Range<MultiBufferRow> {
20388    type Row = MultiBufferRow;
20389
20390    fn len(&self) -> usize {
20391        (self.end.0 - self.start.0) as usize
20392    }
20393
20394    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20395        (self.start.0..self.end.0).map(MultiBufferRow)
20396    }
20397}
20398
20399impl RowRangeExt for Range<DisplayRow> {
20400    type Row = DisplayRow;
20401
20402    fn len(&self) -> usize {
20403        (self.end.0 - self.start.0) as usize
20404    }
20405
20406    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20407        (self.start.0..self.end.0).map(DisplayRow)
20408    }
20409}
20410
20411/// If select range has more than one line, we
20412/// just point the cursor to range.start.
20413fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20414    if range.start.row == range.end.row {
20415        range
20416    } else {
20417        range.start..range.start
20418    }
20419}
20420pub struct KillRing(ClipboardItem);
20421impl Global for KillRing {}
20422
20423const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20424
20425enum BreakpointPromptEditAction {
20426    Log,
20427    Condition,
20428    HitCondition,
20429}
20430
20431struct BreakpointPromptEditor {
20432    pub(crate) prompt: Entity<Editor>,
20433    editor: WeakEntity<Editor>,
20434    breakpoint_anchor: Anchor,
20435    breakpoint: Breakpoint,
20436    edit_action: BreakpointPromptEditAction,
20437    block_ids: HashSet<CustomBlockId>,
20438    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20439    _subscriptions: Vec<Subscription>,
20440}
20441
20442impl BreakpointPromptEditor {
20443    const MAX_LINES: u8 = 4;
20444
20445    fn new(
20446        editor: WeakEntity<Editor>,
20447        breakpoint_anchor: Anchor,
20448        breakpoint: Breakpoint,
20449        edit_action: BreakpointPromptEditAction,
20450        window: &mut Window,
20451        cx: &mut Context<Self>,
20452    ) -> Self {
20453        let base_text = match edit_action {
20454            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20455            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20456            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20457        }
20458        .map(|msg| msg.to_string())
20459        .unwrap_or_default();
20460
20461        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20462        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20463
20464        let prompt = cx.new(|cx| {
20465            let mut prompt = Editor::new(
20466                EditorMode::AutoHeight {
20467                    max_lines: Self::MAX_LINES as usize,
20468                },
20469                buffer,
20470                None,
20471                window,
20472                cx,
20473            );
20474            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20475            prompt.set_show_cursor_when_unfocused(false, cx);
20476            prompt.set_placeholder_text(
20477                match edit_action {
20478                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20479                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20480                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20481                },
20482                cx,
20483            );
20484
20485            prompt
20486        });
20487
20488        Self {
20489            prompt,
20490            editor,
20491            breakpoint_anchor,
20492            breakpoint,
20493            edit_action,
20494            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20495            block_ids: Default::default(),
20496            _subscriptions: vec![],
20497        }
20498    }
20499
20500    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20501        self.block_ids.extend(block_ids)
20502    }
20503
20504    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20505        if let Some(editor) = self.editor.upgrade() {
20506            let message = self
20507                .prompt
20508                .read(cx)
20509                .buffer
20510                .read(cx)
20511                .as_singleton()
20512                .expect("A multi buffer in breakpoint prompt isn't possible")
20513                .read(cx)
20514                .as_rope()
20515                .to_string();
20516
20517            editor.update(cx, |editor, cx| {
20518                editor.edit_breakpoint_at_anchor(
20519                    self.breakpoint_anchor,
20520                    self.breakpoint.clone(),
20521                    match self.edit_action {
20522                        BreakpointPromptEditAction::Log => {
20523                            BreakpointEditAction::EditLogMessage(message.into())
20524                        }
20525                        BreakpointPromptEditAction::Condition => {
20526                            BreakpointEditAction::EditCondition(message.into())
20527                        }
20528                        BreakpointPromptEditAction::HitCondition => {
20529                            BreakpointEditAction::EditHitCondition(message.into())
20530                        }
20531                    },
20532                    cx,
20533                );
20534
20535                editor.remove_blocks(self.block_ids.clone(), None, cx);
20536                cx.focus_self(window);
20537            });
20538        }
20539    }
20540
20541    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20542        self.editor
20543            .update(cx, |editor, cx| {
20544                editor.remove_blocks(self.block_ids.clone(), None, cx);
20545                window.focus(&editor.focus_handle);
20546            })
20547            .log_err();
20548    }
20549
20550    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20551        let settings = ThemeSettings::get_global(cx);
20552        let text_style = TextStyle {
20553            color: if self.prompt.read(cx).read_only(cx) {
20554                cx.theme().colors().text_disabled
20555            } else {
20556                cx.theme().colors().text
20557            },
20558            font_family: settings.buffer_font.family.clone(),
20559            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20560            font_size: settings.buffer_font_size(cx).into(),
20561            font_weight: settings.buffer_font.weight,
20562            line_height: relative(settings.buffer_line_height.value()),
20563            ..Default::default()
20564        };
20565        EditorElement::new(
20566            &self.prompt,
20567            EditorStyle {
20568                background: cx.theme().colors().editor_background,
20569                local_player: cx.theme().players().local(),
20570                text: text_style,
20571                ..Default::default()
20572            },
20573        )
20574    }
20575}
20576
20577impl Render for BreakpointPromptEditor {
20578    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20579        let gutter_dimensions = *self.gutter_dimensions.lock();
20580        h_flex()
20581            .key_context("Editor")
20582            .bg(cx.theme().colors().editor_background)
20583            .border_y_1()
20584            .border_color(cx.theme().status().info_border)
20585            .size_full()
20586            .py(window.line_height() / 2.5)
20587            .on_action(cx.listener(Self::confirm))
20588            .on_action(cx.listener(Self::cancel))
20589            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20590            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20591    }
20592}
20593
20594impl Focusable for BreakpointPromptEditor {
20595    fn focus_handle(&self, cx: &App) -> FocusHandle {
20596        self.prompt.focus_handle(cx)
20597    }
20598}
20599
20600fn all_edits_insertions_or_deletions(
20601    edits: &Vec<(Range<Anchor>, String)>,
20602    snapshot: &MultiBufferSnapshot,
20603) -> bool {
20604    let mut all_insertions = true;
20605    let mut all_deletions = true;
20606
20607    for (range, new_text) in edits.iter() {
20608        let range_is_empty = range.to_offset(&snapshot).is_empty();
20609        let text_is_empty = new_text.is_empty();
20610
20611        if range_is_empty != text_is_empty {
20612            if range_is_empty {
20613                all_deletions = false;
20614            } else {
20615                all_insertions = false;
20616            }
20617        } else {
20618            return false;
20619        }
20620
20621        if !all_insertions && !all_deletions {
20622            return false;
20623        }
20624    }
20625    all_insertions || all_deletions
20626}
20627
20628struct MissingEditPredictionKeybindingTooltip;
20629
20630impl Render for MissingEditPredictionKeybindingTooltip {
20631    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20632        ui::tooltip_container(window, cx, |container, _, cx| {
20633            container
20634                .flex_shrink_0()
20635                .max_w_80()
20636                .min_h(rems_from_px(124.))
20637                .justify_between()
20638                .child(
20639                    v_flex()
20640                        .flex_1()
20641                        .text_ui_sm(cx)
20642                        .child(Label::new("Conflict with Accept Keybinding"))
20643                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20644                )
20645                .child(
20646                    h_flex()
20647                        .pb_1()
20648                        .gap_1()
20649                        .items_end()
20650                        .w_full()
20651                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20652                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20653                        }))
20654                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20655                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20656                        })),
20657                )
20658        })
20659    }
20660}
20661
20662#[derive(Debug, Clone, Copy, PartialEq)]
20663pub struct LineHighlight {
20664    pub background: Background,
20665    pub border: Option<gpui::Hsla>,
20666}
20667
20668impl From<Hsla> for LineHighlight {
20669    fn from(hsla: Hsla) -> Self {
20670        Self {
20671            background: hsla.into(),
20672            border: None,
20673        }
20674    }
20675}
20676
20677impl From<Background> for LineHighlight {
20678    fn from(background: Background) -> Self {
20679        Self {
20680            background,
20681            border: None,
20682        }
20683    }
20684}
20685
20686fn render_diff_hunk_controls(
20687    row: u32,
20688    status: &DiffHunkStatus,
20689    hunk_range: Range<Anchor>,
20690    is_created_file: bool,
20691    line_height: Pixels,
20692    editor: &Entity<Editor>,
20693    _window: &mut Window,
20694    cx: &mut App,
20695) -> AnyElement {
20696    h_flex()
20697        .h(line_height)
20698        .mr_1()
20699        .gap_1()
20700        .px_0p5()
20701        .pb_1()
20702        .border_x_1()
20703        .border_b_1()
20704        .border_color(cx.theme().colors().border_variant)
20705        .rounded_b_lg()
20706        .bg(cx.theme().colors().editor_background)
20707        .gap_1()
20708        .occlude()
20709        .shadow_md()
20710        .child(if status.has_secondary_hunk() {
20711            Button::new(("stage", row as u64), "Stage")
20712                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20713                .tooltip({
20714                    let focus_handle = editor.focus_handle(cx);
20715                    move |window, cx| {
20716                        Tooltip::for_action_in(
20717                            "Stage Hunk",
20718                            &::git::ToggleStaged,
20719                            &focus_handle,
20720                            window,
20721                            cx,
20722                        )
20723                    }
20724                })
20725                .on_click({
20726                    let editor = editor.clone();
20727                    move |_event, _window, cx| {
20728                        editor.update(cx, |editor, cx| {
20729                            editor.stage_or_unstage_diff_hunks(
20730                                true,
20731                                vec![hunk_range.start..hunk_range.start],
20732                                cx,
20733                            );
20734                        });
20735                    }
20736                })
20737        } else {
20738            Button::new(("unstage", row as u64), "Unstage")
20739                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20740                .tooltip({
20741                    let focus_handle = editor.focus_handle(cx);
20742                    move |window, cx| {
20743                        Tooltip::for_action_in(
20744                            "Unstage Hunk",
20745                            &::git::ToggleStaged,
20746                            &focus_handle,
20747                            window,
20748                            cx,
20749                        )
20750                    }
20751                })
20752                .on_click({
20753                    let editor = editor.clone();
20754                    move |_event, _window, cx| {
20755                        editor.update(cx, |editor, cx| {
20756                            editor.stage_or_unstage_diff_hunks(
20757                                false,
20758                                vec![hunk_range.start..hunk_range.start],
20759                                cx,
20760                            );
20761                        });
20762                    }
20763                })
20764        })
20765        .child(
20766            Button::new(("restore", row as u64), "Restore")
20767                .tooltip({
20768                    let focus_handle = editor.focus_handle(cx);
20769                    move |window, cx| {
20770                        Tooltip::for_action_in(
20771                            "Restore Hunk",
20772                            &::git::Restore,
20773                            &focus_handle,
20774                            window,
20775                            cx,
20776                        )
20777                    }
20778                })
20779                .on_click({
20780                    let editor = editor.clone();
20781                    move |_event, window, cx| {
20782                        editor.update(cx, |editor, cx| {
20783                            let snapshot = editor.snapshot(window, cx);
20784                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20785                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20786                        });
20787                    }
20788                })
20789                .disabled(is_created_file),
20790        )
20791        .when(
20792            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20793            |el| {
20794                el.child(
20795                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20796                        .shape(IconButtonShape::Square)
20797                        .icon_size(IconSize::Small)
20798                        // .disabled(!has_multiple_hunks)
20799                        .tooltip({
20800                            let focus_handle = editor.focus_handle(cx);
20801                            move |window, cx| {
20802                                Tooltip::for_action_in(
20803                                    "Next Hunk",
20804                                    &GoToHunk,
20805                                    &focus_handle,
20806                                    window,
20807                                    cx,
20808                                )
20809                            }
20810                        })
20811                        .on_click({
20812                            let editor = editor.clone();
20813                            move |_event, window, cx| {
20814                                editor.update(cx, |editor, cx| {
20815                                    let snapshot = editor.snapshot(window, cx);
20816                                    let position =
20817                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20818                                    editor.go_to_hunk_before_or_after_position(
20819                                        &snapshot,
20820                                        position,
20821                                        Direction::Next,
20822                                        window,
20823                                        cx,
20824                                    );
20825                                    editor.expand_selected_diff_hunks(cx);
20826                                });
20827                            }
20828                        }),
20829                )
20830                .child(
20831                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20832                        .shape(IconButtonShape::Square)
20833                        .icon_size(IconSize::Small)
20834                        // .disabled(!has_multiple_hunks)
20835                        .tooltip({
20836                            let focus_handle = editor.focus_handle(cx);
20837                            move |window, cx| {
20838                                Tooltip::for_action_in(
20839                                    "Previous Hunk",
20840                                    &GoToPreviousHunk,
20841                                    &focus_handle,
20842                                    window,
20843                                    cx,
20844                                )
20845                            }
20846                        })
20847                        .on_click({
20848                            let editor = editor.clone();
20849                            move |_event, window, cx| {
20850                                editor.update(cx, |editor, cx| {
20851                                    let snapshot = editor.snapshot(window, cx);
20852                                    let point =
20853                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20854                                    editor.go_to_hunk_before_or_after_position(
20855                                        &snapshot,
20856                                        point,
20857                                        Direction::Prev,
20858                                        window,
20859                                        cx,
20860                                    );
20861                                    editor.expand_selected_diff_hunks(cx);
20862                                });
20863                            }
20864                        }),
20865                )
20866            },
20867        )
20868        .into_any_element()
20869}