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_non_empty_selection(&self, cx: &mut App) -> bool {
 3112        self.selections
 3113            .all_adjusted(cx)
 3114            .iter()
 3115            .any(|selection| !selection.is_empty())
 3116    }
 3117
 3118    pub fn has_pending_nonempty_selection(&self) -> bool {
 3119        let pending_nonempty_selection = match self.selections.pending_anchor() {
 3120            Some(Selection { start, end, .. }) => start != end,
 3121            None => false,
 3122        };
 3123
 3124        pending_nonempty_selection
 3125            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 3126    }
 3127
 3128    pub fn has_pending_selection(&self) -> bool {
 3129        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 3130    }
 3131
 3132    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 3133        self.selection_mark_mode = false;
 3134
 3135        if self.clear_expanded_diff_hunks(cx) {
 3136            cx.notify();
 3137            return;
 3138        }
 3139        if self.dismiss_menus_and_popups(true, window, cx) {
 3140            return;
 3141        }
 3142
 3143        if self.mode.is_full()
 3144            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 3145        {
 3146            return;
 3147        }
 3148
 3149        cx.propagate();
 3150    }
 3151
 3152    pub fn dismiss_menus_and_popups(
 3153        &mut self,
 3154        is_user_requested: bool,
 3155        window: &mut Window,
 3156        cx: &mut Context<Self>,
 3157    ) -> bool {
 3158        if self.take_rename(false, window, cx).is_some() {
 3159            return true;
 3160        }
 3161
 3162        if hide_hover(self, cx) {
 3163            return true;
 3164        }
 3165
 3166        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3167            return true;
 3168        }
 3169
 3170        if self.hide_context_menu(window, cx).is_some() {
 3171            return true;
 3172        }
 3173
 3174        if self.mouse_context_menu.take().is_some() {
 3175            return true;
 3176        }
 3177
 3178        if is_user_requested && self.discard_inline_completion(true, cx) {
 3179            return true;
 3180        }
 3181
 3182        if self.snippet_stack.pop().is_some() {
 3183            return true;
 3184        }
 3185
 3186        if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
 3187            self.dismiss_diagnostics(cx);
 3188            return true;
 3189        }
 3190
 3191        false
 3192    }
 3193
 3194    fn linked_editing_ranges_for(
 3195        &self,
 3196        selection: Range<text::Anchor>,
 3197        cx: &App,
 3198    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3199        if self.linked_edit_ranges.is_empty() {
 3200            return None;
 3201        }
 3202        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3203            selection.end.buffer_id.and_then(|end_buffer_id| {
 3204                if selection.start.buffer_id != Some(end_buffer_id) {
 3205                    return None;
 3206                }
 3207                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3208                let snapshot = buffer.read(cx).snapshot();
 3209                self.linked_edit_ranges
 3210                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3211                    .map(|ranges| (ranges, snapshot, buffer))
 3212            })?;
 3213        use text::ToOffset as TO;
 3214        // find offset from the start of current range to current cursor position
 3215        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3216
 3217        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3218        let start_difference = start_offset - start_byte_offset;
 3219        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3220        let end_difference = end_offset - start_byte_offset;
 3221        // Current range has associated linked ranges.
 3222        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3223        for range in linked_ranges.iter() {
 3224            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3225            let end_offset = start_offset + end_difference;
 3226            let start_offset = start_offset + start_difference;
 3227            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3228                continue;
 3229            }
 3230            if self.selections.disjoint_anchor_ranges().any(|s| {
 3231                if s.start.buffer_id != selection.start.buffer_id
 3232                    || s.end.buffer_id != selection.end.buffer_id
 3233                {
 3234                    return false;
 3235                }
 3236                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3237                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3238            }) {
 3239                continue;
 3240            }
 3241            let start = buffer_snapshot.anchor_after(start_offset);
 3242            let end = buffer_snapshot.anchor_after(end_offset);
 3243            linked_edits
 3244                .entry(buffer.clone())
 3245                .or_default()
 3246                .push(start..end);
 3247        }
 3248        Some(linked_edits)
 3249    }
 3250
 3251    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3252        let text: Arc<str> = text.into();
 3253
 3254        if self.read_only(cx) {
 3255            return;
 3256        }
 3257
 3258        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3259
 3260        let selections = self.selections.all_adjusted(cx);
 3261        let mut bracket_inserted = false;
 3262        let mut edits = Vec::new();
 3263        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3264        let mut new_selections = Vec::with_capacity(selections.len());
 3265        let mut new_autoclose_regions = Vec::new();
 3266        let snapshot = self.buffer.read(cx).read(cx);
 3267        let mut clear_linked_edit_ranges = false;
 3268
 3269        for (selection, autoclose_region) in
 3270            self.selections_with_autoclose_regions(selections, &snapshot)
 3271        {
 3272            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3273                // Determine if the inserted text matches the opening or closing
 3274                // bracket of any of this language's bracket pairs.
 3275                let mut bracket_pair = None;
 3276                let mut is_bracket_pair_start = false;
 3277                let mut is_bracket_pair_end = false;
 3278                if !text.is_empty() {
 3279                    let mut bracket_pair_matching_end = None;
 3280                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3281                    //  and they are removing the character that triggered IME popup.
 3282                    for (pair, enabled) in scope.brackets() {
 3283                        if !pair.close && !pair.surround {
 3284                            continue;
 3285                        }
 3286
 3287                        if enabled && pair.start.ends_with(text.as_ref()) {
 3288                            let prefix_len = pair.start.len() - text.len();
 3289                            let preceding_text_matches_prefix = prefix_len == 0
 3290                                || (selection.start.column >= (prefix_len as u32)
 3291                                    && snapshot.contains_str_at(
 3292                                        Point::new(
 3293                                            selection.start.row,
 3294                                            selection.start.column - (prefix_len as u32),
 3295                                        ),
 3296                                        &pair.start[..prefix_len],
 3297                                    ));
 3298                            if preceding_text_matches_prefix {
 3299                                bracket_pair = Some(pair.clone());
 3300                                is_bracket_pair_start = true;
 3301                                break;
 3302                            }
 3303                        }
 3304                        if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
 3305                        {
 3306                            // take first bracket pair matching end, but don't break in case a later bracket
 3307                            // pair matches start
 3308                            bracket_pair_matching_end = Some(pair.clone());
 3309                        }
 3310                    }
 3311                    if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
 3312                        bracket_pair = Some(bracket_pair_matching_end.unwrap());
 3313                        is_bracket_pair_end = true;
 3314                    }
 3315                }
 3316
 3317                if let Some(bracket_pair) = bracket_pair {
 3318                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3319                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3320                    let auto_surround =
 3321                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3322                    if selection.is_empty() {
 3323                        if is_bracket_pair_start {
 3324                            // If the inserted text is a suffix of an opening bracket and the
 3325                            // selection is preceded by the rest of the opening bracket, then
 3326                            // insert the closing bracket.
 3327                            let following_text_allows_autoclose = snapshot
 3328                                .chars_at(selection.start)
 3329                                .next()
 3330                                .map_or(true, |c| scope.should_autoclose_before(c));
 3331
 3332                            let preceding_text_allows_autoclose = selection.start.column == 0
 3333                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3334                                    true,
 3335                                    |c| {
 3336                                        bracket_pair.start != bracket_pair.end
 3337                                            || !snapshot
 3338                                                .char_classifier_at(selection.start)
 3339                                                .is_word(c)
 3340                                    },
 3341                                );
 3342
 3343                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3344                                && bracket_pair.start.len() == 1
 3345                            {
 3346                                let target = bracket_pair.start.chars().next().unwrap();
 3347                                let current_line_count = snapshot
 3348                                    .reversed_chars_at(selection.start)
 3349                                    .take_while(|&c| c != '\n')
 3350                                    .filter(|&c| c == target)
 3351                                    .count();
 3352                                current_line_count % 2 == 1
 3353                            } else {
 3354                                false
 3355                            };
 3356
 3357                            if autoclose
 3358                                && bracket_pair.close
 3359                                && following_text_allows_autoclose
 3360                                && preceding_text_allows_autoclose
 3361                                && !is_closing_quote
 3362                            {
 3363                                let anchor = snapshot.anchor_before(selection.end);
 3364                                new_selections.push((selection.map(|_| anchor), text.len()));
 3365                                new_autoclose_regions.push((
 3366                                    anchor,
 3367                                    text.len(),
 3368                                    selection.id,
 3369                                    bracket_pair.clone(),
 3370                                ));
 3371                                edits.push((
 3372                                    selection.range(),
 3373                                    format!("{}{}", text, bracket_pair.end).into(),
 3374                                ));
 3375                                bracket_inserted = true;
 3376                                continue;
 3377                            }
 3378                        }
 3379
 3380                        if let Some(region) = autoclose_region {
 3381                            // If the selection is followed by an auto-inserted closing bracket,
 3382                            // then don't insert that closing bracket again; just move the selection
 3383                            // past the closing bracket.
 3384                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3385                                && text.as_ref() == region.pair.end.as_str();
 3386                            if should_skip {
 3387                                let anchor = snapshot.anchor_after(selection.end);
 3388                                new_selections
 3389                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3390                                continue;
 3391                            }
 3392                        }
 3393
 3394                        let always_treat_brackets_as_autoclosed = snapshot
 3395                            .language_settings_at(selection.start, cx)
 3396                            .always_treat_brackets_as_autoclosed;
 3397                        if always_treat_brackets_as_autoclosed
 3398                            && is_bracket_pair_end
 3399                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3400                        {
 3401                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3402                            // and the inserted text is a closing bracket and the selection is followed
 3403                            // by the closing bracket then move the selection past the closing bracket.
 3404                            let anchor = snapshot.anchor_after(selection.end);
 3405                            new_selections.push((selection.map(|_| anchor), text.len()));
 3406                            continue;
 3407                        }
 3408                    }
 3409                    // If an opening bracket is 1 character long and is typed while
 3410                    // text is selected, then surround that text with the bracket pair.
 3411                    else if auto_surround
 3412                        && bracket_pair.surround
 3413                        && is_bracket_pair_start
 3414                        && bracket_pair.start.chars().count() == 1
 3415                    {
 3416                        edits.push((selection.start..selection.start, text.clone()));
 3417                        edits.push((
 3418                            selection.end..selection.end,
 3419                            bracket_pair.end.as_str().into(),
 3420                        ));
 3421                        bracket_inserted = true;
 3422                        new_selections.push((
 3423                            Selection {
 3424                                id: selection.id,
 3425                                start: snapshot.anchor_after(selection.start),
 3426                                end: snapshot.anchor_before(selection.end),
 3427                                reversed: selection.reversed,
 3428                                goal: selection.goal,
 3429                            },
 3430                            0,
 3431                        ));
 3432                        continue;
 3433                    }
 3434                }
 3435            }
 3436
 3437            if self.auto_replace_emoji_shortcode
 3438                && selection.is_empty()
 3439                && text.as_ref().ends_with(':')
 3440            {
 3441                if let Some(possible_emoji_short_code) =
 3442                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3443                {
 3444                    if !possible_emoji_short_code.is_empty() {
 3445                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3446                            let emoji_shortcode_start = Point::new(
 3447                                selection.start.row,
 3448                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3449                            );
 3450
 3451                            // Remove shortcode from buffer
 3452                            edits.push((
 3453                                emoji_shortcode_start..selection.start,
 3454                                "".to_string().into(),
 3455                            ));
 3456                            new_selections.push((
 3457                                Selection {
 3458                                    id: selection.id,
 3459                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3460                                    end: snapshot.anchor_before(selection.start),
 3461                                    reversed: selection.reversed,
 3462                                    goal: selection.goal,
 3463                                },
 3464                                0,
 3465                            ));
 3466
 3467                            // Insert emoji
 3468                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3469                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3470                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3471
 3472                            continue;
 3473                        }
 3474                    }
 3475                }
 3476            }
 3477
 3478            // If not handling any auto-close operation, then just replace the selected
 3479            // text with the given input and move the selection to the end of the
 3480            // newly inserted text.
 3481            let anchor = snapshot.anchor_after(selection.end);
 3482            if !self.linked_edit_ranges.is_empty() {
 3483                let start_anchor = snapshot.anchor_before(selection.start);
 3484
 3485                let is_word_char = text.chars().next().map_or(true, |char| {
 3486                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3487                    classifier.is_word(char)
 3488                });
 3489
 3490                if is_word_char {
 3491                    if let Some(ranges) = self
 3492                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3493                    {
 3494                        for (buffer, edits) in ranges {
 3495                            linked_edits
 3496                                .entry(buffer.clone())
 3497                                .or_default()
 3498                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3499                        }
 3500                    }
 3501                } else {
 3502                    clear_linked_edit_ranges = true;
 3503                }
 3504            }
 3505
 3506            new_selections.push((selection.map(|_| anchor), 0));
 3507            edits.push((selection.start..selection.end, text.clone()));
 3508        }
 3509
 3510        drop(snapshot);
 3511
 3512        self.transact(window, cx, |this, window, cx| {
 3513            if clear_linked_edit_ranges {
 3514                this.linked_edit_ranges.clear();
 3515            }
 3516            let initial_buffer_versions =
 3517                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3518
 3519            this.buffer.update(cx, |buffer, cx| {
 3520                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3521            });
 3522            for (buffer, edits) in linked_edits {
 3523                buffer.update(cx, |buffer, cx| {
 3524                    let snapshot = buffer.snapshot();
 3525                    let edits = edits
 3526                        .into_iter()
 3527                        .map(|(range, text)| {
 3528                            use text::ToPoint as TP;
 3529                            let end_point = TP::to_point(&range.end, &snapshot);
 3530                            let start_point = TP::to_point(&range.start, &snapshot);
 3531                            (start_point..end_point, text)
 3532                        })
 3533                        .sorted_by_key(|(range, _)| range.start);
 3534                    buffer.edit(edits, None, cx);
 3535                })
 3536            }
 3537            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3538            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3539            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3540            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3541                .zip(new_selection_deltas)
 3542                .map(|(selection, delta)| Selection {
 3543                    id: selection.id,
 3544                    start: selection.start + delta,
 3545                    end: selection.end + delta,
 3546                    reversed: selection.reversed,
 3547                    goal: SelectionGoal::None,
 3548                })
 3549                .collect::<Vec<_>>();
 3550
 3551            let mut i = 0;
 3552            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3553                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3554                let start = map.buffer_snapshot.anchor_before(position);
 3555                let end = map.buffer_snapshot.anchor_after(position);
 3556                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3557                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3558                        Ordering::Less => i += 1,
 3559                        Ordering::Greater => break,
 3560                        Ordering::Equal => {
 3561                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3562                                Ordering::Less => i += 1,
 3563                                Ordering::Equal => break,
 3564                                Ordering::Greater => break,
 3565                            }
 3566                        }
 3567                    }
 3568                }
 3569                this.autoclose_regions.insert(
 3570                    i,
 3571                    AutocloseRegion {
 3572                        selection_id,
 3573                        range: start..end,
 3574                        pair,
 3575                    },
 3576                );
 3577            }
 3578
 3579            let had_active_inline_completion = this.has_active_inline_completion();
 3580            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3581                s.select(new_selections)
 3582            });
 3583
 3584            if !bracket_inserted {
 3585                if let Some(on_type_format_task) =
 3586                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3587                {
 3588                    on_type_format_task.detach_and_log_err(cx);
 3589                }
 3590            }
 3591
 3592            let editor_settings = EditorSettings::get_global(cx);
 3593            if bracket_inserted
 3594                && (editor_settings.auto_signature_help
 3595                    || editor_settings.show_signature_help_after_edits)
 3596            {
 3597                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3598            }
 3599
 3600            let trigger_in_words =
 3601                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3602            if this.hard_wrap.is_some() {
 3603                let latest: Range<Point> = this.selections.newest(cx).range();
 3604                if latest.is_empty()
 3605                    && this
 3606                        .buffer()
 3607                        .read(cx)
 3608                        .snapshot(cx)
 3609                        .line_len(MultiBufferRow(latest.start.row))
 3610                        == latest.start.column
 3611                {
 3612                    this.rewrap_impl(
 3613                        RewrapOptions {
 3614                            override_language_settings: true,
 3615                            preserve_existing_whitespace: true,
 3616                        },
 3617                        cx,
 3618                    )
 3619                }
 3620            }
 3621            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3622            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3623            this.refresh_inline_completion(true, false, window, cx);
 3624            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3625        });
 3626    }
 3627
 3628    fn find_possible_emoji_shortcode_at_position(
 3629        snapshot: &MultiBufferSnapshot,
 3630        position: Point,
 3631    ) -> Option<String> {
 3632        let mut chars = Vec::new();
 3633        let mut found_colon = false;
 3634        for char in snapshot.reversed_chars_at(position).take(100) {
 3635            // Found a possible emoji shortcode in the middle of the buffer
 3636            if found_colon {
 3637                if char.is_whitespace() {
 3638                    chars.reverse();
 3639                    return Some(chars.iter().collect());
 3640                }
 3641                // If the previous character is not a whitespace, we are in the middle of a word
 3642                // and we only want to complete the shortcode if the word is made up of other emojis
 3643                let mut containing_word = String::new();
 3644                for ch in snapshot
 3645                    .reversed_chars_at(position)
 3646                    .skip(chars.len() + 1)
 3647                    .take(100)
 3648                {
 3649                    if ch.is_whitespace() {
 3650                        break;
 3651                    }
 3652                    containing_word.push(ch);
 3653                }
 3654                let containing_word = containing_word.chars().rev().collect::<String>();
 3655                if util::word_consists_of_emojis(containing_word.as_str()) {
 3656                    chars.reverse();
 3657                    return Some(chars.iter().collect());
 3658                }
 3659            }
 3660
 3661            if char.is_whitespace() || !char.is_ascii() {
 3662                return None;
 3663            }
 3664            if char == ':' {
 3665                found_colon = true;
 3666            } else {
 3667                chars.push(char);
 3668            }
 3669        }
 3670        // Found a possible emoji shortcode at the beginning of the buffer
 3671        chars.reverse();
 3672        Some(chars.iter().collect())
 3673    }
 3674
 3675    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3676        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3677        self.transact(window, cx, |this, window, cx| {
 3678            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3679                let selections = this.selections.all::<usize>(cx);
 3680                let multi_buffer = this.buffer.read(cx);
 3681                let buffer = multi_buffer.snapshot(cx);
 3682                selections
 3683                    .iter()
 3684                    .map(|selection| {
 3685                        let start_point = selection.start.to_point(&buffer);
 3686                        let mut indent =
 3687                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3688                        indent.len = cmp::min(indent.len, start_point.column);
 3689                        let start = selection.start;
 3690                        let end = selection.end;
 3691                        let selection_is_empty = start == end;
 3692                        let language_scope = buffer.language_scope_at(start);
 3693                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3694                            &language_scope
 3695                        {
 3696                            let insert_extra_newline =
 3697                                insert_extra_newline_brackets(&buffer, start..end, language)
 3698                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3699
 3700                            // Comment extension on newline is allowed only for cursor selections
 3701                            let comment_delimiter = maybe!({
 3702                                if !selection_is_empty {
 3703                                    return None;
 3704                                }
 3705
 3706                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3707                                    return None;
 3708                                }
 3709
 3710                                let delimiters = language.line_comment_prefixes();
 3711                                let max_len_of_delimiter =
 3712                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3713                                let (snapshot, range) =
 3714                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3715
 3716                                let mut index_of_first_non_whitespace = 0;
 3717                                let comment_candidate = snapshot
 3718                                    .chars_for_range(range)
 3719                                    .skip_while(|c| {
 3720                                        let should_skip = c.is_whitespace();
 3721                                        if should_skip {
 3722                                            index_of_first_non_whitespace += 1;
 3723                                        }
 3724                                        should_skip
 3725                                    })
 3726                                    .take(max_len_of_delimiter)
 3727                                    .collect::<String>();
 3728                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3729                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3730                                })?;
 3731                                let cursor_is_placed_after_comment_marker =
 3732                                    index_of_first_non_whitespace + comment_prefix.len()
 3733                                        <= start_point.column as usize;
 3734                                if cursor_is_placed_after_comment_marker {
 3735                                    Some(comment_prefix.clone())
 3736                                } else {
 3737                                    None
 3738                                }
 3739                            });
 3740                            (comment_delimiter, insert_extra_newline)
 3741                        } else {
 3742                            (None, false)
 3743                        };
 3744
 3745                        let capacity_for_delimiter = comment_delimiter
 3746                            .as_deref()
 3747                            .map(str::len)
 3748                            .unwrap_or_default();
 3749                        let mut new_text =
 3750                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3751                        new_text.push('\n');
 3752                        new_text.extend(indent.chars());
 3753                        if let Some(delimiter) = &comment_delimiter {
 3754                            new_text.push_str(delimiter);
 3755                        }
 3756                        if insert_extra_newline {
 3757                            new_text = new_text.repeat(2);
 3758                        }
 3759
 3760                        let anchor = buffer.anchor_after(end);
 3761                        let new_selection = selection.map(|_| anchor);
 3762                        (
 3763                            (start..end, new_text),
 3764                            (insert_extra_newline, new_selection),
 3765                        )
 3766                    })
 3767                    .unzip()
 3768            };
 3769
 3770            this.edit_with_autoindent(edits, cx);
 3771            let buffer = this.buffer.read(cx).snapshot(cx);
 3772            let new_selections = selection_fixup_info
 3773                .into_iter()
 3774                .map(|(extra_newline_inserted, new_selection)| {
 3775                    let mut cursor = new_selection.end.to_point(&buffer);
 3776                    if extra_newline_inserted {
 3777                        cursor.row -= 1;
 3778                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3779                    }
 3780                    new_selection.map(|_| cursor)
 3781                })
 3782                .collect();
 3783
 3784            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3785                s.select(new_selections)
 3786            });
 3787            this.refresh_inline_completion(true, false, window, cx);
 3788        });
 3789    }
 3790
 3791    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3792        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3793
 3794        let buffer = self.buffer.read(cx);
 3795        let snapshot = buffer.snapshot(cx);
 3796
 3797        let mut edits = Vec::new();
 3798        let mut rows = Vec::new();
 3799
 3800        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3801            let cursor = selection.head();
 3802            let row = cursor.row;
 3803
 3804            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3805
 3806            let newline = "\n".to_string();
 3807            edits.push((start_of_line..start_of_line, newline));
 3808
 3809            rows.push(row + rows_inserted as u32);
 3810        }
 3811
 3812        self.transact(window, cx, |editor, window, cx| {
 3813            editor.edit(edits, cx);
 3814
 3815            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3816                let mut index = 0;
 3817                s.move_cursors_with(|map, _, _| {
 3818                    let row = rows[index];
 3819                    index += 1;
 3820
 3821                    let point = Point::new(row, 0);
 3822                    let boundary = map.next_line_boundary(point).1;
 3823                    let clipped = map.clip_point(boundary, Bias::Left);
 3824
 3825                    (clipped, SelectionGoal::None)
 3826                });
 3827            });
 3828
 3829            let mut indent_edits = Vec::new();
 3830            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3831            for row in rows {
 3832                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3833                for (row, indent) in indents {
 3834                    if indent.len == 0 {
 3835                        continue;
 3836                    }
 3837
 3838                    let text = match indent.kind {
 3839                        IndentKind::Space => " ".repeat(indent.len as usize),
 3840                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3841                    };
 3842                    let point = Point::new(row.0, 0);
 3843                    indent_edits.push((point..point, text));
 3844                }
 3845            }
 3846            editor.edit(indent_edits, cx);
 3847        });
 3848    }
 3849
 3850    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3851        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3852
 3853        let buffer = self.buffer.read(cx);
 3854        let snapshot = buffer.snapshot(cx);
 3855
 3856        let mut edits = Vec::new();
 3857        let mut rows = Vec::new();
 3858        let mut rows_inserted = 0;
 3859
 3860        for selection in self.selections.all_adjusted(cx) {
 3861            let cursor = selection.head();
 3862            let row = cursor.row;
 3863
 3864            let point = Point::new(row + 1, 0);
 3865            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3866
 3867            let newline = "\n".to_string();
 3868            edits.push((start_of_line..start_of_line, newline));
 3869
 3870            rows_inserted += 1;
 3871            rows.push(row + rows_inserted);
 3872        }
 3873
 3874        self.transact(window, cx, |editor, window, cx| {
 3875            editor.edit(edits, cx);
 3876
 3877            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3878                let mut index = 0;
 3879                s.move_cursors_with(|map, _, _| {
 3880                    let row = rows[index];
 3881                    index += 1;
 3882
 3883                    let point = Point::new(row, 0);
 3884                    let boundary = map.next_line_boundary(point).1;
 3885                    let clipped = map.clip_point(boundary, Bias::Left);
 3886
 3887                    (clipped, SelectionGoal::None)
 3888                });
 3889            });
 3890
 3891            let mut indent_edits = Vec::new();
 3892            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3893            for row in rows {
 3894                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3895                for (row, indent) in indents {
 3896                    if indent.len == 0 {
 3897                        continue;
 3898                    }
 3899
 3900                    let text = match indent.kind {
 3901                        IndentKind::Space => " ".repeat(indent.len as usize),
 3902                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3903                    };
 3904                    let point = Point::new(row.0, 0);
 3905                    indent_edits.push((point..point, text));
 3906                }
 3907            }
 3908            editor.edit(indent_edits, cx);
 3909        });
 3910    }
 3911
 3912    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3913        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3914            original_indent_columns: Vec::new(),
 3915        });
 3916        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3917    }
 3918
 3919    fn insert_with_autoindent_mode(
 3920        &mut self,
 3921        text: &str,
 3922        autoindent_mode: Option<AutoindentMode>,
 3923        window: &mut Window,
 3924        cx: &mut Context<Self>,
 3925    ) {
 3926        if self.read_only(cx) {
 3927            return;
 3928        }
 3929
 3930        let text: Arc<str> = text.into();
 3931        self.transact(window, cx, |this, window, cx| {
 3932            let old_selections = this.selections.all_adjusted(cx);
 3933            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3934                let anchors = {
 3935                    let snapshot = buffer.read(cx);
 3936                    old_selections
 3937                        .iter()
 3938                        .map(|s| {
 3939                            let anchor = snapshot.anchor_after(s.head());
 3940                            s.map(|_| anchor)
 3941                        })
 3942                        .collect::<Vec<_>>()
 3943                };
 3944                buffer.edit(
 3945                    old_selections
 3946                        .iter()
 3947                        .map(|s| (s.start..s.end, text.clone())),
 3948                    autoindent_mode,
 3949                    cx,
 3950                );
 3951                anchors
 3952            });
 3953
 3954            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3955                s.select_anchors(selection_anchors);
 3956            });
 3957
 3958            cx.notify();
 3959        });
 3960    }
 3961
 3962    fn trigger_completion_on_input(
 3963        &mut self,
 3964        text: &str,
 3965        trigger_in_words: bool,
 3966        window: &mut Window,
 3967        cx: &mut Context<Self>,
 3968    ) {
 3969        let ignore_completion_provider = self
 3970            .context_menu
 3971            .borrow()
 3972            .as_ref()
 3973            .map(|menu| match menu {
 3974                CodeContextMenu::Completions(completions_menu) => {
 3975                    completions_menu.ignore_completion_provider
 3976                }
 3977                CodeContextMenu::CodeActions(_) => false,
 3978            })
 3979            .unwrap_or(false);
 3980
 3981        if ignore_completion_provider {
 3982            self.show_word_completions(&ShowWordCompletions, window, cx);
 3983        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3984            self.show_completions(
 3985                &ShowCompletions {
 3986                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3987                },
 3988                window,
 3989                cx,
 3990            );
 3991        } else {
 3992            self.hide_context_menu(window, cx);
 3993        }
 3994    }
 3995
 3996    fn is_completion_trigger(
 3997        &self,
 3998        text: &str,
 3999        trigger_in_words: bool,
 4000        cx: &mut Context<Self>,
 4001    ) -> bool {
 4002        let position = self.selections.newest_anchor().head();
 4003        let multibuffer = self.buffer.read(cx);
 4004        let Some(buffer) = position
 4005            .buffer_id
 4006            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 4007        else {
 4008            return false;
 4009        };
 4010
 4011        if let Some(completion_provider) = &self.completion_provider {
 4012            completion_provider.is_completion_trigger(
 4013                &buffer,
 4014                position.text_anchor,
 4015                text,
 4016                trigger_in_words,
 4017                cx,
 4018            )
 4019        } else {
 4020            false
 4021        }
 4022    }
 4023
 4024    /// If any empty selections is touching the start of its innermost containing autoclose
 4025    /// region, expand it to select the brackets.
 4026    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4027        let selections = self.selections.all::<usize>(cx);
 4028        let buffer = self.buffer.read(cx).read(cx);
 4029        let new_selections = self
 4030            .selections_with_autoclose_regions(selections, &buffer)
 4031            .map(|(mut selection, region)| {
 4032                if !selection.is_empty() {
 4033                    return selection;
 4034                }
 4035
 4036                if let Some(region) = region {
 4037                    let mut range = region.range.to_offset(&buffer);
 4038                    if selection.start == range.start && range.start >= region.pair.start.len() {
 4039                        range.start -= region.pair.start.len();
 4040                        if buffer.contains_str_at(range.start, &region.pair.start)
 4041                            && buffer.contains_str_at(range.end, &region.pair.end)
 4042                        {
 4043                            range.end += region.pair.end.len();
 4044                            selection.start = range.start;
 4045                            selection.end = range.end;
 4046
 4047                            return selection;
 4048                        }
 4049                    }
 4050                }
 4051
 4052                let always_treat_brackets_as_autoclosed = buffer
 4053                    .language_settings_at(selection.start, cx)
 4054                    .always_treat_brackets_as_autoclosed;
 4055
 4056                if !always_treat_brackets_as_autoclosed {
 4057                    return selection;
 4058                }
 4059
 4060                if let Some(scope) = buffer.language_scope_at(selection.start) {
 4061                    for (pair, enabled) in scope.brackets() {
 4062                        if !enabled || !pair.close {
 4063                            continue;
 4064                        }
 4065
 4066                        if buffer.contains_str_at(selection.start, &pair.end) {
 4067                            let pair_start_len = pair.start.len();
 4068                            if buffer.contains_str_at(
 4069                                selection.start.saturating_sub(pair_start_len),
 4070                                &pair.start,
 4071                            ) {
 4072                                selection.start -= pair_start_len;
 4073                                selection.end += pair.end.len();
 4074
 4075                                return selection;
 4076                            }
 4077                        }
 4078                    }
 4079                }
 4080
 4081                selection
 4082            })
 4083            .collect();
 4084
 4085        drop(buffer);
 4086        self.change_selections(None, window, cx, |selections| {
 4087            selections.select(new_selections)
 4088        });
 4089    }
 4090
 4091    /// Iterate the given selections, and for each one, find the smallest surrounding
 4092    /// autoclose region. This uses the ordering of the selections and the autoclose
 4093    /// regions to avoid repeated comparisons.
 4094    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 4095        &'a self,
 4096        selections: impl IntoIterator<Item = Selection<D>>,
 4097        buffer: &'a MultiBufferSnapshot,
 4098    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 4099        let mut i = 0;
 4100        let mut regions = self.autoclose_regions.as_slice();
 4101        selections.into_iter().map(move |selection| {
 4102            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 4103
 4104            let mut enclosing = None;
 4105            while let Some(pair_state) = regions.get(i) {
 4106                if pair_state.range.end.to_offset(buffer) < range.start {
 4107                    regions = &regions[i + 1..];
 4108                    i = 0;
 4109                } else if pair_state.range.start.to_offset(buffer) > range.end {
 4110                    break;
 4111                } else {
 4112                    if pair_state.selection_id == selection.id {
 4113                        enclosing = Some(pair_state);
 4114                    }
 4115                    i += 1;
 4116                }
 4117            }
 4118
 4119            (selection, enclosing)
 4120        })
 4121    }
 4122
 4123    /// Remove any autoclose regions that no longer contain their selection.
 4124    fn invalidate_autoclose_regions(
 4125        &mut self,
 4126        mut selections: &[Selection<Anchor>],
 4127        buffer: &MultiBufferSnapshot,
 4128    ) {
 4129        self.autoclose_regions.retain(|state| {
 4130            let mut i = 0;
 4131            while let Some(selection) = selections.get(i) {
 4132                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 4133                    selections = &selections[1..];
 4134                    continue;
 4135                }
 4136                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 4137                    break;
 4138                }
 4139                if selection.id == state.selection_id {
 4140                    return true;
 4141                } else {
 4142                    i += 1;
 4143                }
 4144            }
 4145            false
 4146        });
 4147    }
 4148
 4149    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 4150        let offset = position.to_offset(buffer);
 4151        let (word_range, kind) = buffer.surrounding_word(offset, true);
 4152        if offset > word_range.start && kind == Some(CharKind::Word) {
 4153            Some(
 4154                buffer
 4155                    .text_for_range(word_range.start..offset)
 4156                    .collect::<String>(),
 4157            )
 4158        } else {
 4159            None
 4160        }
 4161    }
 4162
 4163    pub fn toggle_inlay_hints(
 4164        &mut self,
 4165        _: &ToggleInlayHints,
 4166        _: &mut Window,
 4167        cx: &mut Context<Self>,
 4168    ) {
 4169        self.refresh_inlay_hints(
 4170            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 4171            cx,
 4172        );
 4173    }
 4174
 4175    pub fn inlay_hints_enabled(&self) -> bool {
 4176        self.inlay_hint_cache.enabled
 4177    }
 4178
 4179    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4180        if self.semantics_provider.is_none() || !self.mode.is_full() {
 4181            return;
 4182        }
 4183
 4184        let reason_description = reason.description();
 4185        let ignore_debounce = matches!(
 4186            reason,
 4187            InlayHintRefreshReason::SettingsChange(_)
 4188                | InlayHintRefreshReason::Toggle(_)
 4189                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4190                | InlayHintRefreshReason::ModifiersChanged(_)
 4191        );
 4192        let (invalidate_cache, required_languages) = match reason {
 4193            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4194                match self.inlay_hint_cache.modifiers_override(enabled) {
 4195                    Some(enabled) => {
 4196                        if enabled {
 4197                            (InvalidationStrategy::RefreshRequested, None)
 4198                        } else {
 4199                            self.splice_inlays(
 4200                                &self
 4201                                    .visible_inlay_hints(cx)
 4202                                    .iter()
 4203                                    .map(|inlay| inlay.id)
 4204                                    .collect::<Vec<InlayId>>(),
 4205                                Vec::new(),
 4206                                cx,
 4207                            );
 4208                            return;
 4209                        }
 4210                    }
 4211                    None => return,
 4212                }
 4213            }
 4214            InlayHintRefreshReason::Toggle(enabled) => {
 4215                if self.inlay_hint_cache.toggle(enabled) {
 4216                    if enabled {
 4217                        (InvalidationStrategy::RefreshRequested, None)
 4218                    } else {
 4219                        self.splice_inlays(
 4220                            &self
 4221                                .visible_inlay_hints(cx)
 4222                                .iter()
 4223                                .map(|inlay| inlay.id)
 4224                                .collect::<Vec<InlayId>>(),
 4225                            Vec::new(),
 4226                            cx,
 4227                        );
 4228                        return;
 4229                    }
 4230                } else {
 4231                    return;
 4232                }
 4233            }
 4234            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4235                match self.inlay_hint_cache.update_settings(
 4236                    &self.buffer,
 4237                    new_settings,
 4238                    self.visible_inlay_hints(cx),
 4239                    cx,
 4240                ) {
 4241                    ControlFlow::Break(Some(InlaySplice {
 4242                        to_remove,
 4243                        to_insert,
 4244                    })) => {
 4245                        self.splice_inlays(&to_remove, to_insert, cx);
 4246                        return;
 4247                    }
 4248                    ControlFlow::Break(None) => return,
 4249                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4250                }
 4251            }
 4252            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4253                if let Some(InlaySplice {
 4254                    to_remove,
 4255                    to_insert,
 4256                }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
 4257                {
 4258                    self.splice_inlays(&to_remove, to_insert, cx);
 4259                }
 4260                self.display_map.update(cx, |display_map, _| {
 4261                    display_map.remove_inlays_for_excerpts(&excerpts_removed)
 4262                });
 4263                return;
 4264            }
 4265            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4266            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4267                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4268            }
 4269            InlayHintRefreshReason::RefreshRequested => {
 4270                (InvalidationStrategy::RefreshRequested, None)
 4271            }
 4272        };
 4273
 4274        if let Some(InlaySplice {
 4275            to_remove,
 4276            to_insert,
 4277        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4278            reason_description,
 4279            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4280            invalidate_cache,
 4281            ignore_debounce,
 4282            cx,
 4283        ) {
 4284            self.splice_inlays(&to_remove, to_insert, cx);
 4285        }
 4286    }
 4287
 4288    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4289        self.display_map
 4290            .read(cx)
 4291            .current_inlays()
 4292            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4293            .cloned()
 4294            .collect()
 4295    }
 4296
 4297    pub fn excerpts_for_inlay_hints_query(
 4298        &self,
 4299        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4300        cx: &mut Context<Editor>,
 4301    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4302        let Some(project) = self.project.as_ref() else {
 4303            return HashMap::default();
 4304        };
 4305        let project = project.read(cx);
 4306        let multi_buffer = self.buffer().read(cx);
 4307        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4308        let multi_buffer_visible_start = self
 4309            .scroll_manager
 4310            .anchor()
 4311            .anchor
 4312            .to_point(&multi_buffer_snapshot);
 4313        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4314            multi_buffer_visible_start
 4315                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4316            Bias::Left,
 4317        );
 4318        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4319        multi_buffer_snapshot
 4320            .range_to_buffer_ranges(multi_buffer_visible_range)
 4321            .into_iter()
 4322            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4323            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4324                let buffer_file = project::File::from_dyn(buffer.file())?;
 4325                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4326                let worktree_entry = buffer_worktree
 4327                    .read(cx)
 4328                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4329                if worktree_entry.is_ignored {
 4330                    return None;
 4331                }
 4332
 4333                let language = buffer.language()?;
 4334                if let Some(restrict_to_languages) = restrict_to_languages {
 4335                    if !restrict_to_languages.contains(language) {
 4336                        return None;
 4337                    }
 4338                }
 4339                Some((
 4340                    excerpt_id,
 4341                    (
 4342                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4343                        buffer.version().clone(),
 4344                        excerpt_visible_range,
 4345                    ),
 4346                ))
 4347            })
 4348            .collect()
 4349    }
 4350
 4351    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4352        TextLayoutDetails {
 4353            text_system: window.text_system().clone(),
 4354            editor_style: self.style.clone().unwrap(),
 4355            rem_size: window.rem_size(),
 4356            scroll_anchor: self.scroll_manager.anchor(),
 4357            visible_rows: self.visible_line_count(),
 4358            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4359        }
 4360    }
 4361
 4362    pub fn splice_inlays(
 4363        &self,
 4364        to_remove: &[InlayId],
 4365        to_insert: Vec<Inlay>,
 4366        cx: &mut Context<Self>,
 4367    ) {
 4368        self.display_map.update(cx, |display_map, cx| {
 4369            display_map.splice_inlays(to_remove, to_insert, cx)
 4370        });
 4371        cx.notify();
 4372    }
 4373
 4374    fn trigger_on_type_formatting(
 4375        &self,
 4376        input: String,
 4377        window: &mut Window,
 4378        cx: &mut Context<Self>,
 4379    ) -> Option<Task<Result<()>>> {
 4380        if input.len() != 1 {
 4381            return None;
 4382        }
 4383
 4384        let project = self.project.as_ref()?;
 4385        let position = self.selections.newest_anchor().head();
 4386        let (buffer, buffer_position) = self
 4387            .buffer
 4388            .read(cx)
 4389            .text_anchor_for_position(position, cx)?;
 4390
 4391        let settings = language_settings::language_settings(
 4392            buffer
 4393                .read(cx)
 4394                .language_at(buffer_position)
 4395                .map(|l| l.name()),
 4396            buffer.read(cx).file(),
 4397            cx,
 4398        );
 4399        if !settings.use_on_type_format {
 4400            return None;
 4401        }
 4402
 4403        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4404        // hence we do LSP request & edit on host side only — add formats to host's history.
 4405        let push_to_lsp_host_history = true;
 4406        // If this is not the host, append its history with new edits.
 4407        let push_to_client_history = project.read(cx).is_via_collab();
 4408
 4409        let on_type_formatting = project.update(cx, |project, cx| {
 4410            project.on_type_format(
 4411                buffer.clone(),
 4412                buffer_position,
 4413                input,
 4414                push_to_lsp_host_history,
 4415                cx,
 4416            )
 4417        });
 4418        Some(cx.spawn_in(window, async move |editor, cx| {
 4419            if let Some(transaction) = on_type_formatting.await? {
 4420                if push_to_client_history {
 4421                    buffer
 4422                        .update(cx, |buffer, _| {
 4423                            buffer.push_transaction(transaction, Instant::now());
 4424                            buffer.finalize_last_transaction();
 4425                        })
 4426                        .ok();
 4427                }
 4428                editor.update(cx, |editor, cx| {
 4429                    editor.refresh_document_highlights(cx);
 4430                })?;
 4431            }
 4432            Ok(())
 4433        }))
 4434    }
 4435
 4436    pub fn show_word_completions(
 4437        &mut self,
 4438        _: &ShowWordCompletions,
 4439        window: &mut Window,
 4440        cx: &mut Context<Self>,
 4441    ) {
 4442        self.open_completions_menu(true, None, window, cx);
 4443    }
 4444
 4445    pub fn show_completions(
 4446        &mut self,
 4447        options: &ShowCompletions,
 4448        window: &mut Window,
 4449        cx: &mut Context<Self>,
 4450    ) {
 4451        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4452    }
 4453
 4454    fn open_completions_menu(
 4455        &mut self,
 4456        ignore_completion_provider: bool,
 4457        trigger: Option<&str>,
 4458        window: &mut Window,
 4459        cx: &mut Context<Self>,
 4460    ) {
 4461        if self.pending_rename.is_some() {
 4462            return;
 4463        }
 4464        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4465            return;
 4466        }
 4467
 4468        let position = self.selections.newest_anchor().head();
 4469        if position.diff_base_anchor.is_some() {
 4470            return;
 4471        }
 4472        let (buffer, buffer_position) =
 4473            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4474                output
 4475            } else {
 4476                return;
 4477            };
 4478        let buffer_snapshot = buffer.read(cx).snapshot();
 4479        let show_completion_documentation = buffer_snapshot
 4480            .settings_at(buffer_position, cx)
 4481            .show_completion_documentation;
 4482
 4483        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4484
 4485        let trigger_kind = match trigger {
 4486            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4487                CompletionTriggerKind::TRIGGER_CHARACTER
 4488            }
 4489            _ => CompletionTriggerKind::INVOKED,
 4490        };
 4491        let completion_context = CompletionContext {
 4492            trigger_character: trigger.and_then(|trigger| {
 4493                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4494                    Some(String::from(trigger))
 4495                } else {
 4496                    None
 4497                }
 4498            }),
 4499            trigger_kind,
 4500        };
 4501
 4502        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4503        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4504            let word_to_exclude = buffer_snapshot
 4505                .text_for_range(old_range.clone())
 4506                .collect::<String>();
 4507            (
 4508                buffer_snapshot.anchor_before(old_range.start)
 4509                    ..buffer_snapshot.anchor_after(old_range.end),
 4510                Some(word_to_exclude),
 4511            )
 4512        } else {
 4513            (buffer_position..buffer_position, None)
 4514        };
 4515
 4516        let completion_settings = language_settings(
 4517            buffer_snapshot
 4518                .language_at(buffer_position)
 4519                .map(|language| language.name()),
 4520            buffer_snapshot.file(),
 4521            cx,
 4522        )
 4523        .completions;
 4524
 4525        // The document can be large, so stay in reasonable bounds when searching for words,
 4526        // otherwise completion pop-up might be slow to appear.
 4527        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4528        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4529        let min_word_search = buffer_snapshot.clip_point(
 4530            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4531            Bias::Left,
 4532        );
 4533        let max_word_search = buffer_snapshot.clip_point(
 4534            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4535            Bias::Right,
 4536        );
 4537        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4538            ..buffer_snapshot.point_to_offset(max_word_search);
 4539
 4540        let provider = self
 4541            .completion_provider
 4542            .as_ref()
 4543            .filter(|_| !ignore_completion_provider);
 4544        let skip_digits = query
 4545            .as_ref()
 4546            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4547
 4548        let (mut words, provided_completions) = match provider {
 4549            Some(provider) => {
 4550                let completions = provider.completions(
 4551                    position.excerpt_id,
 4552                    &buffer,
 4553                    buffer_position,
 4554                    completion_context,
 4555                    window,
 4556                    cx,
 4557                );
 4558
 4559                let words = match completion_settings.words {
 4560                    WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
 4561                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4562                        .background_spawn(async move {
 4563                            buffer_snapshot.words_in_range(WordsQuery {
 4564                                fuzzy_contents: None,
 4565                                range: word_search_range,
 4566                                skip_digits,
 4567                            })
 4568                        }),
 4569                };
 4570
 4571                (words, completions)
 4572            }
 4573            None => (
 4574                cx.background_spawn(async move {
 4575                    buffer_snapshot.words_in_range(WordsQuery {
 4576                        fuzzy_contents: None,
 4577                        range: word_search_range,
 4578                        skip_digits,
 4579                    })
 4580                }),
 4581                Task::ready(Ok(None)),
 4582            ),
 4583        };
 4584
 4585        let sort_completions = provider
 4586            .as_ref()
 4587            .map_or(false, |provider| provider.sort_completions());
 4588
 4589        let filter_completions = provider
 4590            .as_ref()
 4591            .map_or(true, |provider| provider.filter_completions());
 4592
 4593        let id = post_inc(&mut self.next_completion_id);
 4594        let task = cx.spawn_in(window, async move |editor, cx| {
 4595            async move {
 4596                editor.update(cx, |this, _| {
 4597                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4598                })?;
 4599
 4600                let mut completions = Vec::new();
 4601                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4602                    completions.extend(provided_completions);
 4603                    if completion_settings.words == WordsCompletionMode::Fallback {
 4604                        words = Task::ready(BTreeMap::default());
 4605                    }
 4606                }
 4607
 4608                let mut words = words.await;
 4609                if let Some(word_to_exclude) = &word_to_exclude {
 4610                    words.remove(word_to_exclude);
 4611                }
 4612                for lsp_completion in &completions {
 4613                    words.remove(&lsp_completion.new_text);
 4614                }
 4615                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4616                    replace_range: old_range.clone(),
 4617                    new_text: word.clone(),
 4618                    label: CodeLabel::plain(word, None),
 4619                    icon_path: None,
 4620                    documentation: None,
 4621                    source: CompletionSource::BufferWord {
 4622                        word_range,
 4623                        resolved: false,
 4624                    },
 4625                    insert_text_mode: Some(InsertTextMode::AS_IS),
 4626                    confirm: None,
 4627                }));
 4628
 4629                let menu = if completions.is_empty() {
 4630                    None
 4631                } else {
 4632                    let mut menu = CompletionsMenu::new(
 4633                        id,
 4634                        sort_completions,
 4635                        show_completion_documentation,
 4636                        ignore_completion_provider,
 4637                        position,
 4638                        buffer.clone(),
 4639                        completions.into(),
 4640                    );
 4641
 4642                    menu.filter(
 4643                        if filter_completions {
 4644                            query.as_deref()
 4645                        } else {
 4646                            None
 4647                        },
 4648                        cx.background_executor().clone(),
 4649                    )
 4650                    .await;
 4651
 4652                    menu.visible().then_some(menu)
 4653                };
 4654
 4655                editor.update_in(cx, |editor, window, cx| {
 4656                    match editor.context_menu.borrow().as_ref() {
 4657                        None => {}
 4658                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4659                            if prev_menu.id > id {
 4660                                return;
 4661                            }
 4662                        }
 4663                        _ => return,
 4664                    }
 4665
 4666                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4667                        let mut menu = menu.unwrap();
 4668                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4669
 4670                        *editor.context_menu.borrow_mut() =
 4671                            Some(CodeContextMenu::Completions(menu));
 4672
 4673                        if editor.show_edit_predictions_in_menu() {
 4674                            editor.update_visible_inline_completion(window, cx);
 4675                        } else {
 4676                            editor.discard_inline_completion(false, cx);
 4677                        }
 4678
 4679                        cx.notify();
 4680                    } else if editor.completion_tasks.len() <= 1 {
 4681                        // If there are no more completion tasks and the last menu was
 4682                        // empty, we should hide it.
 4683                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4684                        // If it was already hidden and we don't show inline
 4685                        // completions in the menu, we should also show the
 4686                        // inline-completion when available.
 4687                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4688                            editor.update_visible_inline_completion(window, cx);
 4689                        }
 4690                    }
 4691                })?;
 4692
 4693                anyhow::Ok(())
 4694            }
 4695            .log_err()
 4696            .await
 4697        });
 4698
 4699        self.completion_tasks.push((id, task));
 4700    }
 4701
 4702    #[cfg(feature = "test-support")]
 4703    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4704        let menu = self.context_menu.borrow();
 4705        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4706            let completions = menu.completions.borrow();
 4707            Some(completions.to_vec())
 4708        } else {
 4709            None
 4710        }
 4711    }
 4712
 4713    pub fn confirm_completion(
 4714        &mut self,
 4715        action: &ConfirmCompletion,
 4716        window: &mut Window,
 4717        cx: &mut Context<Self>,
 4718    ) -> Option<Task<Result<()>>> {
 4719        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4720        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4721    }
 4722
 4723    pub fn confirm_completion_insert(
 4724        &mut self,
 4725        _: &ConfirmCompletionInsert,
 4726        window: &mut Window,
 4727        cx: &mut Context<Self>,
 4728    ) -> Option<Task<Result<()>>> {
 4729        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4730        self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
 4731    }
 4732
 4733    pub fn confirm_completion_replace(
 4734        &mut self,
 4735        _: &ConfirmCompletionReplace,
 4736        window: &mut Window,
 4737        cx: &mut Context<Self>,
 4738    ) -> Option<Task<Result<()>>> {
 4739        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4740        self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
 4741    }
 4742
 4743    pub fn compose_completion(
 4744        &mut self,
 4745        action: &ComposeCompletion,
 4746        window: &mut Window,
 4747        cx: &mut Context<Self>,
 4748    ) -> Option<Task<Result<()>>> {
 4749        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4750        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4751    }
 4752
 4753    fn do_completion(
 4754        &mut self,
 4755        item_ix: Option<usize>,
 4756        intent: CompletionIntent,
 4757        window: &mut Window,
 4758        cx: &mut Context<Editor>,
 4759    ) -> Option<Task<Result<()>>> {
 4760        use language::ToOffset as _;
 4761
 4762        let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
 4763        else {
 4764            return None;
 4765        };
 4766
 4767        let candidate_id = {
 4768            let entries = completions_menu.entries.borrow();
 4769            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4770            if self.show_edit_predictions_in_menu() {
 4771                self.discard_inline_completion(true, cx);
 4772            }
 4773            mat.candidate_id
 4774        };
 4775
 4776        let buffer_handle = completions_menu.buffer;
 4777        let completion = completions_menu
 4778            .completions
 4779            .borrow()
 4780            .get(candidate_id)?
 4781            .clone();
 4782        cx.stop_propagation();
 4783
 4784        let snippet;
 4785        let new_text;
 4786        if completion.is_snippet() {
 4787            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4788            new_text = snippet.as_ref().unwrap().text.clone();
 4789        } else {
 4790            snippet = None;
 4791            new_text = completion.new_text.clone();
 4792        };
 4793
 4794        let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
 4795        let buffer = buffer_handle.read(cx);
 4796        let snapshot = self.buffer.read(cx).snapshot(cx);
 4797        let replace_range_multibuffer = {
 4798            let excerpt = snapshot
 4799                .excerpt_containing(self.selections.newest_anchor().range())
 4800                .unwrap();
 4801            let multibuffer_anchor = snapshot
 4802                .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
 4803                .unwrap()
 4804                ..snapshot
 4805                    .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
 4806                    .unwrap();
 4807            multibuffer_anchor.start.to_offset(&snapshot)
 4808                ..multibuffer_anchor.end.to_offset(&snapshot)
 4809        };
 4810        let newest_anchor = self.selections.newest_anchor();
 4811        if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
 4812            return None;
 4813        }
 4814
 4815        let old_text = buffer
 4816            .text_for_range(replace_range.clone())
 4817            .collect::<String>();
 4818        let lookbehind = newest_anchor
 4819            .start
 4820            .text_anchor
 4821            .to_offset(buffer)
 4822            .saturating_sub(replace_range.start);
 4823        let lookahead = replace_range
 4824            .end
 4825            .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
 4826        let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
 4827        let suffix = &old_text[lookbehind.min(old_text.len())..];
 4828
 4829        let selections = self.selections.all::<usize>(cx);
 4830        let mut ranges = Vec::new();
 4831        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4832
 4833        for selection in &selections {
 4834            let range = if selection.id == newest_anchor.id {
 4835                replace_range_multibuffer.clone()
 4836            } else {
 4837                let mut range = selection.range();
 4838
 4839                // if prefix is present, don't duplicate it
 4840                if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
 4841                    range.start = range.start.saturating_sub(lookbehind);
 4842
 4843                    // if suffix is also present, mimic the newest cursor and replace it
 4844                    if selection.id != newest_anchor.id
 4845                        && snapshot.contains_str_at(range.end, suffix)
 4846                    {
 4847                        range.end += lookahead;
 4848                    }
 4849                }
 4850                range
 4851            };
 4852
 4853            ranges.push(range);
 4854
 4855            if !self.linked_edit_ranges.is_empty() {
 4856                let start_anchor = snapshot.anchor_before(selection.head());
 4857                let end_anchor = snapshot.anchor_after(selection.tail());
 4858                if let Some(ranges) = self
 4859                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4860                {
 4861                    for (buffer, edits) in ranges {
 4862                        linked_edits
 4863                            .entry(buffer.clone())
 4864                            .or_default()
 4865                            .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
 4866                    }
 4867                }
 4868            }
 4869        }
 4870
 4871        cx.emit(EditorEvent::InputHandled {
 4872            utf16_range_to_replace: None,
 4873            text: new_text.clone().into(),
 4874        });
 4875
 4876        self.transact(window, cx, |this, window, cx| {
 4877            if let Some(mut snippet) = snippet {
 4878                snippet.text = new_text.to_string();
 4879                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4880            } else {
 4881                this.buffer.update(cx, |buffer, cx| {
 4882                    let auto_indent = match completion.insert_text_mode {
 4883                        Some(InsertTextMode::AS_IS) => None,
 4884                        _ => this.autoindent_mode.clone(),
 4885                    };
 4886                    let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
 4887                    buffer.edit(edits, auto_indent, cx);
 4888                });
 4889            }
 4890            for (buffer, edits) in linked_edits {
 4891                buffer.update(cx, |buffer, cx| {
 4892                    let snapshot = buffer.snapshot();
 4893                    let edits = edits
 4894                        .into_iter()
 4895                        .map(|(range, text)| {
 4896                            use text::ToPoint as TP;
 4897                            let end_point = TP::to_point(&range.end, &snapshot);
 4898                            let start_point = TP::to_point(&range.start, &snapshot);
 4899                            (start_point..end_point, text)
 4900                        })
 4901                        .sorted_by_key(|(range, _)| range.start);
 4902                    buffer.edit(edits, None, cx);
 4903                })
 4904            }
 4905
 4906            this.refresh_inline_completion(true, false, window, cx);
 4907        });
 4908
 4909        let show_new_completions_on_confirm = completion
 4910            .confirm
 4911            .as_ref()
 4912            .map_or(false, |confirm| confirm(intent, window, cx));
 4913        if show_new_completions_on_confirm {
 4914            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4915        }
 4916
 4917        let provider = self.completion_provider.as_ref()?;
 4918        drop(completion);
 4919        let apply_edits = provider.apply_additional_edits_for_completion(
 4920            buffer_handle,
 4921            completions_menu.completions.clone(),
 4922            candidate_id,
 4923            true,
 4924            cx,
 4925        );
 4926
 4927        let editor_settings = EditorSettings::get_global(cx);
 4928        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4929            // After the code completion is finished, users often want to know what signatures are needed.
 4930            // so we should automatically call signature_help
 4931            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4932        }
 4933
 4934        Some(cx.foreground_executor().spawn(async move {
 4935            apply_edits.await?;
 4936            Ok(())
 4937        }))
 4938    }
 4939
 4940    pub fn toggle_code_actions(
 4941        &mut self,
 4942        action: &ToggleCodeActions,
 4943        window: &mut Window,
 4944        cx: &mut Context<Self>,
 4945    ) {
 4946        let mut context_menu = self.context_menu.borrow_mut();
 4947        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4948            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4949                // Toggle if we're selecting the same one
 4950                *context_menu = None;
 4951                cx.notify();
 4952                return;
 4953            } else {
 4954                // Otherwise, clear it and start a new one
 4955                *context_menu = None;
 4956                cx.notify();
 4957            }
 4958        }
 4959        drop(context_menu);
 4960        let snapshot = self.snapshot(window, cx);
 4961        let deployed_from_indicator = action.deployed_from_indicator;
 4962        let mut task = self.code_actions_task.take();
 4963        let action = action.clone();
 4964        cx.spawn_in(window, async move |editor, cx| {
 4965            while let Some(prev_task) = task {
 4966                prev_task.await.log_err();
 4967                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4968            }
 4969
 4970            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4971                if editor.focus_handle.is_focused(window) {
 4972                    let multibuffer_point = action
 4973                        .deployed_from_indicator
 4974                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4975                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4976                    let (buffer, buffer_row) = snapshot
 4977                        .buffer_snapshot
 4978                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4979                        .and_then(|(buffer_snapshot, range)| {
 4980                            editor
 4981                                .buffer
 4982                                .read(cx)
 4983                                .buffer(buffer_snapshot.remote_id())
 4984                                .map(|buffer| (buffer, range.start.row))
 4985                        })?;
 4986                    let (_, code_actions) = editor
 4987                        .available_code_actions
 4988                        .clone()
 4989                        .and_then(|(location, code_actions)| {
 4990                            let snapshot = location.buffer.read(cx).snapshot();
 4991                            let point_range = location.range.to_point(&snapshot);
 4992                            let point_range = point_range.start.row..=point_range.end.row;
 4993                            if point_range.contains(&buffer_row) {
 4994                                Some((location, code_actions))
 4995                            } else {
 4996                                None
 4997                            }
 4998                        })
 4999                        .unzip();
 5000                    let buffer_id = buffer.read(cx).remote_id();
 5001                    let tasks = editor
 5002                        .tasks
 5003                        .get(&(buffer_id, buffer_row))
 5004                        .map(|t| Arc::new(t.to_owned()));
 5005                    if tasks.is_none() && code_actions.is_none() {
 5006                        return None;
 5007                    }
 5008
 5009                    editor.completion_tasks.clear();
 5010                    editor.discard_inline_completion(false, cx);
 5011                    let task_context =
 5012                        tasks
 5013                            .as_ref()
 5014                            .zip(editor.project.clone())
 5015                            .map(|(tasks, project)| {
 5016                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 5017                            });
 5018
 5019                    let debugger_flag = cx.has_flag::<Debugger>();
 5020
 5021                    Some(cx.spawn_in(window, async move |editor, cx| {
 5022                        let task_context = match task_context {
 5023                            Some(task_context) => task_context.await,
 5024                            None => None,
 5025                        };
 5026                        let resolved_tasks =
 5027                            tasks
 5028                                .zip(task_context)
 5029                                .map(|(tasks, task_context)| ResolvedTasks {
 5030                                    templates: tasks.resolve(&task_context).collect(),
 5031                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 5032                                        multibuffer_point.row,
 5033                                        tasks.column,
 5034                                    )),
 5035                                });
 5036                        let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
 5037                            tasks
 5038                                .templates
 5039                                .iter()
 5040                                .filter(|task| {
 5041                                    if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 5042                                        debugger_flag
 5043                                    } else {
 5044                                        true
 5045                                    }
 5046                                })
 5047                                .count()
 5048                                == 1
 5049                        }) && code_actions
 5050                            .as_ref()
 5051                            .map_or(true, |actions| actions.is_empty());
 5052                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 5053                            *editor.context_menu.borrow_mut() =
 5054                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 5055                                    buffer,
 5056                                    actions: CodeActionContents::new(
 5057                                        resolved_tasks,
 5058                                        code_actions,
 5059                                        cx,
 5060                                    ),
 5061                                    selected_item: Default::default(),
 5062                                    scroll_handle: UniformListScrollHandle::default(),
 5063                                    deployed_from_indicator,
 5064                                }));
 5065                            if spawn_straight_away {
 5066                                if let Some(task) = editor.confirm_code_action(
 5067                                    &ConfirmCodeAction { item_ix: Some(0) },
 5068                                    window,
 5069                                    cx,
 5070                                ) {
 5071                                    cx.notify();
 5072                                    return task;
 5073                                }
 5074                            }
 5075                            cx.notify();
 5076                            Task::ready(Ok(()))
 5077                        }) {
 5078                            task.await
 5079                        } else {
 5080                            Ok(())
 5081                        }
 5082                    }))
 5083                } else {
 5084                    Some(Task::ready(Ok(())))
 5085                }
 5086            })?;
 5087            if let Some(task) = spawned_test_task {
 5088                task.await?;
 5089            }
 5090
 5091            Ok::<_, anyhow::Error>(())
 5092        })
 5093        .detach_and_log_err(cx);
 5094    }
 5095
 5096    pub fn confirm_code_action(
 5097        &mut self,
 5098        action: &ConfirmCodeAction,
 5099        window: &mut Window,
 5100        cx: &mut Context<Self>,
 5101    ) -> Option<Task<Result<()>>> {
 5102        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 5103
 5104        let actions_menu =
 5105            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 5106                menu
 5107            } else {
 5108                return None;
 5109            };
 5110
 5111        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 5112        let action = actions_menu.actions.get(action_ix)?;
 5113        let title = action.label();
 5114        let buffer = actions_menu.buffer;
 5115        let workspace = self.workspace()?;
 5116
 5117        match action {
 5118            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 5119                match resolved_task.task_type() {
 5120                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 5121                        workspace.schedule_resolved_task(
 5122                            task_source_kind,
 5123                            resolved_task,
 5124                            false,
 5125                            window,
 5126                            cx,
 5127                        );
 5128
 5129                        Some(Task::ready(Ok(())))
 5130                    }),
 5131                    task::TaskType::Debug(_) => {
 5132                        workspace.update(cx, |workspace, cx| {
 5133                            workspace.schedule_debug_task(resolved_task, window, cx);
 5134                        });
 5135                        Some(Task::ready(Ok(())))
 5136                    }
 5137                }
 5138            }
 5139            CodeActionsItem::CodeAction {
 5140                excerpt_id,
 5141                action,
 5142                provider,
 5143            } => {
 5144                let apply_code_action =
 5145                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 5146                let workspace = workspace.downgrade();
 5147                Some(cx.spawn_in(window, async move |editor, cx| {
 5148                    let project_transaction = apply_code_action.await?;
 5149                    Self::open_project_transaction(
 5150                        &editor,
 5151                        workspace,
 5152                        project_transaction,
 5153                        title,
 5154                        cx,
 5155                    )
 5156                    .await
 5157                }))
 5158            }
 5159        }
 5160    }
 5161
 5162    pub async fn open_project_transaction(
 5163        this: &WeakEntity<Editor>,
 5164        workspace: WeakEntity<Workspace>,
 5165        transaction: ProjectTransaction,
 5166        title: String,
 5167        cx: &mut AsyncWindowContext,
 5168    ) -> Result<()> {
 5169        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 5170        cx.update(|_, cx| {
 5171            entries.sort_unstable_by_key(|(buffer, _)| {
 5172                buffer.read(cx).file().map(|f| f.path().clone())
 5173            });
 5174        })?;
 5175
 5176        // If the project transaction's edits are all contained within this editor, then
 5177        // avoid opening a new editor to display them.
 5178
 5179        if let Some((buffer, transaction)) = entries.first() {
 5180            if entries.len() == 1 {
 5181                let excerpt = this.update(cx, |editor, cx| {
 5182                    editor
 5183                        .buffer()
 5184                        .read(cx)
 5185                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5186                })?;
 5187                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5188                    if excerpted_buffer == *buffer {
 5189                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5190                            let excerpt_range = excerpt_range.to_offset(buffer);
 5191                            buffer
 5192                                .edited_ranges_for_transaction::<usize>(transaction)
 5193                                .all(|range| {
 5194                                    excerpt_range.start <= range.start
 5195                                        && excerpt_range.end >= range.end
 5196                                })
 5197                        })?;
 5198
 5199                        if all_edits_within_excerpt {
 5200                            return Ok(());
 5201                        }
 5202                    }
 5203                }
 5204            }
 5205        } else {
 5206            return Ok(());
 5207        }
 5208
 5209        let mut ranges_to_highlight = Vec::new();
 5210        let excerpt_buffer = cx.new(|cx| {
 5211            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5212            for (buffer_handle, transaction) in &entries {
 5213                let edited_ranges = buffer_handle
 5214                    .read(cx)
 5215                    .edited_ranges_for_transaction::<Point>(transaction)
 5216                    .collect::<Vec<_>>();
 5217                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5218                    PathKey::for_buffer(buffer_handle, cx),
 5219                    buffer_handle.clone(),
 5220                    edited_ranges,
 5221                    DEFAULT_MULTIBUFFER_CONTEXT,
 5222                    cx,
 5223                );
 5224
 5225                ranges_to_highlight.extend(ranges);
 5226            }
 5227            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5228            multibuffer
 5229        })?;
 5230
 5231        workspace.update_in(cx, |workspace, window, cx| {
 5232            let project = workspace.project().clone();
 5233            let editor =
 5234                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5235            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5236            editor.update(cx, |editor, cx| {
 5237                editor.highlight_background::<Self>(
 5238                    &ranges_to_highlight,
 5239                    |theme| theme.editor_highlighted_line_background,
 5240                    cx,
 5241                );
 5242            });
 5243        })?;
 5244
 5245        Ok(())
 5246    }
 5247
 5248    pub fn clear_code_action_providers(&mut self) {
 5249        self.code_action_providers.clear();
 5250        self.available_code_actions.take();
 5251    }
 5252
 5253    pub fn add_code_action_provider(
 5254        &mut self,
 5255        provider: Rc<dyn CodeActionProvider>,
 5256        window: &mut Window,
 5257        cx: &mut Context<Self>,
 5258    ) {
 5259        if self
 5260            .code_action_providers
 5261            .iter()
 5262            .any(|existing_provider| existing_provider.id() == provider.id())
 5263        {
 5264            return;
 5265        }
 5266
 5267        self.code_action_providers.push(provider);
 5268        self.refresh_code_actions(window, cx);
 5269    }
 5270
 5271    pub fn remove_code_action_provider(
 5272        &mut self,
 5273        id: Arc<str>,
 5274        window: &mut Window,
 5275        cx: &mut Context<Self>,
 5276    ) {
 5277        self.code_action_providers
 5278            .retain(|provider| provider.id() != id);
 5279        self.refresh_code_actions(window, cx);
 5280    }
 5281
 5282    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5283        let newest_selection = self.selections.newest_anchor().clone();
 5284        let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
 5285        let buffer = self.buffer.read(cx);
 5286        if newest_selection.head().diff_base_anchor.is_some() {
 5287            return None;
 5288        }
 5289        let (start_buffer, start) =
 5290            buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
 5291        let (end_buffer, end) =
 5292            buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
 5293        if start_buffer != end_buffer {
 5294            return None;
 5295        }
 5296
 5297        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5298            cx.background_executor()
 5299                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5300                .await;
 5301
 5302            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5303                let providers = this.code_action_providers.clone();
 5304                let tasks = this
 5305                    .code_action_providers
 5306                    .iter()
 5307                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5308                    .collect::<Vec<_>>();
 5309                (providers, tasks)
 5310            })?;
 5311
 5312            let mut actions = Vec::new();
 5313            for (provider, provider_actions) in
 5314                providers.into_iter().zip(future::join_all(tasks).await)
 5315            {
 5316                if let Some(provider_actions) = provider_actions.log_err() {
 5317                    actions.extend(provider_actions.into_iter().map(|action| {
 5318                        AvailableCodeAction {
 5319                            excerpt_id: newest_selection.start.excerpt_id,
 5320                            action,
 5321                            provider: provider.clone(),
 5322                        }
 5323                    }));
 5324                }
 5325            }
 5326
 5327            this.update(cx, |this, cx| {
 5328                this.available_code_actions = if actions.is_empty() {
 5329                    None
 5330                } else {
 5331                    Some((
 5332                        Location {
 5333                            buffer: start_buffer,
 5334                            range: start..end,
 5335                        },
 5336                        actions.into(),
 5337                    ))
 5338                };
 5339                cx.notify();
 5340            })
 5341        }));
 5342        None
 5343    }
 5344
 5345    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5346        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5347            self.show_git_blame_inline = false;
 5348
 5349            self.show_git_blame_inline_delay_task =
 5350                Some(cx.spawn_in(window, async move |this, cx| {
 5351                    cx.background_executor().timer(delay).await;
 5352
 5353                    this.update(cx, |this, cx| {
 5354                        this.show_git_blame_inline = true;
 5355                        cx.notify();
 5356                    })
 5357                    .log_err();
 5358                }));
 5359        }
 5360    }
 5361
 5362    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5363        if self.pending_rename.is_some() {
 5364            return None;
 5365        }
 5366
 5367        let provider = self.semantics_provider.clone()?;
 5368        let buffer = self.buffer.read(cx);
 5369        let newest_selection = self.selections.newest_anchor().clone();
 5370        let cursor_position = newest_selection.head();
 5371        let (cursor_buffer, cursor_buffer_position) =
 5372            buffer.text_anchor_for_position(cursor_position, cx)?;
 5373        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5374        if cursor_buffer != tail_buffer {
 5375            return None;
 5376        }
 5377        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5378        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5379            cx.background_executor()
 5380                .timer(Duration::from_millis(debounce))
 5381                .await;
 5382
 5383            let highlights = if let Some(highlights) = cx
 5384                .update(|cx| {
 5385                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5386                })
 5387                .ok()
 5388                .flatten()
 5389            {
 5390                highlights.await.log_err()
 5391            } else {
 5392                None
 5393            };
 5394
 5395            if let Some(highlights) = highlights {
 5396                this.update(cx, |this, cx| {
 5397                    if this.pending_rename.is_some() {
 5398                        return;
 5399                    }
 5400
 5401                    let buffer_id = cursor_position.buffer_id;
 5402                    let buffer = this.buffer.read(cx);
 5403                    if !buffer
 5404                        .text_anchor_for_position(cursor_position, cx)
 5405                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5406                    {
 5407                        return;
 5408                    }
 5409
 5410                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5411                    let mut write_ranges = Vec::new();
 5412                    let mut read_ranges = Vec::new();
 5413                    for highlight in highlights {
 5414                        for (excerpt_id, excerpt_range) in
 5415                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5416                        {
 5417                            let start = highlight
 5418                                .range
 5419                                .start
 5420                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5421                            let end = highlight
 5422                                .range
 5423                                .end
 5424                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5425                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5426                                continue;
 5427                            }
 5428
 5429                            let range = Anchor {
 5430                                buffer_id,
 5431                                excerpt_id,
 5432                                text_anchor: start,
 5433                                diff_base_anchor: None,
 5434                            }..Anchor {
 5435                                buffer_id,
 5436                                excerpt_id,
 5437                                text_anchor: end,
 5438                                diff_base_anchor: None,
 5439                            };
 5440                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5441                                write_ranges.push(range);
 5442                            } else {
 5443                                read_ranges.push(range);
 5444                            }
 5445                        }
 5446                    }
 5447
 5448                    this.highlight_background::<DocumentHighlightRead>(
 5449                        &read_ranges,
 5450                        |theme| theme.editor_document_highlight_read_background,
 5451                        cx,
 5452                    );
 5453                    this.highlight_background::<DocumentHighlightWrite>(
 5454                        &write_ranges,
 5455                        |theme| theme.editor_document_highlight_write_background,
 5456                        cx,
 5457                    );
 5458                    cx.notify();
 5459                })
 5460                .log_err();
 5461            }
 5462        }));
 5463        None
 5464    }
 5465
 5466    fn prepare_highlight_query_from_selection(
 5467        &mut self,
 5468        cx: &mut Context<Editor>,
 5469    ) -> Option<(String, Range<Anchor>)> {
 5470        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5471            return None;
 5472        }
 5473        if !EditorSettings::get_global(cx).selection_highlight {
 5474            return None;
 5475        }
 5476        if self.selections.count() != 1 || self.selections.line_mode {
 5477            return None;
 5478        }
 5479        let selection = self.selections.newest::<Point>(cx);
 5480        if selection.is_empty() || selection.start.row != selection.end.row {
 5481            return None;
 5482        }
 5483        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5484        let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
 5485        let query = multi_buffer_snapshot
 5486            .text_for_range(selection_anchor_range.clone())
 5487            .collect::<String>();
 5488        if query.trim().is_empty() {
 5489            return None;
 5490        }
 5491        Some((query, selection_anchor_range))
 5492    }
 5493
 5494    fn update_selection_occurrence_highlights(
 5495        &mut self,
 5496        query_text: String,
 5497        query_range: Range<Anchor>,
 5498        multi_buffer_range_to_query: Range<Point>,
 5499        use_debounce: bool,
 5500        window: &mut Window,
 5501        cx: &mut Context<Editor>,
 5502    ) -> Task<()> {
 5503        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5504        cx.spawn_in(window, async move |editor, cx| {
 5505            if use_debounce {
 5506                cx.background_executor()
 5507                    .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
 5508                    .await;
 5509            }
 5510            let match_task = cx.background_spawn(async move {
 5511                let buffer_ranges = multi_buffer_snapshot
 5512                    .range_to_buffer_ranges(multi_buffer_range_to_query)
 5513                    .into_iter()
 5514                    .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
 5515                let mut match_ranges = Vec::new();
 5516                for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
 5517                    match_ranges.extend(
 5518                        project::search::SearchQuery::text(
 5519                            query_text.clone(),
 5520                            false,
 5521                            false,
 5522                            false,
 5523                            Default::default(),
 5524                            Default::default(),
 5525                            false,
 5526                            None,
 5527                        )
 5528                        .unwrap()
 5529                        .search(&buffer_snapshot, Some(search_range.clone()))
 5530                        .await
 5531                        .into_iter()
 5532                        .filter_map(|match_range| {
 5533                            let match_start = buffer_snapshot
 5534                                .anchor_after(search_range.start + match_range.start);
 5535                            let match_end =
 5536                                buffer_snapshot.anchor_before(search_range.start + match_range.end);
 5537                            let match_anchor_range = Anchor::range_in_buffer(
 5538                                excerpt_id,
 5539                                buffer_snapshot.remote_id(),
 5540                                match_start..match_end,
 5541                            );
 5542                            (match_anchor_range != query_range).then_some(match_anchor_range)
 5543                        }),
 5544                    );
 5545                }
 5546                match_ranges
 5547            });
 5548            let match_ranges = match_task.await;
 5549            editor
 5550                .update_in(cx, |editor, _, cx| {
 5551                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5552                    if !match_ranges.is_empty() {
 5553                        editor.highlight_background::<SelectedTextHighlight>(
 5554                            &match_ranges,
 5555                            |theme| theme.editor_document_highlight_bracket_background,
 5556                            cx,
 5557                        )
 5558                    }
 5559                })
 5560                .log_err();
 5561        })
 5562    }
 5563
 5564    fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
 5565        let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
 5566        else {
 5567            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5568            self.quick_selection_highlight_task.take();
 5569            self.debounced_selection_highlight_task.take();
 5570            return;
 5571        };
 5572        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 5573        if self
 5574            .quick_selection_highlight_task
 5575            .as_ref()
 5576            .map_or(true, |(prev_anchor_range, _)| {
 5577                prev_anchor_range != &query_range
 5578            })
 5579        {
 5580            let multi_buffer_visible_start = self
 5581                .scroll_manager
 5582                .anchor()
 5583                .anchor
 5584                .to_point(&multi_buffer_snapshot);
 5585            let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 5586                multi_buffer_visible_start
 5587                    + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 5588                Bias::Left,
 5589            );
 5590            let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 5591            self.quick_selection_highlight_task = Some((
 5592                query_range.clone(),
 5593                self.update_selection_occurrence_highlights(
 5594                    query_text.clone(),
 5595                    query_range.clone(),
 5596                    multi_buffer_visible_range,
 5597                    false,
 5598                    window,
 5599                    cx,
 5600                ),
 5601            ));
 5602        }
 5603        if self
 5604            .debounced_selection_highlight_task
 5605            .as_ref()
 5606            .map_or(true, |(prev_anchor_range, _)| {
 5607                prev_anchor_range != &query_range
 5608            })
 5609        {
 5610            let multi_buffer_start = multi_buffer_snapshot
 5611                .anchor_before(0)
 5612                .to_point(&multi_buffer_snapshot);
 5613            let multi_buffer_end = multi_buffer_snapshot
 5614                .anchor_after(multi_buffer_snapshot.len())
 5615                .to_point(&multi_buffer_snapshot);
 5616            let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
 5617            self.debounced_selection_highlight_task = Some((
 5618                query_range.clone(),
 5619                self.update_selection_occurrence_highlights(
 5620                    query_text,
 5621                    query_range,
 5622                    multi_buffer_full_range,
 5623                    true,
 5624                    window,
 5625                    cx,
 5626                ),
 5627            ));
 5628        }
 5629    }
 5630
 5631    pub fn refresh_inline_completion(
 5632        &mut self,
 5633        debounce: bool,
 5634        user_requested: bool,
 5635        window: &mut Window,
 5636        cx: &mut Context<Self>,
 5637    ) -> Option<()> {
 5638        let provider = self.edit_prediction_provider()?;
 5639        let cursor = self.selections.newest_anchor().head();
 5640        let (buffer, cursor_buffer_position) =
 5641            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5642
 5643        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5644            self.discard_inline_completion(false, cx);
 5645            return None;
 5646        }
 5647
 5648        if !user_requested
 5649            && (!self.should_show_edit_predictions()
 5650                || !self.is_focused(window)
 5651                || buffer.read(cx).is_empty())
 5652        {
 5653            self.discard_inline_completion(false, cx);
 5654            return None;
 5655        }
 5656
 5657        self.update_visible_inline_completion(window, cx);
 5658        provider.refresh(
 5659            self.project.clone(),
 5660            buffer,
 5661            cursor_buffer_position,
 5662            debounce,
 5663            cx,
 5664        );
 5665        Some(())
 5666    }
 5667
 5668    fn show_edit_predictions_in_menu(&self) -> bool {
 5669        match self.edit_prediction_settings {
 5670            EditPredictionSettings::Disabled => false,
 5671            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5672        }
 5673    }
 5674
 5675    pub fn edit_predictions_enabled(&self) -> bool {
 5676        match self.edit_prediction_settings {
 5677            EditPredictionSettings::Disabled => false,
 5678            EditPredictionSettings::Enabled { .. } => true,
 5679        }
 5680    }
 5681
 5682    fn edit_prediction_requires_modifier(&self) -> bool {
 5683        match self.edit_prediction_settings {
 5684            EditPredictionSettings::Disabled => false,
 5685            EditPredictionSettings::Enabled {
 5686                preview_requires_modifier,
 5687                ..
 5688            } => preview_requires_modifier,
 5689        }
 5690    }
 5691
 5692    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5693        if self.edit_prediction_provider.is_none() {
 5694            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5695        } else {
 5696            let selection = self.selections.newest_anchor();
 5697            let cursor = selection.head();
 5698
 5699            if let Some((buffer, cursor_buffer_position)) =
 5700                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5701            {
 5702                self.edit_prediction_settings =
 5703                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5704            }
 5705        }
 5706    }
 5707
 5708    fn edit_prediction_settings_at_position(
 5709        &self,
 5710        buffer: &Entity<Buffer>,
 5711        buffer_position: language::Anchor,
 5712        cx: &App,
 5713    ) -> EditPredictionSettings {
 5714        if !self.mode.is_full()
 5715            || !self.show_inline_completions_override.unwrap_or(true)
 5716            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5717        {
 5718            return EditPredictionSettings::Disabled;
 5719        }
 5720
 5721        let buffer = buffer.read(cx);
 5722
 5723        let file = buffer.file();
 5724
 5725        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5726            return EditPredictionSettings::Disabled;
 5727        };
 5728
 5729        let by_provider = matches!(
 5730            self.menu_inline_completions_policy,
 5731            MenuInlineCompletionsPolicy::ByProvider
 5732        );
 5733
 5734        let show_in_menu = by_provider
 5735            && self
 5736                .edit_prediction_provider
 5737                .as_ref()
 5738                .map_or(false, |provider| {
 5739                    provider.provider.show_completions_in_menu()
 5740                });
 5741
 5742        let preview_requires_modifier =
 5743            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5744
 5745        EditPredictionSettings::Enabled {
 5746            show_in_menu,
 5747            preview_requires_modifier,
 5748        }
 5749    }
 5750
 5751    fn should_show_edit_predictions(&self) -> bool {
 5752        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5753    }
 5754
 5755    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5756        matches!(
 5757            self.edit_prediction_preview,
 5758            EditPredictionPreview::Active { .. }
 5759        )
 5760    }
 5761
 5762    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5763        let cursor = self.selections.newest_anchor().head();
 5764        if let Some((buffer, cursor_position)) =
 5765            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5766        {
 5767            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5768        } else {
 5769            false
 5770        }
 5771    }
 5772
 5773    fn edit_predictions_enabled_in_buffer(
 5774        &self,
 5775        buffer: &Entity<Buffer>,
 5776        buffer_position: language::Anchor,
 5777        cx: &App,
 5778    ) -> bool {
 5779        maybe!({
 5780            if self.read_only(cx) {
 5781                return Some(false);
 5782            }
 5783            let provider = self.edit_prediction_provider()?;
 5784            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5785                return Some(false);
 5786            }
 5787            let buffer = buffer.read(cx);
 5788            let Some(file) = buffer.file() else {
 5789                return Some(true);
 5790            };
 5791            let settings = all_language_settings(Some(file), cx);
 5792            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5793        })
 5794        .unwrap_or(false)
 5795    }
 5796
 5797    fn cycle_inline_completion(
 5798        &mut self,
 5799        direction: Direction,
 5800        window: &mut Window,
 5801        cx: &mut Context<Self>,
 5802    ) -> Option<()> {
 5803        let provider = self.edit_prediction_provider()?;
 5804        let cursor = self.selections.newest_anchor().head();
 5805        let (buffer, cursor_buffer_position) =
 5806            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5807        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5808            return None;
 5809        }
 5810
 5811        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5812        self.update_visible_inline_completion(window, cx);
 5813
 5814        Some(())
 5815    }
 5816
 5817    pub fn show_inline_completion(
 5818        &mut self,
 5819        _: &ShowEditPrediction,
 5820        window: &mut Window,
 5821        cx: &mut Context<Self>,
 5822    ) {
 5823        if !self.has_active_inline_completion() {
 5824            self.refresh_inline_completion(false, true, window, cx);
 5825            return;
 5826        }
 5827
 5828        self.update_visible_inline_completion(window, cx);
 5829    }
 5830
 5831    pub fn display_cursor_names(
 5832        &mut self,
 5833        _: &DisplayCursorNames,
 5834        window: &mut Window,
 5835        cx: &mut Context<Self>,
 5836    ) {
 5837        self.show_cursor_names(window, cx);
 5838    }
 5839
 5840    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5841        self.show_cursor_names = true;
 5842        cx.notify();
 5843        cx.spawn_in(window, async move |this, cx| {
 5844            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5845            this.update(cx, |this, cx| {
 5846                this.show_cursor_names = false;
 5847                cx.notify()
 5848            })
 5849            .ok()
 5850        })
 5851        .detach();
 5852    }
 5853
 5854    pub fn next_edit_prediction(
 5855        &mut self,
 5856        _: &NextEditPrediction,
 5857        window: &mut Window,
 5858        cx: &mut Context<Self>,
 5859    ) {
 5860        if self.has_active_inline_completion() {
 5861            self.cycle_inline_completion(Direction::Next, window, cx);
 5862        } else {
 5863            let is_copilot_disabled = self
 5864                .refresh_inline_completion(false, true, window, cx)
 5865                .is_none();
 5866            if is_copilot_disabled {
 5867                cx.propagate();
 5868            }
 5869        }
 5870    }
 5871
 5872    pub fn previous_edit_prediction(
 5873        &mut self,
 5874        _: &PreviousEditPrediction,
 5875        window: &mut Window,
 5876        cx: &mut Context<Self>,
 5877    ) {
 5878        if self.has_active_inline_completion() {
 5879            self.cycle_inline_completion(Direction::Prev, window, cx);
 5880        } else {
 5881            let is_copilot_disabled = self
 5882                .refresh_inline_completion(false, true, window, cx)
 5883                .is_none();
 5884            if is_copilot_disabled {
 5885                cx.propagate();
 5886            }
 5887        }
 5888    }
 5889
 5890    pub fn accept_edit_prediction(
 5891        &mut self,
 5892        _: &AcceptEditPrediction,
 5893        window: &mut Window,
 5894        cx: &mut Context<Self>,
 5895    ) {
 5896        if self.show_edit_predictions_in_menu() {
 5897            self.hide_context_menu(window, cx);
 5898        }
 5899
 5900        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5901            return;
 5902        };
 5903
 5904        self.report_inline_completion_event(
 5905            active_inline_completion.completion_id.clone(),
 5906            true,
 5907            cx,
 5908        );
 5909
 5910        match &active_inline_completion.completion {
 5911            InlineCompletion::Move { target, .. } => {
 5912                let target = *target;
 5913
 5914                if let Some(position_map) = &self.last_position_map {
 5915                    if position_map
 5916                        .visible_row_range
 5917                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5918                        || !self.edit_prediction_requires_modifier()
 5919                    {
 5920                        self.unfold_ranges(&[target..target], true, false, cx);
 5921                        // Note that this is also done in vim's handler of the Tab action.
 5922                        self.change_selections(
 5923                            Some(Autoscroll::newest()),
 5924                            window,
 5925                            cx,
 5926                            |selections| {
 5927                                selections.select_anchor_ranges([target..target]);
 5928                            },
 5929                        );
 5930                        self.clear_row_highlights::<EditPredictionPreview>();
 5931
 5932                        self.edit_prediction_preview
 5933                            .set_previous_scroll_position(None);
 5934                    } else {
 5935                        self.edit_prediction_preview
 5936                            .set_previous_scroll_position(Some(
 5937                                position_map.snapshot.scroll_anchor,
 5938                            ));
 5939
 5940                        self.highlight_rows::<EditPredictionPreview>(
 5941                            target..target,
 5942                            cx.theme().colors().editor_highlighted_line_background,
 5943                            true,
 5944                            cx,
 5945                        );
 5946                        self.request_autoscroll(Autoscroll::fit(), cx);
 5947                    }
 5948                }
 5949            }
 5950            InlineCompletion::Edit { edits, .. } => {
 5951                if let Some(provider) = self.edit_prediction_provider() {
 5952                    provider.accept(cx);
 5953                }
 5954
 5955                let snapshot = self.buffer.read(cx).snapshot(cx);
 5956                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5957
 5958                self.buffer.update(cx, |buffer, cx| {
 5959                    buffer.edit(edits.iter().cloned(), None, cx)
 5960                });
 5961
 5962                self.change_selections(None, window, cx, |s| {
 5963                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5964                });
 5965
 5966                self.update_visible_inline_completion(window, cx);
 5967                if self.active_inline_completion.is_none() {
 5968                    self.refresh_inline_completion(true, true, window, cx);
 5969                }
 5970
 5971                cx.notify();
 5972            }
 5973        }
 5974
 5975        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5976    }
 5977
 5978    pub fn accept_partial_inline_completion(
 5979        &mut self,
 5980        _: &AcceptPartialEditPrediction,
 5981        window: &mut Window,
 5982        cx: &mut Context<Self>,
 5983    ) {
 5984        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5985            return;
 5986        };
 5987        if self.selections.count() != 1 {
 5988            return;
 5989        }
 5990
 5991        self.report_inline_completion_event(
 5992            active_inline_completion.completion_id.clone(),
 5993            true,
 5994            cx,
 5995        );
 5996
 5997        match &active_inline_completion.completion {
 5998            InlineCompletion::Move { target, .. } => {
 5999                let target = *target;
 6000                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 6001                    selections.select_anchor_ranges([target..target]);
 6002                });
 6003            }
 6004            InlineCompletion::Edit { edits, .. } => {
 6005                // Find an insertion that starts at the cursor position.
 6006                let snapshot = self.buffer.read(cx).snapshot(cx);
 6007                let cursor_offset = self.selections.newest::<usize>(cx).head();
 6008                let insertion = edits.iter().find_map(|(range, text)| {
 6009                    let range = range.to_offset(&snapshot);
 6010                    if range.is_empty() && range.start == cursor_offset {
 6011                        Some(text)
 6012                    } else {
 6013                        None
 6014                    }
 6015                });
 6016
 6017                if let Some(text) = insertion {
 6018                    let mut partial_completion = text
 6019                        .chars()
 6020                        .by_ref()
 6021                        .take_while(|c| c.is_alphabetic())
 6022                        .collect::<String>();
 6023                    if partial_completion.is_empty() {
 6024                        partial_completion = text
 6025                            .chars()
 6026                            .by_ref()
 6027                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 6028                            .collect::<String>();
 6029                    }
 6030
 6031                    cx.emit(EditorEvent::InputHandled {
 6032                        utf16_range_to_replace: None,
 6033                        text: partial_completion.clone().into(),
 6034                    });
 6035
 6036                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 6037
 6038                    self.refresh_inline_completion(true, true, window, cx);
 6039                    cx.notify();
 6040                } else {
 6041                    self.accept_edit_prediction(&Default::default(), window, cx);
 6042                }
 6043            }
 6044        }
 6045    }
 6046
 6047    fn discard_inline_completion(
 6048        &mut self,
 6049        should_report_inline_completion_event: bool,
 6050        cx: &mut Context<Self>,
 6051    ) -> bool {
 6052        if should_report_inline_completion_event {
 6053            let completion_id = self
 6054                .active_inline_completion
 6055                .as_ref()
 6056                .and_then(|active_completion| active_completion.completion_id.clone());
 6057
 6058            self.report_inline_completion_event(completion_id, false, cx);
 6059        }
 6060
 6061        if let Some(provider) = self.edit_prediction_provider() {
 6062            provider.discard(cx);
 6063        }
 6064
 6065        self.take_active_inline_completion(cx)
 6066    }
 6067
 6068    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 6069        let Some(provider) = self.edit_prediction_provider() else {
 6070            return;
 6071        };
 6072
 6073        let Some((_, buffer, _)) = self
 6074            .buffer
 6075            .read(cx)
 6076            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 6077        else {
 6078            return;
 6079        };
 6080
 6081        let extension = buffer
 6082            .read(cx)
 6083            .file()
 6084            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 6085
 6086        let event_type = match accepted {
 6087            true => "Edit Prediction Accepted",
 6088            false => "Edit Prediction Discarded",
 6089        };
 6090        telemetry::event!(
 6091            event_type,
 6092            provider = provider.name(),
 6093            prediction_id = id,
 6094            suggestion_accepted = accepted,
 6095            file_extension = extension,
 6096        );
 6097    }
 6098
 6099    pub fn has_active_inline_completion(&self) -> bool {
 6100        self.active_inline_completion.is_some()
 6101    }
 6102
 6103    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 6104        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 6105            return false;
 6106        };
 6107
 6108        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 6109        self.clear_highlights::<InlineCompletionHighlight>(cx);
 6110        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 6111        true
 6112    }
 6113
 6114    /// Returns true when we're displaying the edit prediction popover below the cursor
 6115    /// like we are not previewing and the LSP autocomplete menu is visible
 6116    /// or we are in `when_holding_modifier` mode.
 6117    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 6118        if self.edit_prediction_preview_is_active()
 6119            || !self.show_edit_predictions_in_menu()
 6120            || !self.edit_predictions_enabled()
 6121        {
 6122            return false;
 6123        }
 6124
 6125        if self.has_visible_completions_menu() {
 6126            return true;
 6127        }
 6128
 6129        has_completion && self.edit_prediction_requires_modifier()
 6130    }
 6131
 6132    fn handle_modifiers_changed(
 6133        &mut self,
 6134        modifiers: Modifiers,
 6135        position_map: &PositionMap,
 6136        window: &mut Window,
 6137        cx: &mut Context<Self>,
 6138    ) {
 6139        if self.show_edit_predictions_in_menu() {
 6140            self.update_edit_prediction_preview(&modifiers, window, cx);
 6141        }
 6142
 6143        self.update_selection_mode(&modifiers, position_map, window, cx);
 6144
 6145        let mouse_position = window.mouse_position();
 6146        if !position_map.text_hitbox.is_hovered(window) {
 6147            return;
 6148        }
 6149
 6150        self.update_hovered_link(
 6151            position_map.point_for_position(mouse_position),
 6152            &position_map.snapshot,
 6153            modifiers,
 6154            window,
 6155            cx,
 6156        )
 6157    }
 6158
 6159    fn update_selection_mode(
 6160        &mut self,
 6161        modifiers: &Modifiers,
 6162        position_map: &PositionMap,
 6163        window: &mut Window,
 6164        cx: &mut Context<Self>,
 6165    ) {
 6166        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 6167            return;
 6168        }
 6169
 6170        let mouse_position = window.mouse_position();
 6171        let point_for_position = position_map.point_for_position(mouse_position);
 6172        let position = point_for_position.previous_valid;
 6173
 6174        self.select(
 6175            SelectPhase::BeginColumnar {
 6176                position,
 6177                reset: false,
 6178                goal_column: point_for_position.exact_unclipped.column(),
 6179            },
 6180            window,
 6181            cx,
 6182        );
 6183    }
 6184
 6185    fn update_edit_prediction_preview(
 6186        &mut self,
 6187        modifiers: &Modifiers,
 6188        window: &mut Window,
 6189        cx: &mut Context<Self>,
 6190    ) {
 6191        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 6192        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 6193            return;
 6194        };
 6195
 6196        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 6197            if matches!(
 6198                self.edit_prediction_preview,
 6199                EditPredictionPreview::Inactive { .. }
 6200            ) {
 6201                self.edit_prediction_preview = EditPredictionPreview::Active {
 6202                    previous_scroll_position: None,
 6203                    since: Instant::now(),
 6204                };
 6205
 6206                self.update_visible_inline_completion(window, cx);
 6207                cx.notify();
 6208            }
 6209        } else if let EditPredictionPreview::Active {
 6210            previous_scroll_position,
 6211            since,
 6212        } = self.edit_prediction_preview
 6213        {
 6214            if let (Some(previous_scroll_position), Some(position_map)) =
 6215                (previous_scroll_position, self.last_position_map.as_ref())
 6216            {
 6217                self.set_scroll_position(
 6218                    previous_scroll_position
 6219                        .scroll_position(&position_map.snapshot.display_snapshot),
 6220                    window,
 6221                    cx,
 6222                );
 6223            }
 6224
 6225            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 6226                released_too_fast: since.elapsed() < Duration::from_millis(200),
 6227            };
 6228            self.clear_row_highlights::<EditPredictionPreview>();
 6229            self.update_visible_inline_completion(window, cx);
 6230            cx.notify();
 6231        }
 6232    }
 6233
 6234    fn update_visible_inline_completion(
 6235        &mut self,
 6236        _window: &mut Window,
 6237        cx: &mut Context<Self>,
 6238    ) -> Option<()> {
 6239        let selection = self.selections.newest_anchor();
 6240        let cursor = selection.head();
 6241        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6242        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6243        let excerpt_id = cursor.excerpt_id;
 6244
 6245        let show_in_menu = self.show_edit_predictions_in_menu();
 6246        let completions_menu_has_precedence = !show_in_menu
 6247            && (self.context_menu.borrow().is_some()
 6248                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6249
 6250        if completions_menu_has_precedence
 6251            || !offset_selection.is_empty()
 6252            || self
 6253                .active_inline_completion
 6254                .as_ref()
 6255                .map_or(false, |completion| {
 6256                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6257                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6258                    !invalidation_range.contains(&offset_selection.head())
 6259                })
 6260        {
 6261            self.discard_inline_completion(false, cx);
 6262            return None;
 6263        }
 6264
 6265        self.take_active_inline_completion(cx);
 6266        let Some(provider) = self.edit_prediction_provider() else {
 6267            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6268            return None;
 6269        };
 6270
 6271        let (buffer, cursor_buffer_position) =
 6272            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6273
 6274        self.edit_prediction_settings =
 6275            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6276
 6277        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6278
 6279        if self.edit_prediction_indent_conflict {
 6280            let cursor_point = cursor.to_point(&multibuffer);
 6281
 6282            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6283
 6284            if let Some((_, indent)) = indents.iter().next() {
 6285                if indent.len == cursor_point.column {
 6286                    self.edit_prediction_indent_conflict = false;
 6287                }
 6288            }
 6289        }
 6290
 6291        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6292        let edits = inline_completion
 6293            .edits
 6294            .into_iter()
 6295            .flat_map(|(range, new_text)| {
 6296                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6297                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6298                Some((start..end, new_text))
 6299            })
 6300            .collect::<Vec<_>>();
 6301        if edits.is_empty() {
 6302            return None;
 6303        }
 6304
 6305        let first_edit_start = edits.first().unwrap().0.start;
 6306        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6307        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6308
 6309        let last_edit_end = edits.last().unwrap().0.end;
 6310        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6311        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6312
 6313        let cursor_row = cursor.to_point(&multibuffer).row;
 6314
 6315        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6316
 6317        let mut inlay_ids = Vec::new();
 6318        let invalidation_row_range;
 6319        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6320            Some(cursor_row..edit_end_row)
 6321        } else if cursor_row > edit_end_row {
 6322            Some(edit_start_row..cursor_row)
 6323        } else {
 6324            None
 6325        };
 6326        let is_move =
 6327            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6328        let completion = if is_move {
 6329            invalidation_row_range =
 6330                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6331            let target = first_edit_start;
 6332            InlineCompletion::Move { target, snapshot }
 6333        } else {
 6334            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6335                && !self.inline_completions_hidden_for_vim_mode;
 6336
 6337            if show_completions_in_buffer {
 6338                if edits
 6339                    .iter()
 6340                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6341                {
 6342                    let mut inlays = Vec::new();
 6343                    for (range, new_text) in &edits {
 6344                        let inlay = Inlay::inline_completion(
 6345                            post_inc(&mut self.next_inlay_id),
 6346                            range.start,
 6347                            new_text.as_str(),
 6348                        );
 6349                        inlay_ids.push(inlay.id);
 6350                        inlays.push(inlay);
 6351                    }
 6352
 6353                    self.splice_inlays(&[], inlays, cx);
 6354                } else {
 6355                    let background_color = cx.theme().status().deleted_background;
 6356                    self.highlight_text::<InlineCompletionHighlight>(
 6357                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6358                        HighlightStyle {
 6359                            background_color: Some(background_color),
 6360                            ..Default::default()
 6361                        },
 6362                        cx,
 6363                    );
 6364                }
 6365            }
 6366
 6367            invalidation_row_range = edit_start_row..edit_end_row;
 6368
 6369            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6370                if provider.show_tab_accept_marker() {
 6371                    EditDisplayMode::TabAccept
 6372                } else {
 6373                    EditDisplayMode::Inline
 6374                }
 6375            } else {
 6376                EditDisplayMode::DiffPopover
 6377            };
 6378
 6379            InlineCompletion::Edit {
 6380                edits,
 6381                edit_preview: inline_completion.edit_preview,
 6382                display_mode,
 6383                snapshot,
 6384            }
 6385        };
 6386
 6387        let invalidation_range = multibuffer
 6388            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6389            ..multibuffer.anchor_after(Point::new(
 6390                invalidation_row_range.end,
 6391                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6392            ));
 6393
 6394        self.stale_inline_completion_in_menu = None;
 6395        self.active_inline_completion = Some(InlineCompletionState {
 6396            inlay_ids,
 6397            completion,
 6398            completion_id: inline_completion.id,
 6399            invalidation_range,
 6400        });
 6401
 6402        cx.notify();
 6403
 6404        Some(())
 6405    }
 6406
 6407    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6408        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6409    }
 6410
 6411    fn render_code_actions_indicator(
 6412        &self,
 6413        _style: &EditorStyle,
 6414        row: DisplayRow,
 6415        is_active: bool,
 6416        breakpoint: Option<&(Anchor, Breakpoint)>,
 6417        cx: &mut Context<Self>,
 6418    ) -> Option<IconButton> {
 6419        let color = Color::Muted;
 6420        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6421        let show_tooltip = !self.context_menu_visible();
 6422
 6423        if self.available_code_actions.is_some() {
 6424            Some(
 6425                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6426                    .shape(ui::IconButtonShape::Square)
 6427                    .icon_size(IconSize::XSmall)
 6428                    .icon_color(color)
 6429                    .toggle_state(is_active)
 6430                    .when(show_tooltip, |this| {
 6431                        this.tooltip({
 6432                            let focus_handle = self.focus_handle.clone();
 6433                            move |window, cx| {
 6434                                Tooltip::for_action_in(
 6435                                    "Toggle Code Actions",
 6436                                    &ToggleCodeActions {
 6437                                        deployed_from_indicator: None,
 6438                                    },
 6439                                    &focus_handle,
 6440                                    window,
 6441                                    cx,
 6442                                )
 6443                            }
 6444                        })
 6445                    })
 6446                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6447                        window.focus(&editor.focus_handle(cx));
 6448                        editor.toggle_code_actions(
 6449                            &ToggleCodeActions {
 6450                                deployed_from_indicator: Some(row),
 6451                            },
 6452                            window,
 6453                            cx,
 6454                        );
 6455                    }))
 6456                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6457                        editor.set_breakpoint_context_menu(
 6458                            row,
 6459                            position,
 6460                            event.down.position,
 6461                            window,
 6462                            cx,
 6463                        );
 6464                    })),
 6465            )
 6466        } else {
 6467            None
 6468        }
 6469    }
 6470
 6471    fn clear_tasks(&mut self) {
 6472        self.tasks.clear()
 6473    }
 6474
 6475    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6476        if self.tasks.insert(key, value).is_some() {
 6477            // This case should hopefully be rare, but just in case...
 6478            log::error!(
 6479                "multiple different run targets found on a single line, only the last target will be rendered"
 6480            )
 6481        }
 6482    }
 6483
 6484    /// Get all display points of breakpoints that will be rendered within editor
 6485    ///
 6486    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6487    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6488    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6489    fn active_breakpoints(
 6490        &self,
 6491        range: Range<DisplayRow>,
 6492        window: &mut Window,
 6493        cx: &mut Context<Self>,
 6494    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6495        let mut breakpoint_display_points = HashMap::default();
 6496
 6497        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6498            return breakpoint_display_points;
 6499        };
 6500
 6501        let snapshot = self.snapshot(window, cx);
 6502
 6503        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6504        let Some(project) = self.project.as_ref() else {
 6505            return breakpoint_display_points;
 6506        };
 6507
 6508        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6509            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6510
 6511        for (buffer_snapshot, range, excerpt_id) in
 6512            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6513        {
 6514            let Some(buffer) = project.read_with(cx, |this, cx| {
 6515                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6516            }) else {
 6517                continue;
 6518            };
 6519            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6520                &buffer,
 6521                Some(
 6522                    buffer_snapshot.anchor_before(range.start)
 6523                        ..buffer_snapshot.anchor_after(range.end),
 6524                ),
 6525                buffer_snapshot,
 6526                cx,
 6527            );
 6528            for (anchor, breakpoint) in breakpoints {
 6529                let multi_buffer_anchor =
 6530                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6531                let position = multi_buffer_anchor
 6532                    .to_point(&multi_buffer_snapshot)
 6533                    .to_display_point(&snapshot);
 6534
 6535                breakpoint_display_points
 6536                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6537            }
 6538        }
 6539
 6540        breakpoint_display_points
 6541    }
 6542
 6543    fn breakpoint_context_menu(
 6544        &self,
 6545        anchor: Anchor,
 6546        window: &mut Window,
 6547        cx: &mut Context<Self>,
 6548    ) -> Entity<ui::ContextMenu> {
 6549        let weak_editor = cx.weak_entity();
 6550        let focus_handle = self.focus_handle(cx);
 6551
 6552        let row = self
 6553            .buffer
 6554            .read(cx)
 6555            .snapshot(cx)
 6556            .summary_for_anchor::<Point>(&anchor)
 6557            .row;
 6558
 6559        let breakpoint = self
 6560            .breakpoint_at_row(row, window, cx)
 6561            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6562
 6563        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6564            "Edit Log Breakpoint"
 6565        } else {
 6566            "Set Log Breakpoint"
 6567        };
 6568
 6569        let condition_breakpoint_msg = if breakpoint
 6570            .as_ref()
 6571            .is_some_and(|bp| bp.1.condition.is_some())
 6572        {
 6573            "Edit Condition Breakpoint"
 6574        } else {
 6575            "Set Condition Breakpoint"
 6576        };
 6577
 6578        let hit_condition_breakpoint_msg = if breakpoint
 6579            .as_ref()
 6580            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6581        {
 6582            "Edit Hit Condition Breakpoint"
 6583        } else {
 6584            "Set Hit Condition Breakpoint"
 6585        };
 6586
 6587        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6588            "Unset Breakpoint"
 6589        } else {
 6590            "Set Breakpoint"
 6591        };
 6592
 6593        let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
 6594            .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
 6595
 6596        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6597            BreakpointState::Enabled => Some("Disable"),
 6598            BreakpointState::Disabled => Some("Enable"),
 6599        });
 6600
 6601        let (anchor, breakpoint) =
 6602            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6603
 6604        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6605            menu.on_blur_subscription(Subscription::new(|| {}))
 6606                .context(focus_handle)
 6607                .when(run_to_cursor, |this| {
 6608                    let weak_editor = weak_editor.clone();
 6609                    this.entry("Run to cursor", None, move |window, cx| {
 6610                        weak_editor
 6611                            .update(cx, |editor, cx| {
 6612                                editor.change_selections(None, window, cx, |s| {
 6613                                    s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
 6614                                });
 6615                            })
 6616                            .ok();
 6617
 6618                        window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
 6619                    })
 6620                    .separator()
 6621                })
 6622                .when_some(toggle_state_msg, |this, msg| {
 6623                    this.entry(msg, None, {
 6624                        let weak_editor = weak_editor.clone();
 6625                        let breakpoint = breakpoint.clone();
 6626                        move |_window, cx| {
 6627                            weak_editor
 6628                                .update(cx, |this, cx| {
 6629                                    this.edit_breakpoint_at_anchor(
 6630                                        anchor,
 6631                                        breakpoint.as_ref().clone(),
 6632                                        BreakpointEditAction::InvertState,
 6633                                        cx,
 6634                                    );
 6635                                })
 6636                                .log_err();
 6637                        }
 6638                    })
 6639                })
 6640                .entry(set_breakpoint_msg, None, {
 6641                    let weak_editor = weak_editor.clone();
 6642                    let breakpoint = breakpoint.clone();
 6643                    move |_window, cx| {
 6644                        weak_editor
 6645                            .update(cx, |this, cx| {
 6646                                this.edit_breakpoint_at_anchor(
 6647                                    anchor,
 6648                                    breakpoint.as_ref().clone(),
 6649                                    BreakpointEditAction::Toggle,
 6650                                    cx,
 6651                                );
 6652                            })
 6653                            .log_err();
 6654                    }
 6655                })
 6656                .entry(log_breakpoint_msg, None, {
 6657                    let breakpoint = breakpoint.clone();
 6658                    let weak_editor = weak_editor.clone();
 6659                    move |window, cx| {
 6660                        weak_editor
 6661                            .update(cx, |this, cx| {
 6662                                this.add_edit_breakpoint_block(
 6663                                    anchor,
 6664                                    breakpoint.as_ref(),
 6665                                    BreakpointPromptEditAction::Log,
 6666                                    window,
 6667                                    cx,
 6668                                );
 6669                            })
 6670                            .log_err();
 6671                    }
 6672                })
 6673                .entry(condition_breakpoint_msg, None, {
 6674                    let breakpoint = breakpoint.clone();
 6675                    let weak_editor = weak_editor.clone();
 6676                    move |window, cx| {
 6677                        weak_editor
 6678                            .update(cx, |this, cx| {
 6679                                this.add_edit_breakpoint_block(
 6680                                    anchor,
 6681                                    breakpoint.as_ref(),
 6682                                    BreakpointPromptEditAction::Condition,
 6683                                    window,
 6684                                    cx,
 6685                                );
 6686                            })
 6687                            .log_err();
 6688                    }
 6689                })
 6690                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6691                    weak_editor
 6692                        .update(cx, |this, cx| {
 6693                            this.add_edit_breakpoint_block(
 6694                                anchor,
 6695                                breakpoint.as_ref(),
 6696                                BreakpointPromptEditAction::HitCondition,
 6697                                window,
 6698                                cx,
 6699                            );
 6700                        })
 6701                        .log_err();
 6702                })
 6703        })
 6704    }
 6705
 6706    fn render_breakpoint(
 6707        &self,
 6708        position: Anchor,
 6709        row: DisplayRow,
 6710        breakpoint: &Breakpoint,
 6711        cx: &mut Context<Self>,
 6712    ) -> IconButton {
 6713        let (color, icon) = {
 6714            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6715                (false, false) => ui::IconName::DebugBreakpoint,
 6716                (true, false) => ui::IconName::DebugLogBreakpoint,
 6717                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6718                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6719            };
 6720
 6721            let color = if self
 6722                .gutter_breakpoint_indicator
 6723                .0
 6724                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6725            {
 6726                Color::Hint
 6727            } else {
 6728                Color::Debugger
 6729            };
 6730
 6731            (color, icon)
 6732        };
 6733
 6734        let breakpoint = Arc::from(breakpoint.clone());
 6735
 6736        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6737            .icon_size(IconSize::XSmall)
 6738            .size(ui::ButtonSize::None)
 6739            .icon_color(color)
 6740            .style(ButtonStyle::Transparent)
 6741            .on_click(cx.listener({
 6742                let breakpoint = breakpoint.clone();
 6743
 6744                move |editor, event: &ClickEvent, window, cx| {
 6745                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6746                        BreakpointEditAction::InvertState
 6747                    } else {
 6748                        BreakpointEditAction::Toggle
 6749                    };
 6750
 6751                    window.focus(&editor.focus_handle(cx));
 6752                    editor.edit_breakpoint_at_anchor(
 6753                        position,
 6754                        breakpoint.as_ref().clone(),
 6755                        edit_action,
 6756                        cx,
 6757                    );
 6758                }
 6759            }))
 6760            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6761                editor.set_breakpoint_context_menu(
 6762                    row,
 6763                    Some(position),
 6764                    event.down.position,
 6765                    window,
 6766                    cx,
 6767                );
 6768            }))
 6769    }
 6770
 6771    fn build_tasks_context(
 6772        project: &Entity<Project>,
 6773        buffer: &Entity<Buffer>,
 6774        buffer_row: u32,
 6775        tasks: &Arc<RunnableTasks>,
 6776        cx: &mut Context<Self>,
 6777    ) -> Task<Option<task::TaskContext>> {
 6778        let position = Point::new(buffer_row, tasks.column);
 6779        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6780        let location = Location {
 6781            buffer: buffer.clone(),
 6782            range: range_start..range_start,
 6783        };
 6784        // Fill in the environmental variables from the tree-sitter captures
 6785        let mut captured_task_variables = TaskVariables::default();
 6786        for (capture_name, value) in tasks.extra_variables.clone() {
 6787            captured_task_variables.insert(
 6788                task::VariableName::Custom(capture_name.into()),
 6789                value.clone(),
 6790            );
 6791        }
 6792        project.update(cx, |project, cx| {
 6793            project.task_store().update(cx, |task_store, cx| {
 6794                task_store.task_context_for_location(captured_task_variables, location, cx)
 6795            })
 6796        })
 6797    }
 6798
 6799    pub fn spawn_nearest_task(
 6800        &mut self,
 6801        action: &SpawnNearestTask,
 6802        window: &mut Window,
 6803        cx: &mut Context<Self>,
 6804    ) {
 6805        let Some((workspace, _)) = self.workspace.clone() else {
 6806            return;
 6807        };
 6808        let Some(project) = self.project.clone() else {
 6809            return;
 6810        };
 6811
 6812        // Try to find a closest, enclosing node using tree-sitter that has a
 6813        // task
 6814        let Some((buffer, buffer_row, tasks)) = self
 6815            .find_enclosing_node_task(cx)
 6816            // Or find the task that's closest in row-distance.
 6817            .or_else(|| self.find_closest_task(cx))
 6818        else {
 6819            return;
 6820        };
 6821
 6822        let reveal_strategy = action.reveal;
 6823        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6824        cx.spawn_in(window, async move |_, cx| {
 6825            let context = task_context.await?;
 6826            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6827
 6828            let resolved = resolved_task.resolved.as_mut()?;
 6829            resolved.reveal = reveal_strategy;
 6830
 6831            workspace
 6832                .update_in(cx, |workspace, window, cx| {
 6833                    workspace.schedule_resolved_task(
 6834                        task_source_kind,
 6835                        resolved_task,
 6836                        false,
 6837                        window,
 6838                        cx,
 6839                    );
 6840                })
 6841                .ok()
 6842        })
 6843        .detach();
 6844    }
 6845
 6846    fn find_closest_task(
 6847        &mut self,
 6848        cx: &mut Context<Self>,
 6849    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6850        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6851
 6852        let ((buffer_id, row), tasks) = self
 6853            .tasks
 6854            .iter()
 6855            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6856
 6857        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6858        let tasks = Arc::new(tasks.to_owned());
 6859        Some((buffer, *row, tasks))
 6860    }
 6861
 6862    fn find_enclosing_node_task(
 6863        &mut self,
 6864        cx: &mut Context<Self>,
 6865    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6866        let snapshot = self.buffer.read(cx).snapshot(cx);
 6867        let offset = self.selections.newest::<usize>(cx).head();
 6868        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6869        let buffer_id = excerpt.buffer().remote_id();
 6870
 6871        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6872        let mut cursor = layer.node().walk();
 6873
 6874        while cursor.goto_first_child_for_byte(offset).is_some() {
 6875            if cursor.node().end_byte() == offset {
 6876                cursor.goto_next_sibling();
 6877            }
 6878        }
 6879
 6880        // Ascend to the smallest ancestor that contains the range and has a task.
 6881        loop {
 6882            let node = cursor.node();
 6883            let node_range = node.byte_range();
 6884            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6885
 6886            // Check if this node contains our offset
 6887            if node_range.start <= offset && node_range.end >= offset {
 6888                // If it contains offset, check for task
 6889                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6890                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6891                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6892                }
 6893            }
 6894
 6895            if !cursor.goto_parent() {
 6896                break;
 6897            }
 6898        }
 6899        None
 6900    }
 6901
 6902    fn render_run_indicator(
 6903        &self,
 6904        _style: &EditorStyle,
 6905        is_active: bool,
 6906        row: DisplayRow,
 6907        breakpoint: Option<(Anchor, Breakpoint)>,
 6908        cx: &mut Context<Self>,
 6909    ) -> IconButton {
 6910        let color = Color::Muted;
 6911        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6912
 6913        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6914            .shape(ui::IconButtonShape::Square)
 6915            .icon_size(IconSize::XSmall)
 6916            .icon_color(color)
 6917            .toggle_state(is_active)
 6918            .on_click(cx.listener(move |editor, _e, window, cx| {
 6919                window.focus(&editor.focus_handle(cx));
 6920                editor.toggle_code_actions(
 6921                    &ToggleCodeActions {
 6922                        deployed_from_indicator: Some(row),
 6923                    },
 6924                    window,
 6925                    cx,
 6926                );
 6927            }))
 6928            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6929                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6930            }))
 6931    }
 6932
 6933    pub fn context_menu_visible(&self) -> bool {
 6934        !self.edit_prediction_preview_is_active()
 6935            && self
 6936                .context_menu
 6937                .borrow()
 6938                .as_ref()
 6939                .map_or(false, |menu| menu.visible())
 6940    }
 6941
 6942    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6943        self.context_menu
 6944            .borrow()
 6945            .as_ref()
 6946            .map(|menu| menu.origin())
 6947    }
 6948
 6949    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6950        self.context_menu_options = Some(options);
 6951    }
 6952
 6953    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6954    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6955
 6956    fn render_edit_prediction_popover(
 6957        &mut self,
 6958        text_bounds: &Bounds<Pixels>,
 6959        content_origin: gpui::Point<Pixels>,
 6960        editor_snapshot: &EditorSnapshot,
 6961        visible_row_range: Range<DisplayRow>,
 6962        scroll_top: f32,
 6963        scroll_bottom: f32,
 6964        line_layouts: &[LineWithInvisibles],
 6965        line_height: Pixels,
 6966        scroll_pixel_position: gpui::Point<Pixels>,
 6967        newest_selection_head: Option<DisplayPoint>,
 6968        editor_width: Pixels,
 6969        style: &EditorStyle,
 6970        window: &mut Window,
 6971        cx: &mut App,
 6972    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6973        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6974
 6975        if self.edit_prediction_visible_in_cursor_popover(true) {
 6976            return None;
 6977        }
 6978
 6979        match &active_inline_completion.completion {
 6980            InlineCompletion::Move { target, .. } => {
 6981                let target_display_point = target.to_display_point(editor_snapshot);
 6982
 6983                if self.edit_prediction_requires_modifier() {
 6984                    if !self.edit_prediction_preview_is_active() {
 6985                        return None;
 6986                    }
 6987
 6988                    self.render_edit_prediction_modifier_jump_popover(
 6989                        text_bounds,
 6990                        content_origin,
 6991                        visible_row_range,
 6992                        line_layouts,
 6993                        line_height,
 6994                        scroll_pixel_position,
 6995                        newest_selection_head,
 6996                        target_display_point,
 6997                        window,
 6998                        cx,
 6999                    )
 7000                } else {
 7001                    self.render_edit_prediction_eager_jump_popover(
 7002                        text_bounds,
 7003                        content_origin,
 7004                        editor_snapshot,
 7005                        visible_row_range,
 7006                        scroll_top,
 7007                        scroll_bottom,
 7008                        line_height,
 7009                        scroll_pixel_position,
 7010                        target_display_point,
 7011                        editor_width,
 7012                        window,
 7013                        cx,
 7014                    )
 7015                }
 7016            }
 7017            InlineCompletion::Edit {
 7018                display_mode: EditDisplayMode::Inline,
 7019                ..
 7020            } => None,
 7021            InlineCompletion::Edit {
 7022                display_mode: EditDisplayMode::TabAccept,
 7023                edits,
 7024                ..
 7025            } => {
 7026                let range = &edits.first()?.0;
 7027                let target_display_point = range.end.to_display_point(editor_snapshot);
 7028
 7029                self.render_edit_prediction_end_of_line_popover(
 7030                    "Accept",
 7031                    editor_snapshot,
 7032                    visible_row_range,
 7033                    target_display_point,
 7034                    line_height,
 7035                    scroll_pixel_position,
 7036                    content_origin,
 7037                    editor_width,
 7038                    window,
 7039                    cx,
 7040                )
 7041            }
 7042            InlineCompletion::Edit {
 7043                edits,
 7044                edit_preview,
 7045                display_mode: EditDisplayMode::DiffPopover,
 7046                snapshot,
 7047            } => self.render_edit_prediction_diff_popover(
 7048                text_bounds,
 7049                content_origin,
 7050                editor_snapshot,
 7051                visible_row_range,
 7052                line_layouts,
 7053                line_height,
 7054                scroll_pixel_position,
 7055                newest_selection_head,
 7056                editor_width,
 7057                style,
 7058                edits,
 7059                edit_preview,
 7060                snapshot,
 7061                window,
 7062                cx,
 7063            ),
 7064        }
 7065    }
 7066
 7067    fn render_edit_prediction_modifier_jump_popover(
 7068        &mut self,
 7069        text_bounds: &Bounds<Pixels>,
 7070        content_origin: gpui::Point<Pixels>,
 7071        visible_row_range: Range<DisplayRow>,
 7072        line_layouts: &[LineWithInvisibles],
 7073        line_height: Pixels,
 7074        scroll_pixel_position: gpui::Point<Pixels>,
 7075        newest_selection_head: Option<DisplayPoint>,
 7076        target_display_point: DisplayPoint,
 7077        window: &mut Window,
 7078        cx: &mut App,
 7079    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7080        let scrolled_content_origin =
 7081            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 7082
 7083        const SCROLL_PADDING_Y: Pixels = px(12.);
 7084
 7085        if target_display_point.row() < visible_row_range.start {
 7086            return self.render_edit_prediction_scroll_popover(
 7087                |_| SCROLL_PADDING_Y,
 7088                IconName::ArrowUp,
 7089                visible_row_range,
 7090                line_layouts,
 7091                newest_selection_head,
 7092                scrolled_content_origin,
 7093                window,
 7094                cx,
 7095            );
 7096        } else if target_display_point.row() >= visible_row_range.end {
 7097            return self.render_edit_prediction_scroll_popover(
 7098                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 7099                IconName::ArrowDown,
 7100                visible_row_range,
 7101                line_layouts,
 7102                newest_selection_head,
 7103                scrolled_content_origin,
 7104                window,
 7105                cx,
 7106            );
 7107        }
 7108
 7109        const POLE_WIDTH: Pixels = px(2.);
 7110
 7111        let line_layout =
 7112            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 7113        let target_column = target_display_point.column() as usize;
 7114
 7115        let target_x = line_layout.x_for_index(target_column);
 7116        let target_y =
 7117            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 7118
 7119        let flag_on_right = target_x < text_bounds.size.width / 2.;
 7120
 7121        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 7122        border_color.l += 0.001;
 7123
 7124        let mut element = v_flex()
 7125            .items_end()
 7126            .when(flag_on_right, |el| el.items_start())
 7127            .child(if flag_on_right {
 7128                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7129                    .rounded_bl(px(0.))
 7130                    .rounded_tl(px(0.))
 7131                    .border_l_2()
 7132                    .border_color(border_color)
 7133            } else {
 7134                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 7135                    .rounded_br(px(0.))
 7136                    .rounded_tr(px(0.))
 7137                    .border_r_2()
 7138                    .border_color(border_color)
 7139            })
 7140            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 7141            .into_any();
 7142
 7143        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7144
 7145        let mut origin = scrolled_content_origin + point(target_x, target_y)
 7146            - point(
 7147                if flag_on_right {
 7148                    POLE_WIDTH
 7149                } else {
 7150                    size.width - POLE_WIDTH
 7151                },
 7152                size.height - line_height,
 7153            );
 7154
 7155        origin.x = origin.x.max(content_origin.x);
 7156
 7157        element.prepaint_at(origin, window, cx);
 7158
 7159        Some((element, origin))
 7160    }
 7161
 7162    fn render_edit_prediction_scroll_popover(
 7163        &mut self,
 7164        to_y: impl Fn(Size<Pixels>) -> Pixels,
 7165        scroll_icon: IconName,
 7166        visible_row_range: Range<DisplayRow>,
 7167        line_layouts: &[LineWithInvisibles],
 7168        newest_selection_head: Option<DisplayPoint>,
 7169        scrolled_content_origin: gpui::Point<Pixels>,
 7170        window: &mut Window,
 7171        cx: &mut App,
 7172    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7173        let mut element = self
 7174            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 7175            .into_any();
 7176
 7177        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7178
 7179        let cursor = newest_selection_head?;
 7180        let cursor_row_layout =
 7181            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 7182        let cursor_column = cursor.column() as usize;
 7183
 7184        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 7185
 7186        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 7187
 7188        element.prepaint_at(origin, window, cx);
 7189        Some((element, origin))
 7190    }
 7191
 7192    fn render_edit_prediction_eager_jump_popover(
 7193        &mut self,
 7194        text_bounds: &Bounds<Pixels>,
 7195        content_origin: gpui::Point<Pixels>,
 7196        editor_snapshot: &EditorSnapshot,
 7197        visible_row_range: Range<DisplayRow>,
 7198        scroll_top: f32,
 7199        scroll_bottom: f32,
 7200        line_height: Pixels,
 7201        scroll_pixel_position: gpui::Point<Pixels>,
 7202        target_display_point: DisplayPoint,
 7203        editor_width: Pixels,
 7204        window: &mut Window,
 7205        cx: &mut App,
 7206    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7207        if target_display_point.row().as_f32() < scroll_top {
 7208            let mut element = self
 7209                .render_edit_prediction_line_popover(
 7210                    "Jump to Edit",
 7211                    Some(IconName::ArrowUp),
 7212                    window,
 7213                    cx,
 7214                )?
 7215                .into_any();
 7216
 7217            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7218            let offset = point(
 7219                (text_bounds.size.width - size.width) / 2.,
 7220                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7221            );
 7222
 7223            let origin = text_bounds.origin + offset;
 7224            element.prepaint_at(origin, window, cx);
 7225            Some((element, origin))
 7226        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 7227            let mut element = self
 7228                .render_edit_prediction_line_popover(
 7229                    "Jump to Edit",
 7230                    Some(IconName::ArrowDown),
 7231                    window,
 7232                    cx,
 7233                )?
 7234                .into_any();
 7235
 7236            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7237            let offset = point(
 7238                (text_bounds.size.width - size.width) / 2.,
 7239                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 7240            );
 7241
 7242            let origin = text_bounds.origin + offset;
 7243            element.prepaint_at(origin, window, cx);
 7244            Some((element, origin))
 7245        } else {
 7246            self.render_edit_prediction_end_of_line_popover(
 7247                "Jump to Edit",
 7248                editor_snapshot,
 7249                visible_row_range,
 7250                target_display_point,
 7251                line_height,
 7252                scroll_pixel_position,
 7253                content_origin,
 7254                editor_width,
 7255                window,
 7256                cx,
 7257            )
 7258        }
 7259    }
 7260
 7261    fn render_edit_prediction_end_of_line_popover(
 7262        self: &mut Editor,
 7263        label: &'static str,
 7264        editor_snapshot: &EditorSnapshot,
 7265        visible_row_range: Range<DisplayRow>,
 7266        target_display_point: DisplayPoint,
 7267        line_height: Pixels,
 7268        scroll_pixel_position: gpui::Point<Pixels>,
 7269        content_origin: gpui::Point<Pixels>,
 7270        editor_width: Pixels,
 7271        window: &mut Window,
 7272        cx: &mut App,
 7273    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7274        let target_line_end = DisplayPoint::new(
 7275            target_display_point.row(),
 7276            editor_snapshot.line_len(target_display_point.row()),
 7277        );
 7278
 7279        let mut element = self
 7280            .render_edit_prediction_line_popover(label, None, window, cx)?
 7281            .into_any();
 7282
 7283        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7284
 7285        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7286
 7287        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7288        let mut origin = start_point
 7289            + line_origin
 7290            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7291        origin.x = origin.x.max(content_origin.x);
 7292
 7293        let max_x = content_origin.x + editor_width - size.width;
 7294
 7295        if origin.x > max_x {
 7296            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7297
 7298            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7299                origin.y += offset;
 7300                IconName::ArrowUp
 7301            } else {
 7302                origin.y -= offset;
 7303                IconName::ArrowDown
 7304            };
 7305
 7306            element = self
 7307                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7308                .into_any();
 7309
 7310            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7311
 7312            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7313        }
 7314
 7315        element.prepaint_at(origin, window, cx);
 7316        Some((element, origin))
 7317    }
 7318
 7319    fn render_edit_prediction_diff_popover(
 7320        self: &Editor,
 7321        text_bounds: &Bounds<Pixels>,
 7322        content_origin: gpui::Point<Pixels>,
 7323        editor_snapshot: &EditorSnapshot,
 7324        visible_row_range: Range<DisplayRow>,
 7325        line_layouts: &[LineWithInvisibles],
 7326        line_height: Pixels,
 7327        scroll_pixel_position: gpui::Point<Pixels>,
 7328        newest_selection_head: Option<DisplayPoint>,
 7329        editor_width: Pixels,
 7330        style: &EditorStyle,
 7331        edits: &Vec<(Range<Anchor>, String)>,
 7332        edit_preview: &Option<language::EditPreview>,
 7333        snapshot: &language::BufferSnapshot,
 7334        window: &mut Window,
 7335        cx: &mut App,
 7336    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7337        let edit_start = edits
 7338            .first()
 7339            .unwrap()
 7340            .0
 7341            .start
 7342            .to_display_point(editor_snapshot);
 7343        let edit_end = edits
 7344            .last()
 7345            .unwrap()
 7346            .0
 7347            .end
 7348            .to_display_point(editor_snapshot);
 7349
 7350        let is_visible = visible_row_range.contains(&edit_start.row())
 7351            || visible_row_range.contains(&edit_end.row());
 7352        if !is_visible {
 7353            return None;
 7354        }
 7355
 7356        let highlighted_edits =
 7357            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7358
 7359        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7360        let line_count = highlighted_edits.text.lines().count();
 7361
 7362        const BORDER_WIDTH: Pixels = px(1.);
 7363
 7364        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7365        let has_keybind = keybind.is_some();
 7366
 7367        let mut element = h_flex()
 7368            .items_start()
 7369            .child(
 7370                h_flex()
 7371                    .bg(cx.theme().colors().editor_background)
 7372                    .border(BORDER_WIDTH)
 7373                    .shadow_sm()
 7374                    .border_color(cx.theme().colors().border)
 7375                    .rounded_l_lg()
 7376                    .when(line_count > 1, |el| el.rounded_br_lg())
 7377                    .pr_1()
 7378                    .child(styled_text),
 7379            )
 7380            .child(
 7381                h_flex()
 7382                    .h(line_height + BORDER_WIDTH * 2.)
 7383                    .px_1p5()
 7384                    .gap_1()
 7385                    // Workaround: For some reason, there's a gap if we don't do this
 7386                    .ml(-BORDER_WIDTH)
 7387                    .shadow(smallvec![gpui::BoxShadow {
 7388                        color: gpui::black().opacity(0.05),
 7389                        offset: point(px(1.), px(1.)),
 7390                        blur_radius: px(2.),
 7391                        spread_radius: px(0.),
 7392                    }])
 7393                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7394                    .border(BORDER_WIDTH)
 7395                    .border_color(cx.theme().colors().border)
 7396                    .rounded_r_lg()
 7397                    .id("edit_prediction_diff_popover_keybind")
 7398                    .when(!has_keybind, |el| {
 7399                        let status_colors = cx.theme().status();
 7400
 7401                        el.bg(status_colors.error_background)
 7402                            .border_color(status_colors.error.opacity(0.6))
 7403                            .child(Icon::new(IconName::Info).color(Color::Error))
 7404                            .cursor_default()
 7405                            .hoverable_tooltip(move |_window, cx| {
 7406                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7407                            })
 7408                    })
 7409                    .children(keybind),
 7410            )
 7411            .into_any();
 7412
 7413        let longest_row =
 7414            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7415        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7416            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7417        } else {
 7418            layout_line(
 7419                longest_row,
 7420                editor_snapshot,
 7421                style,
 7422                editor_width,
 7423                |_| false,
 7424                window,
 7425                cx,
 7426            )
 7427            .width
 7428        };
 7429
 7430        let viewport_bounds =
 7431            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7432                right: -EditorElement::SCROLLBAR_WIDTH,
 7433                ..Default::default()
 7434            });
 7435
 7436        let x_after_longest =
 7437            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7438                - scroll_pixel_position.x;
 7439
 7440        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7441
 7442        // Fully visible if it can be displayed within the window (allow overlapping other
 7443        // panes). However, this is only allowed if the popover starts within text_bounds.
 7444        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7445            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7446
 7447        let mut origin = if can_position_to_the_right {
 7448            point(
 7449                x_after_longest,
 7450                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7451                    - scroll_pixel_position.y,
 7452            )
 7453        } else {
 7454            let cursor_row = newest_selection_head.map(|head| head.row());
 7455            let above_edit = edit_start
 7456                .row()
 7457                .0
 7458                .checked_sub(line_count as u32)
 7459                .map(DisplayRow);
 7460            let below_edit = Some(edit_end.row() + 1);
 7461            let above_cursor =
 7462                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7463            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7464
 7465            // Place the edit popover adjacent to the edit if there is a location
 7466            // available that is onscreen and does not obscure the cursor. Otherwise,
 7467            // place it adjacent to the cursor.
 7468            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7469                .into_iter()
 7470                .flatten()
 7471                .find(|&start_row| {
 7472                    let end_row = start_row + line_count as u32;
 7473                    visible_row_range.contains(&start_row)
 7474                        && visible_row_range.contains(&end_row)
 7475                        && cursor_row.map_or(true, |cursor_row| {
 7476                            !((start_row..end_row).contains(&cursor_row))
 7477                        })
 7478                })?;
 7479
 7480            content_origin
 7481                + point(
 7482                    -scroll_pixel_position.x,
 7483                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7484                )
 7485        };
 7486
 7487        origin.x -= BORDER_WIDTH;
 7488
 7489        window.defer_draw(element, origin, 1);
 7490
 7491        // Do not return an element, since it will already be drawn due to defer_draw.
 7492        None
 7493    }
 7494
 7495    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7496        px(30.)
 7497    }
 7498
 7499    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7500        if self.read_only(cx) {
 7501            cx.theme().players().read_only()
 7502        } else {
 7503            self.style.as_ref().unwrap().local_player
 7504        }
 7505    }
 7506
 7507    fn render_edit_prediction_accept_keybind(
 7508        &self,
 7509        window: &mut Window,
 7510        cx: &App,
 7511    ) -> Option<AnyElement> {
 7512        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7513        let accept_keystroke = accept_binding.keystroke()?;
 7514
 7515        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7516
 7517        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7518            Color::Accent
 7519        } else {
 7520            Color::Muted
 7521        };
 7522
 7523        h_flex()
 7524            .px_0p5()
 7525            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7526            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7527            .text_size(TextSize::XSmall.rems(cx))
 7528            .child(h_flex().children(ui::render_modifiers(
 7529                &accept_keystroke.modifiers,
 7530                PlatformStyle::platform(),
 7531                Some(modifiers_color),
 7532                Some(IconSize::XSmall.rems().into()),
 7533                true,
 7534            )))
 7535            .when(is_platform_style_mac, |parent| {
 7536                parent.child(accept_keystroke.key.clone())
 7537            })
 7538            .when(!is_platform_style_mac, |parent| {
 7539                parent.child(
 7540                    Key::new(
 7541                        util::capitalize(&accept_keystroke.key),
 7542                        Some(Color::Default),
 7543                    )
 7544                    .size(Some(IconSize::XSmall.rems().into())),
 7545                )
 7546            })
 7547            .into_any()
 7548            .into()
 7549    }
 7550
 7551    fn render_edit_prediction_line_popover(
 7552        &self,
 7553        label: impl Into<SharedString>,
 7554        icon: Option<IconName>,
 7555        window: &mut Window,
 7556        cx: &App,
 7557    ) -> Option<Stateful<Div>> {
 7558        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7559
 7560        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7561        let has_keybind = keybind.is_some();
 7562
 7563        let result = h_flex()
 7564            .id("ep-line-popover")
 7565            .py_0p5()
 7566            .pl_1()
 7567            .pr(padding_right)
 7568            .gap_1()
 7569            .rounded_md()
 7570            .border_1()
 7571            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7572            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7573            .shadow_sm()
 7574            .when(!has_keybind, |el| {
 7575                let status_colors = cx.theme().status();
 7576
 7577                el.bg(status_colors.error_background)
 7578                    .border_color(status_colors.error.opacity(0.6))
 7579                    .pl_2()
 7580                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7581                    .cursor_default()
 7582                    .hoverable_tooltip(move |_window, cx| {
 7583                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7584                    })
 7585            })
 7586            .children(keybind)
 7587            .child(
 7588                Label::new(label)
 7589                    .size(LabelSize::Small)
 7590                    .when(!has_keybind, |el| {
 7591                        el.color(cx.theme().status().error.into()).strikethrough()
 7592                    }),
 7593            )
 7594            .when(!has_keybind, |el| {
 7595                el.child(
 7596                    h_flex().ml_1().child(
 7597                        Icon::new(IconName::Info)
 7598                            .size(IconSize::Small)
 7599                            .color(cx.theme().status().error.into()),
 7600                    ),
 7601                )
 7602            })
 7603            .when_some(icon, |element, icon| {
 7604                element.child(
 7605                    div()
 7606                        .mt(px(1.5))
 7607                        .child(Icon::new(icon).size(IconSize::Small)),
 7608                )
 7609            });
 7610
 7611        Some(result)
 7612    }
 7613
 7614    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7615        let accent_color = cx.theme().colors().text_accent;
 7616        let editor_bg_color = cx.theme().colors().editor_background;
 7617        editor_bg_color.blend(accent_color.opacity(0.1))
 7618    }
 7619
 7620    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7621        let accent_color = cx.theme().colors().text_accent;
 7622        let editor_bg_color = cx.theme().colors().editor_background;
 7623        editor_bg_color.blend(accent_color.opacity(0.6))
 7624    }
 7625
 7626    fn render_edit_prediction_cursor_popover(
 7627        &self,
 7628        min_width: Pixels,
 7629        max_width: Pixels,
 7630        cursor_point: Point,
 7631        style: &EditorStyle,
 7632        accept_keystroke: Option<&gpui::Keystroke>,
 7633        _window: &Window,
 7634        cx: &mut Context<Editor>,
 7635    ) -> Option<AnyElement> {
 7636        let provider = self.edit_prediction_provider.as_ref()?;
 7637
 7638        if provider.provider.needs_terms_acceptance(cx) {
 7639            return Some(
 7640                h_flex()
 7641                    .min_w(min_width)
 7642                    .flex_1()
 7643                    .px_2()
 7644                    .py_1()
 7645                    .gap_3()
 7646                    .elevation_2(cx)
 7647                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7648                    .id("accept-terms")
 7649                    .cursor_pointer()
 7650                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7651                    .on_click(cx.listener(|this, _event, window, cx| {
 7652                        cx.stop_propagation();
 7653                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7654                        window.dispatch_action(
 7655                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7656                            cx,
 7657                        );
 7658                    }))
 7659                    .child(
 7660                        h_flex()
 7661                            .flex_1()
 7662                            .gap_2()
 7663                            .child(Icon::new(IconName::ZedPredict))
 7664                            .child(Label::new("Accept Terms of Service"))
 7665                            .child(div().w_full())
 7666                            .child(
 7667                                Icon::new(IconName::ArrowUpRight)
 7668                                    .color(Color::Muted)
 7669                                    .size(IconSize::Small),
 7670                            )
 7671                            .into_any_element(),
 7672                    )
 7673                    .into_any(),
 7674            );
 7675        }
 7676
 7677        let is_refreshing = provider.provider.is_refreshing(cx);
 7678
 7679        fn pending_completion_container() -> Div {
 7680            h_flex()
 7681                .h_full()
 7682                .flex_1()
 7683                .gap_2()
 7684                .child(Icon::new(IconName::ZedPredict))
 7685        }
 7686
 7687        let completion = match &self.active_inline_completion {
 7688            Some(prediction) => {
 7689                if !self.has_visible_completions_menu() {
 7690                    const RADIUS: Pixels = px(6.);
 7691                    const BORDER_WIDTH: Pixels = px(1.);
 7692
 7693                    return Some(
 7694                        h_flex()
 7695                            .elevation_2(cx)
 7696                            .border(BORDER_WIDTH)
 7697                            .border_color(cx.theme().colors().border)
 7698                            .when(accept_keystroke.is_none(), |el| {
 7699                                el.border_color(cx.theme().status().error)
 7700                            })
 7701                            .rounded(RADIUS)
 7702                            .rounded_tl(px(0.))
 7703                            .overflow_hidden()
 7704                            .child(div().px_1p5().child(match &prediction.completion {
 7705                                InlineCompletion::Move { target, snapshot } => {
 7706                                    use text::ToPoint as _;
 7707                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7708                                    {
 7709                                        Icon::new(IconName::ZedPredictDown)
 7710                                    } else {
 7711                                        Icon::new(IconName::ZedPredictUp)
 7712                                    }
 7713                                }
 7714                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7715                            }))
 7716                            .child(
 7717                                h_flex()
 7718                                    .gap_1()
 7719                                    .py_1()
 7720                                    .px_2()
 7721                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7722                                    .border_l_1()
 7723                                    .border_color(cx.theme().colors().border)
 7724                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7725                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7726                                        el.child(
 7727                                            Label::new("Hold")
 7728                                                .size(LabelSize::Small)
 7729                                                .when(accept_keystroke.is_none(), |el| {
 7730                                                    el.strikethrough()
 7731                                                })
 7732                                                .line_height_style(LineHeightStyle::UiLabel),
 7733                                        )
 7734                                    })
 7735                                    .id("edit_prediction_cursor_popover_keybind")
 7736                                    .when(accept_keystroke.is_none(), |el| {
 7737                                        let status_colors = cx.theme().status();
 7738
 7739                                        el.bg(status_colors.error_background)
 7740                                            .border_color(status_colors.error.opacity(0.6))
 7741                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7742                                            .cursor_default()
 7743                                            .hoverable_tooltip(move |_window, cx| {
 7744                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7745                                                    .into()
 7746                                            })
 7747                                    })
 7748                                    .when_some(
 7749                                        accept_keystroke.as_ref(),
 7750                                        |el, accept_keystroke| {
 7751                                            el.child(h_flex().children(ui::render_modifiers(
 7752                                                &accept_keystroke.modifiers,
 7753                                                PlatformStyle::platform(),
 7754                                                Some(Color::Default),
 7755                                                Some(IconSize::XSmall.rems().into()),
 7756                                                false,
 7757                                            )))
 7758                                        },
 7759                                    ),
 7760                            )
 7761                            .into_any(),
 7762                    );
 7763                }
 7764
 7765                self.render_edit_prediction_cursor_popover_preview(
 7766                    prediction,
 7767                    cursor_point,
 7768                    style,
 7769                    cx,
 7770                )?
 7771            }
 7772
 7773            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7774                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7775                    stale_completion,
 7776                    cursor_point,
 7777                    style,
 7778                    cx,
 7779                )?,
 7780
 7781                None => {
 7782                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7783                }
 7784            },
 7785
 7786            None => pending_completion_container().child(Label::new("No Prediction")),
 7787        };
 7788
 7789        let completion = if is_refreshing {
 7790            completion
 7791                .with_animation(
 7792                    "loading-completion",
 7793                    Animation::new(Duration::from_secs(2))
 7794                        .repeat()
 7795                        .with_easing(pulsating_between(0.4, 0.8)),
 7796                    |label, delta| label.opacity(delta),
 7797                )
 7798                .into_any_element()
 7799        } else {
 7800            completion.into_any_element()
 7801        };
 7802
 7803        let has_completion = self.active_inline_completion.is_some();
 7804
 7805        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7806        Some(
 7807            h_flex()
 7808                .min_w(min_width)
 7809                .max_w(max_width)
 7810                .flex_1()
 7811                .elevation_2(cx)
 7812                .border_color(cx.theme().colors().border)
 7813                .child(
 7814                    div()
 7815                        .flex_1()
 7816                        .py_1()
 7817                        .px_2()
 7818                        .overflow_hidden()
 7819                        .child(completion),
 7820                )
 7821                .when_some(accept_keystroke, |el, accept_keystroke| {
 7822                    if !accept_keystroke.modifiers.modified() {
 7823                        return el;
 7824                    }
 7825
 7826                    el.child(
 7827                        h_flex()
 7828                            .h_full()
 7829                            .border_l_1()
 7830                            .rounded_r_lg()
 7831                            .border_color(cx.theme().colors().border)
 7832                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7833                            .gap_1()
 7834                            .py_1()
 7835                            .px_2()
 7836                            .child(
 7837                                h_flex()
 7838                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7839                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7840                                    .child(h_flex().children(ui::render_modifiers(
 7841                                        &accept_keystroke.modifiers,
 7842                                        PlatformStyle::platform(),
 7843                                        Some(if !has_completion {
 7844                                            Color::Muted
 7845                                        } else {
 7846                                            Color::Default
 7847                                        }),
 7848                                        None,
 7849                                        false,
 7850                                    ))),
 7851                            )
 7852                            .child(Label::new("Preview").into_any_element())
 7853                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7854                    )
 7855                })
 7856                .into_any(),
 7857        )
 7858    }
 7859
 7860    fn render_edit_prediction_cursor_popover_preview(
 7861        &self,
 7862        completion: &InlineCompletionState,
 7863        cursor_point: Point,
 7864        style: &EditorStyle,
 7865        cx: &mut Context<Editor>,
 7866    ) -> Option<Div> {
 7867        use text::ToPoint as _;
 7868
 7869        fn render_relative_row_jump(
 7870            prefix: impl Into<String>,
 7871            current_row: u32,
 7872            target_row: u32,
 7873        ) -> Div {
 7874            let (row_diff, arrow) = if target_row < current_row {
 7875                (current_row - target_row, IconName::ArrowUp)
 7876            } else {
 7877                (target_row - current_row, IconName::ArrowDown)
 7878            };
 7879
 7880            h_flex()
 7881                .child(
 7882                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7883                        .color(Color::Muted)
 7884                        .size(LabelSize::Small),
 7885                )
 7886                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7887        }
 7888
 7889        match &completion.completion {
 7890            InlineCompletion::Move {
 7891                target, snapshot, ..
 7892            } => Some(
 7893                h_flex()
 7894                    .px_2()
 7895                    .gap_2()
 7896                    .flex_1()
 7897                    .child(
 7898                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7899                            Icon::new(IconName::ZedPredictDown)
 7900                        } else {
 7901                            Icon::new(IconName::ZedPredictUp)
 7902                        },
 7903                    )
 7904                    .child(Label::new("Jump to Edit")),
 7905            ),
 7906
 7907            InlineCompletion::Edit {
 7908                edits,
 7909                edit_preview,
 7910                snapshot,
 7911                display_mode: _,
 7912            } => {
 7913                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7914
 7915                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7916                    &snapshot,
 7917                    &edits,
 7918                    edit_preview.as_ref()?,
 7919                    true,
 7920                    cx,
 7921                )
 7922                .first_line_preview();
 7923
 7924                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7925                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7926
 7927                let preview = h_flex()
 7928                    .gap_1()
 7929                    .min_w_16()
 7930                    .child(styled_text)
 7931                    .when(has_more_lines, |parent| parent.child(""));
 7932
 7933                let left = if first_edit_row != cursor_point.row {
 7934                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7935                        .into_any_element()
 7936                } else {
 7937                    Icon::new(IconName::ZedPredict).into_any_element()
 7938                };
 7939
 7940                Some(
 7941                    h_flex()
 7942                        .h_full()
 7943                        .flex_1()
 7944                        .gap_2()
 7945                        .pr_1()
 7946                        .overflow_x_hidden()
 7947                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7948                        .child(left)
 7949                        .child(preview),
 7950                )
 7951            }
 7952        }
 7953    }
 7954
 7955    fn render_context_menu(
 7956        &self,
 7957        style: &EditorStyle,
 7958        max_height_in_lines: u32,
 7959        window: &mut Window,
 7960        cx: &mut Context<Editor>,
 7961    ) -> Option<AnyElement> {
 7962        let menu = self.context_menu.borrow();
 7963        let menu = menu.as_ref()?;
 7964        if !menu.visible() {
 7965            return None;
 7966        };
 7967        Some(menu.render(style, max_height_in_lines, window, cx))
 7968    }
 7969
 7970    fn render_context_menu_aside(
 7971        &mut self,
 7972        max_size: Size<Pixels>,
 7973        window: &mut Window,
 7974        cx: &mut Context<Editor>,
 7975    ) -> Option<AnyElement> {
 7976        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7977            if menu.visible() {
 7978                menu.render_aside(self, max_size, window, cx)
 7979            } else {
 7980                None
 7981            }
 7982        })
 7983    }
 7984
 7985    fn hide_context_menu(
 7986        &mut self,
 7987        window: &mut Window,
 7988        cx: &mut Context<Self>,
 7989    ) -> Option<CodeContextMenu> {
 7990        cx.notify();
 7991        self.completion_tasks.clear();
 7992        let context_menu = self.context_menu.borrow_mut().take();
 7993        self.stale_inline_completion_in_menu.take();
 7994        self.update_visible_inline_completion(window, cx);
 7995        context_menu
 7996    }
 7997
 7998    fn show_snippet_choices(
 7999        &mut self,
 8000        choices: &Vec<String>,
 8001        selection: Range<Anchor>,
 8002        cx: &mut Context<Self>,
 8003    ) {
 8004        if selection.start.buffer_id.is_none() {
 8005            return;
 8006        }
 8007        let buffer_id = selection.start.buffer_id.unwrap();
 8008        let buffer = self.buffer().read(cx).buffer(buffer_id);
 8009        let id = post_inc(&mut self.next_completion_id);
 8010
 8011        if let Some(buffer) = buffer {
 8012            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 8013                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 8014            ));
 8015        }
 8016    }
 8017
 8018    pub fn insert_snippet(
 8019        &mut self,
 8020        insertion_ranges: &[Range<usize>],
 8021        snippet: Snippet,
 8022        window: &mut Window,
 8023        cx: &mut Context<Self>,
 8024    ) -> Result<()> {
 8025        struct Tabstop<T> {
 8026            is_end_tabstop: bool,
 8027            ranges: Vec<Range<T>>,
 8028            choices: Option<Vec<String>>,
 8029        }
 8030
 8031        let tabstops = self.buffer.update(cx, |buffer, cx| {
 8032            let snippet_text: Arc<str> = snippet.text.clone().into();
 8033            let edits = insertion_ranges
 8034                .iter()
 8035                .cloned()
 8036                .map(|range| (range, snippet_text.clone()));
 8037            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 8038
 8039            let snapshot = &*buffer.read(cx);
 8040            let snippet = &snippet;
 8041            snippet
 8042                .tabstops
 8043                .iter()
 8044                .map(|tabstop| {
 8045                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 8046                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 8047                    });
 8048                    let mut tabstop_ranges = tabstop
 8049                        .ranges
 8050                        .iter()
 8051                        .flat_map(|tabstop_range| {
 8052                            let mut delta = 0_isize;
 8053                            insertion_ranges.iter().map(move |insertion_range| {
 8054                                let insertion_start = insertion_range.start as isize + delta;
 8055                                delta +=
 8056                                    snippet.text.len() as isize - insertion_range.len() as isize;
 8057
 8058                                let start = ((insertion_start + tabstop_range.start) as usize)
 8059                                    .min(snapshot.len());
 8060                                let end = ((insertion_start + tabstop_range.end) as usize)
 8061                                    .min(snapshot.len());
 8062                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 8063                            })
 8064                        })
 8065                        .collect::<Vec<_>>();
 8066                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 8067
 8068                    Tabstop {
 8069                        is_end_tabstop,
 8070                        ranges: tabstop_ranges,
 8071                        choices: tabstop.choices.clone(),
 8072                    }
 8073                })
 8074                .collect::<Vec<_>>()
 8075        });
 8076        if let Some(tabstop) = tabstops.first() {
 8077            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8078                s.select_ranges(tabstop.ranges.iter().cloned());
 8079            });
 8080
 8081            if let Some(choices) = &tabstop.choices {
 8082                if let Some(selection) = tabstop.ranges.first() {
 8083                    self.show_snippet_choices(choices, selection.clone(), cx)
 8084                }
 8085            }
 8086
 8087            // If we're already at the last tabstop and it's at the end of the snippet,
 8088            // we're done, we don't need to keep the state around.
 8089            if !tabstop.is_end_tabstop {
 8090                let choices = tabstops
 8091                    .iter()
 8092                    .map(|tabstop| tabstop.choices.clone())
 8093                    .collect();
 8094
 8095                let ranges = tabstops
 8096                    .into_iter()
 8097                    .map(|tabstop| tabstop.ranges)
 8098                    .collect::<Vec<_>>();
 8099
 8100                self.snippet_stack.push(SnippetState {
 8101                    active_index: 0,
 8102                    ranges,
 8103                    choices,
 8104                });
 8105            }
 8106
 8107            // Check whether the just-entered snippet ends with an auto-closable bracket.
 8108            if self.autoclose_regions.is_empty() {
 8109                let snapshot = self.buffer.read(cx).snapshot(cx);
 8110                for selection in &mut self.selections.all::<Point>(cx) {
 8111                    let selection_head = selection.head();
 8112                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 8113                        continue;
 8114                    };
 8115
 8116                    let mut bracket_pair = None;
 8117                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 8118                    let prev_chars = snapshot
 8119                        .reversed_chars_at(selection_head)
 8120                        .collect::<String>();
 8121                    for (pair, enabled) in scope.brackets() {
 8122                        if enabled
 8123                            && pair.close
 8124                            && prev_chars.starts_with(pair.start.as_str())
 8125                            && next_chars.starts_with(pair.end.as_str())
 8126                        {
 8127                            bracket_pair = Some(pair.clone());
 8128                            break;
 8129                        }
 8130                    }
 8131                    if let Some(pair) = bracket_pair {
 8132                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 8133                        let autoclose_enabled =
 8134                            self.use_autoclose && snapshot_settings.use_autoclose;
 8135                        if autoclose_enabled {
 8136                            let start = snapshot.anchor_after(selection_head);
 8137                            let end = snapshot.anchor_after(selection_head);
 8138                            self.autoclose_regions.push(AutocloseRegion {
 8139                                selection_id: selection.id,
 8140                                range: start..end,
 8141                                pair,
 8142                            });
 8143                        }
 8144                    }
 8145                }
 8146            }
 8147        }
 8148        Ok(())
 8149    }
 8150
 8151    pub fn move_to_next_snippet_tabstop(
 8152        &mut self,
 8153        window: &mut Window,
 8154        cx: &mut Context<Self>,
 8155    ) -> bool {
 8156        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 8157    }
 8158
 8159    pub fn move_to_prev_snippet_tabstop(
 8160        &mut self,
 8161        window: &mut Window,
 8162        cx: &mut Context<Self>,
 8163    ) -> bool {
 8164        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 8165    }
 8166
 8167    pub fn move_to_snippet_tabstop(
 8168        &mut self,
 8169        bias: Bias,
 8170        window: &mut Window,
 8171        cx: &mut Context<Self>,
 8172    ) -> bool {
 8173        if let Some(mut snippet) = self.snippet_stack.pop() {
 8174            match bias {
 8175                Bias::Left => {
 8176                    if snippet.active_index > 0 {
 8177                        snippet.active_index -= 1;
 8178                    } else {
 8179                        self.snippet_stack.push(snippet);
 8180                        return false;
 8181                    }
 8182                }
 8183                Bias::Right => {
 8184                    if snippet.active_index + 1 < snippet.ranges.len() {
 8185                        snippet.active_index += 1;
 8186                    } else {
 8187                        self.snippet_stack.push(snippet);
 8188                        return false;
 8189                    }
 8190                }
 8191            }
 8192            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 8193                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8194                    s.select_anchor_ranges(current_ranges.iter().cloned())
 8195                });
 8196
 8197                if let Some(choices) = &snippet.choices[snippet.active_index] {
 8198                    if let Some(selection) = current_ranges.first() {
 8199                        self.show_snippet_choices(&choices, selection.clone(), cx);
 8200                    }
 8201                }
 8202
 8203                // If snippet state is not at the last tabstop, push it back on the stack
 8204                if snippet.active_index + 1 < snippet.ranges.len() {
 8205                    self.snippet_stack.push(snippet);
 8206                }
 8207                return true;
 8208            }
 8209        }
 8210
 8211        false
 8212    }
 8213
 8214    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 8215        self.transact(window, cx, |this, window, cx| {
 8216            this.select_all(&SelectAll, window, cx);
 8217            this.insert("", window, cx);
 8218        });
 8219    }
 8220
 8221    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 8222        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8223        self.transact(window, cx, |this, window, cx| {
 8224            this.select_autoclose_pair(window, cx);
 8225            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 8226            if !this.linked_edit_ranges.is_empty() {
 8227                let selections = this.selections.all::<MultiBufferPoint>(cx);
 8228                let snapshot = this.buffer.read(cx).snapshot(cx);
 8229
 8230                for selection in selections.iter() {
 8231                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 8232                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 8233                    if selection_start.buffer_id != selection_end.buffer_id {
 8234                        continue;
 8235                    }
 8236                    if let Some(ranges) =
 8237                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 8238                    {
 8239                        for (buffer, entries) in ranges {
 8240                            linked_ranges.entry(buffer).or_default().extend(entries);
 8241                        }
 8242                    }
 8243                }
 8244            }
 8245
 8246            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8247            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 8248            for selection in &mut selections {
 8249                if selection.is_empty() {
 8250                    let old_head = selection.head();
 8251                    let mut new_head =
 8252                        movement::left(&display_map, old_head.to_display_point(&display_map))
 8253                            .to_point(&display_map);
 8254                    if let Some((buffer, line_buffer_range)) = display_map
 8255                        .buffer_snapshot
 8256                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8257                    {
 8258                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8259                        let indent_len = match indent_size.kind {
 8260                            IndentKind::Space => {
 8261                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8262                            }
 8263                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8264                        };
 8265                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8266                            let indent_len = indent_len.get();
 8267                            new_head = cmp::min(
 8268                                new_head,
 8269                                MultiBufferPoint::new(
 8270                                    old_head.row,
 8271                                    ((old_head.column - 1) / indent_len) * indent_len,
 8272                                ),
 8273                            );
 8274                        }
 8275                    }
 8276
 8277                    selection.set_head(new_head, SelectionGoal::None);
 8278                }
 8279            }
 8280
 8281            this.signature_help_state.set_backspace_pressed(true);
 8282            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8283                s.select(selections)
 8284            });
 8285            this.insert("", window, cx);
 8286            let empty_str: Arc<str> = Arc::from("");
 8287            for (buffer, edits) in linked_ranges {
 8288                let snapshot = buffer.read(cx).snapshot();
 8289                use text::ToPoint as TP;
 8290
 8291                let edits = edits
 8292                    .into_iter()
 8293                    .map(|range| {
 8294                        let end_point = TP::to_point(&range.end, &snapshot);
 8295                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8296
 8297                        if end_point == start_point {
 8298                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8299                                .saturating_sub(1);
 8300                            start_point =
 8301                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8302                        };
 8303
 8304                        (start_point..end_point, empty_str.clone())
 8305                    })
 8306                    .sorted_by_key(|(range, _)| range.start)
 8307                    .collect::<Vec<_>>();
 8308                buffer.update(cx, |this, cx| {
 8309                    this.edit(edits, None, cx);
 8310                })
 8311            }
 8312            this.refresh_inline_completion(true, false, window, cx);
 8313            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8314        });
 8315    }
 8316
 8317    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8318        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8319        self.transact(window, cx, |this, window, cx| {
 8320            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8321                s.move_with(|map, selection| {
 8322                    if selection.is_empty() {
 8323                        let cursor = movement::right(map, selection.head());
 8324                        selection.end = cursor;
 8325                        selection.reversed = true;
 8326                        selection.goal = SelectionGoal::None;
 8327                    }
 8328                })
 8329            });
 8330            this.insert("", window, cx);
 8331            this.refresh_inline_completion(true, false, window, cx);
 8332        });
 8333    }
 8334
 8335    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8336        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8337        if self.move_to_prev_snippet_tabstop(window, cx) {
 8338            return;
 8339        }
 8340        self.outdent(&Outdent, window, cx);
 8341    }
 8342
 8343    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8344        if self.move_to_next_snippet_tabstop(window, cx) {
 8345            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8346            return;
 8347        }
 8348        if self.read_only(cx) {
 8349            return;
 8350        }
 8351        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8352        let mut selections = self.selections.all_adjusted(cx);
 8353        let buffer = self.buffer.read(cx);
 8354        let snapshot = buffer.snapshot(cx);
 8355        let rows_iter = selections.iter().map(|s| s.head().row);
 8356        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8357
 8358        let mut edits = Vec::new();
 8359        let mut prev_edited_row = 0;
 8360        let mut row_delta = 0;
 8361        for selection in &mut selections {
 8362            if selection.start.row != prev_edited_row {
 8363                row_delta = 0;
 8364            }
 8365            prev_edited_row = selection.end.row;
 8366
 8367            // If the selection is non-empty, then increase the indentation of the selected lines.
 8368            if !selection.is_empty() {
 8369                row_delta =
 8370                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8371                continue;
 8372            }
 8373
 8374            // If the selection is empty and the cursor is in the leading whitespace before the
 8375            // suggested indentation, then auto-indent the line.
 8376            let cursor = selection.head();
 8377            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8378            if let Some(suggested_indent) =
 8379                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8380            {
 8381                if cursor.column < suggested_indent.len
 8382                    && cursor.column <= current_indent.len
 8383                    && current_indent.len <= suggested_indent.len
 8384                {
 8385                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8386                    selection.end = selection.start;
 8387                    if row_delta == 0 {
 8388                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8389                            cursor.row,
 8390                            current_indent,
 8391                            suggested_indent,
 8392                        ));
 8393                        row_delta = suggested_indent.len - current_indent.len;
 8394                    }
 8395                    continue;
 8396                }
 8397            }
 8398
 8399            // Otherwise, insert a hard or soft tab.
 8400            let settings = buffer.language_settings_at(cursor, cx);
 8401            let tab_size = if settings.hard_tabs {
 8402                IndentSize::tab()
 8403            } else {
 8404                let tab_size = settings.tab_size.get();
 8405                let indent_remainder = snapshot
 8406                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8407                    .flat_map(str::chars)
 8408                    .fold(row_delta % tab_size, |counter: u32, c| {
 8409                        if c == '\t' {
 8410                            0
 8411                        } else {
 8412                            (counter + 1) % tab_size
 8413                        }
 8414                    });
 8415
 8416                let chars_to_next_tab_stop = tab_size - indent_remainder;
 8417                IndentSize::spaces(chars_to_next_tab_stop)
 8418            };
 8419            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8420            selection.end = selection.start;
 8421            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8422            row_delta += tab_size.len;
 8423        }
 8424
 8425        self.transact(window, cx, |this, window, cx| {
 8426            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8427            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8428                s.select(selections)
 8429            });
 8430            this.refresh_inline_completion(true, false, window, cx);
 8431        });
 8432    }
 8433
 8434    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8435        if self.read_only(cx) {
 8436            return;
 8437        }
 8438        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8439        let mut selections = self.selections.all::<Point>(cx);
 8440        let mut prev_edited_row = 0;
 8441        let mut row_delta = 0;
 8442        let mut edits = Vec::new();
 8443        let buffer = self.buffer.read(cx);
 8444        let snapshot = buffer.snapshot(cx);
 8445        for selection in &mut selections {
 8446            if selection.start.row != prev_edited_row {
 8447                row_delta = 0;
 8448            }
 8449            prev_edited_row = selection.end.row;
 8450
 8451            row_delta =
 8452                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8453        }
 8454
 8455        self.transact(window, cx, |this, window, cx| {
 8456            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8457            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8458                s.select(selections)
 8459            });
 8460        });
 8461    }
 8462
 8463    fn indent_selection(
 8464        buffer: &MultiBuffer,
 8465        snapshot: &MultiBufferSnapshot,
 8466        selection: &mut Selection<Point>,
 8467        edits: &mut Vec<(Range<Point>, String)>,
 8468        delta_for_start_row: u32,
 8469        cx: &App,
 8470    ) -> u32 {
 8471        let settings = buffer.language_settings_at(selection.start, cx);
 8472        let tab_size = settings.tab_size.get();
 8473        let indent_kind = if settings.hard_tabs {
 8474            IndentKind::Tab
 8475        } else {
 8476            IndentKind::Space
 8477        };
 8478        let mut start_row = selection.start.row;
 8479        let mut end_row = selection.end.row + 1;
 8480
 8481        // If a selection ends at the beginning of a line, don't indent
 8482        // that last line.
 8483        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8484            end_row -= 1;
 8485        }
 8486
 8487        // Avoid re-indenting a row that has already been indented by a
 8488        // previous selection, but still update this selection's column
 8489        // to reflect that indentation.
 8490        if delta_for_start_row > 0 {
 8491            start_row += 1;
 8492            selection.start.column += delta_for_start_row;
 8493            if selection.end.row == selection.start.row {
 8494                selection.end.column += delta_for_start_row;
 8495            }
 8496        }
 8497
 8498        let mut delta_for_end_row = 0;
 8499        let has_multiple_rows = start_row + 1 != end_row;
 8500        for row in start_row..end_row {
 8501            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8502            let indent_delta = match (current_indent.kind, indent_kind) {
 8503                (IndentKind::Space, IndentKind::Space) => {
 8504                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8505                    IndentSize::spaces(columns_to_next_tab_stop)
 8506                }
 8507                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8508                (_, IndentKind::Tab) => IndentSize::tab(),
 8509            };
 8510
 8511            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8512                0
 8513            } else {
 8514                selection.start.column
 8515            };
 8516            let row_start = Point::new(row, start);
 8517            edits.push((
 8518                row_start..row_start,
 8519                indent_delta.chars().collect::<String>(),
 8520            ));
 8521
 8522            // Update this selection's endpoints to reflect the indentation.
 8523            if row == selection.start.row {
 8524                selection.start.column += indent_delta.len;
 8525            }
 8526            if row == selection.end.row {
 8527                selection.end.column += indent_delta.len;
 8528                delta_for_end_row = indent_delta.len;
 8529            }
 8530        }
 8531
 8532        if selection.start.row == selection.end.row {
 8533            delta_for_start_row + delta_for_end_row
 8534        } else {
 8535            delta_for_end_row
 8536        }
 8537    }
 8538
 8539    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8540        if self.read_only(cx) {
 8541            return;
 8542        }
 8543        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8544        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8545        let selections = self.selections.all::<Point>(cx);
 8546        let mut deletion_ranges = Vec::new();
 8547        let mut last_outdent = None;
 8548        {
 8549            let buffer = self.buffer.read(cx);
 8550            let snapshot = buffer.snapshot(cx);
 8551            for selection in &selections {
 8552                let settings = buffer.language_settings_at(selection.start, cx);
 8553                let tab_size = settings.tab_size.get();
 8554                let mut rows = selection.spanned_rows(false, &display_map);
 8555
 8556                // Avoid re-outdenting a row that has already been outdented by a
 8557                // previous selection.
 8558                if let Some(last_row) = last_outdent {
 8559                    if last_row == rows.start {
 8560                        rows.start = rows.start.next_row();
 8561                    }
 8562                }
 8563                let has_multiple_rows = rows.len() > 1;
 8564                for row in rows.iter_rows() {
 8565                    let indent_size = snapshot.indent_size_for_line(row);
 8566                    if indent_size.len > 0 {
 8567                        let deletion_len = match indent_size.kind {
 8568                            IndentKind::Space => {
 8569                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8570                                if columns_to_prev_tab_stop == 0 {
 8571                                    tab_size
 8572                                } else {
 8573                                    columns_to_prev_tab_stop
 8574                                }
 8575                            }
 8576                            IndentKind::Tab => 1,
 8577                        };
 8578                        let start = if has_multiple_rows
 8579                            || deletion_len > selection.start.column
 8580                            || indent_size.len < selection.start.column
 8581                        {
 8582                            0
 8583                        } else {
 8584                            selection.start.column - deletion_len
 8585                        };
 8586                        deletion_ranges.push(
 8587                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8588                        );
 8589                        last_outdent = Some(row);
 8590                    }
 8591                }
 8592            }
 8593        }
 8594
 8595        self.transact(window, cx, |this, window, cx| {
 8596            this.buffer.update(cx, |buffer, cx| {
 8597                let empty_str: Arc<str> = Arc::default();
 8598                buffer.edit(
 8599                    deletion_ranges
 8600                        .into_iter()
 8601                        .map(|range| (range, empty_str.clone())),
 8602                    None,
 8603                    cx,
 8604                );
 8605            });
 8606            let selections = this.selections.all::<usize>(cx);
 8607            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8608                s.select(selections)
 8609            });
 8610        });
 8611    }
 8612
 8613    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8614        if self.read_only(cx) {
 8615            return;
 8616        }
 8617        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8618        let selections = self
 8619            .selections
 8620            .all::<usize>(cx)
 8621            .into_iter()
 8622            .map(|s| s.range());
 8623
 8624        self.transact(window, cx, |this, window, cx| {
 8625            this.buffer.update(cx, |buffer, cx| {
 8626                buffer.autoindent_ranges(selections, cx);
 8627            });
 8628            let selections = this.selections.all::<usize>(cx);
 8629            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8630                s.select(selections)
 8631            });
 8632        });
 8633    }
 8634
 8635    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8636        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8637        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8638        let selections = self.selections.all::<Point>(cx);
 8639
 8640        let mut new_cursors = Vec::new();
 8641        let mut edit_ranges = Vec::new();
 8642        let mut selections = selections.iter().peekable();
 8643        while let Some(selection) = selections.next() {
 8644            let mut rows = selection.spanned_rows(false, &display_map);
 8645            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8646
 8647            // Accumulate contiguous regions of rows that we want to delete.
 8648            while let Some(next_selection) = selections.peek() {
 8649                let next_rows = next_selection.spanned_rows(false, &display_map);
 8650                if next_rows.start <= rows.end {
 8651                    rows.end = next_rows.end;
 8652                    selections.next().unwrap();
 8653                } else {
 8654                    break;
 8655                }
 8656            }
 8657
 8658            let buffer = &display_map.buffer_snapshot;
 8659            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8660            let edit_end;
 8661            let cursor_buffer_row;
 8662            if buffer.max_point().row >= rows.end.0 {
 8663                // If there's a line after the range, delete the \n from the end of the row range
 8664                // and position the cursor on the next line.
 8665                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8666                cursor_buffer_row = rows.end;
 8667            } else {
 8668                // If there isn't a line after the range, delete the \n from the line before the
 8669                // start of the row range and position the cursor there.
 8670                edit_start = edit_start.saturating_sub(1);
 8671                edit_end = buffer.len();
 8672                cursor_buffer_row = rows.start.previous_row();
 8673            }
 8674
 8675            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8676            *cursor.column_mut() =
 8677                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8678
 8679            new_cursors.push((
 8680                selection.id,
 8681                buffer.anchor_after(cursor.to_point(&display_map)),
 8682            ));
 8683            edit_ranges.push(edit_start..edit_end);
 8684        }
 8685
 8686        self.transact(window, cx, |this, window, cx| {
 8687            let buffer = this.buffer.update(cx, |buffer, cx| {
 8688                let empty_str: Arc<str> = Arc::default();
 8689                buffer.edit(
 8690                    edit_ranges
 8691                        .into_iter()
 8692                        .map(|range| (range, empty_str.clone())),
 8693                    None,
 8694                    cx,
 8695                );
 8696                buffer.snapshot(cx)
 8697            });
 8698            let new_selections = new_cursors
 8699                .into_iter()
 8700                .map(|(id, cursor)| {
 8701                    let cursor = cursor.to_point(&buffer);
 8702                    Selection {
 8703                        id,
 8704                        start: cursor,
 8705                        end: cursor,
 8706                        reversed: false,
 8707                        goal: SelectionGoal::None,
 8708                    }
 8709                })
 8710                .collect();
 8711
 8712            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8713                s.select(new_selections);
 8714            });
 8715        });
 8716    }
 8717
 8718    pub fn join_lines_impl(
 8719        &mut self,
 8720        insert_whitespace: bool,
 8721        window: &mut Window,
 8722        cx: &mut Context<Self>,
 8723    ) {
 8724        if self.read_only(cx) {
 8725            return;
 8726        }
 8727        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8728        for selection in self.selections.all::<Point>(cx) {
 8729            let start = MultiBufferRow(selection.start.row);
 8730            // Treat single line selections as if they include the next line. Otherwise this action
 8731            // would do nothing for single line selections individual cursors.
 8732            let end = if selection.start.row == selection.end.row {
 8733                MultiBufferRow(selection.start.row + 1)
 8734            } else {
 8735                MultiBufferRow(selection.end.row)
 8736            };
 8737
 8738            if let Some(last_row_range) = row_ranges.last_mut() {
 8739                if start <= last_row_range.end {
 8740                    last_row_range.end = end;
 8741                    continue;
 8742                }
 8743            }
 8744            row_ranges.push(start..end);
 8745        }
 8746
 8747        let snapshot = self.buffer.read(cx).snapshot(cx);
 8748        let mut cursor_positions = Vec::new();
 8749        for row_range in &row_ranges {
 8750            let anchor = snapshot.anchor_before(Point::new(
 8751                row_range.end.previous_row().0,
 8752                snapshot.line_len(row_range.end.previous_row()),
 8753            ));
 8754            cursor_positions.push(anchor..anchor);
 8755        }
 8756
 8757        self.transact(window, cx, |this, window, cx| {
 8758            for row_range in row_ranges.into_iter().rev() {
 8759                for row in row_range.iter_rows().rev() {
 8760                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8761                    let next_line_row = row.next_row();
 8762                    let indent = snapshot.indent_size_for_line(next_line_row);
 8763                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8764
 8765                    let replace =
 8766                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8767                            " "
 8768                        } else {
 8769                            ""
 8770                        };
 8771
 8772                    this.buffer.update(cx, |buffer, cx| {
 8773                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8774                    });
 8775                }
 8776            }
 8777
 8778            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8779                s.select_anchor_ranges(cursor_positions)
 8780            });
 8781        });
 8782    }
 8783
 8784    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8785        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8786        self.join_lines_impl(true, window, cx);
 8787    }
 8788
 8789    pub fn sort_lines_case_sensitive(
 8790        &mut self,
 8791        _: &SortLinesCaseSensitive,
 8792        window: &mut Window,
 8793        cx: &mut Context<Self>,
 8794    ) {
 8795        self.manipulate_lines(window, cx, |lines| lines.sort())
 8796    }
 8797
 8798    pub fn sort_lines_case_insensitive(
 8799        &mut self,
 8800        _: &SortLinesCaseInsensitive,
 8801        window: &mut Window,
 8802        cx: &mut Context<Self>,
 8803    ) {
 8804        self.manipulate_lines(window, cx, |lines| {
 8805            lines.sort_by_key(|line| line.to_lowercase())
 8806        })
 8807    }
 8808
 8809    pub fn unique_lines_case_insensitive(
 8810        &mut self,
 8811        _: &UniqueLinesCaseInsensitive,
 8812        window: &mut Window,
 8813        cx: &mut Context<Self>,
 8814    ) {
 8815        self.manipulate_lines(window, cx, |lines| {
 8816            let mut seen = HashSet::default();
 8817            lines.retain(|line| seen.insert(line.to_lowercase()));
 8818        })
 8819    }
 8820
 8821    pub fn unique_lines_case_sensitive(
 8822        &mut self,
 8823        _: &UniqueLinesCaseSensitive,
 8824        window: &mut Window,
 8825        cx: &mut Context<Self>,
 8826    ) {
 8827        self.manipulate_lines(window, cx, |lines| {
 8828            let mut seen = HashSet::default();
 8829            lines.retain(|line| seen.insert(*line));
 8830        })
 8831    }
 8832
 8833    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8834        let Some(project) = self.project.clone() else {
 8835            return;
 8836        };
 8837        self.reload(project, window, cx)
 8838            .detach_and_notify_err(window, cx);
 8839    }
 8840
 8841    pub fn restore_file(
 8842        &mut self,
 8843        _: &::git::RestoreFile,
 8844        window: &mut Window,
 8845        cx: &mut Context<Self>,
 8846    ) {
 8847        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8848        let mut buffer_ids = HashSet::default();
 8849        let snapshot = self.buffer().read(cx).snapshot(cx);
 8850        for selection in self.selections.all::<usize>(cx) {
 8851            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8852        }
 8853
 8854        let buffer = self.buffer().read(cx);
 8855        let ranges = buffer_ids
 8856            .into_iter()
 8857            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8858            .collect::<Vec<_>>();
 8859
 8860        self.restore_hunks_in_ranges(ranges, window, cx);
 8861    }
 8862
 8863    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8864        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8865        let selections = self
 8866            .selections
 8867            .all(cx)
 8868            .into_iter()
 8869            .map(|s| s.range())
 8870            .collect();
 8871        self.restore_hunks_in_ranges(selections, window, cx);
 8872    }
 8873
 8874    pub fn restore_hunks_in_ranges(
 8875        &mut self,
 8876        ranges: Vec<Range<Point>>,
 8877        window: &mut Window,
 8878        cx: &mut Context<Editor>,
 8879    ) {
 8880        let mut revert_changes = HashMap::default();
 8881        let chunk_by = self
 8882            .snapshot(window, cx)
 8883            .hunks_for_ranges(ranges)
 8884            .into_iter()
 8885            .chunk_by(|hunk| hunk.buffer_id);
 8886        for (buffer_id, hunks) in &chunk_by {
 8887            let hunks = hunks.collect::<Vec<_>>();
 8888            for hunk in &hunks {
 8889                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8890            }
 8891            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8892        }
 8893        drop(chunk_by);
 8894        if !revert_changes.is_empty() {
 8895            self.transact(window, cx, |editor, window, cx| {
 8896                editor.restore(revert_changes, window, cx);
 8897            });
 8898        }
 8899    }
 8900
 8901    pub fn open_active_item_in_terminal(
 8902        &mut self,
 8903        _: &OpenInTerminal,
 8904        window: &mut Window,
 8905        cx: &mut Context<Self>,
 8906    ) {
 8907        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8908            let project_path = buffer.read(cx).project_path(cx)?;
 8909            let project = self.project.as_ref()?.read(cx);
 8910            let entry = project.entry_for_path(&project_path, cx)?;
 8911            let parent = match &entry.canonical_path {
 8912                Some(canonical_path) => canonical_path.to_path_buf(),
 8913                None => project.absolute_path(&project_path, cx)?,
 8914            }
 8915            .parent()?
 8916            .to_path_buf();
 8917            Some(parent)
 8918        }) {
 8919            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8920        }
 8921    }
 8922
 8923    fn set_breakpoint_context_menu(
 8924        &mut self,
 8925        display_row: DisplayRow,
 8926        position: Option<Anchor>,
 8927        clicked_point: gpui::Point<Pixels>,
 8928        window: &mut Window,
 8929        cx: &mut Context<Self>,
 8930    ) {
 8931        if !cx.has_flag::<Debugger>() {
 8932            return;
 8933        }
 8934        let source = self
 8935            .buffer
 8936            .read(cx)
 8937            .snapshot(cx)
 8938            .anchor_before(Point::new(display_row.0, 0u32));
 8939
 8940        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8941
 8942        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8943            self,
 8944            source,
 8945            clicked_point,
 8946            context_menu,
 8947            window,
 8948            cx,
 8949        );
 8950    }
 8951
 8952    fn add_edit_breakpoint_block(
 8953        &mut self,
 8954        anchor: Anchor,
 8955        breakpoint: &Breakpoint,
 8956        edit_action: BreakpointPromptEditAction,
 8957        window: &mut Window,
 8958        cx: &mut Context<Self>,
 8959    ) {
 8960        let weak_editor = cx.weak_entity();
 8961        let bp_prompt = cx.new(|cx| {
 8962            BreakpointPromptEditor::new(
 8963                weak_editor,
 8964                anchor,
 8965                breakpoint.clone(),
 8966                edit_action,
 8967                window,
 8968                cx,
 8969            )
 8970        });
 8971
 8972        let height = bp_prompt.update(cx, |this, cx| {
 8973            this.prompt
 8974                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8975        });
 8976        let cloned_prompt = bp_prompt.clone();
 8977        let blocks = vec![BlockProperties {
 8978            style: BlockStyle::Sticky,
 8979            placement: BlockPlacement::Above(anchor),
 8980            height: Some(height),
 8981            render: Arc::new(move |cx| {
 8982                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8983                cloned_prompt.clone().into_any_element()
 8984            }),
 8985            priority: 0,
 8986        }];
 8987
 8988        let focus_handle = bp_prompt.focus_handle(cx);
 8989        window.focus(&focus_handle);
 8990
 8991        let block_ids = self.insert_blocks(blocks, None, cx);
 8992        bp_prompt.update(cx, |prompt, _| {
 8993            prompt.add_block_ids(block_ids);
 8994        });
 8995    }
 8996
 8997    pub(crate) fn breakpoint_at_row(
 8998        &self,
 8999        row: u32,
 9000        window: &mut Window,
 9001        cx: &mut Context<Self>,
 9002    ) -> Option<(Anchor, Breakpoint)> {
 9003        let snapshot = self.snapshot(window, cx);
 9004        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 9005
 9006        self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9007    }
 9008
 9009    pub(crate) fn breakpoint_at_anchor(
 9010        &self,
 9011        breakpoint_position: Anchor,
 9012        snapshot: &EditorSnapshot,
 9013        cx: &mut Context<Self>,
 9014    ) -> Option<(Anchor, Breakpoint)> {
 9015        let project = self.project.clone()?;
 9016
 9017        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 9018            snapshot
 9019                .buffer_snapshot
 9020                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 9021        })?;
 9022
 9023        let enclosing_excerpt = breakpoint_position.excerpt_id;
 9024        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 9025        let buffer_snapshot = buffer.read(cx).snapshot();
 9026
 9027        let row = buffer_snapshot
 9028            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 9029            .row;
 9030
 9031        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 9032        let anchor_end = snapshot
 9033            .buffer_snapshot
 9034            .anchor_after(Point::new(row, line_len));
 9035
 9036        let bp = self
 9037            .breakpoint_store
 9038            .as_ref()?
 9039            .read_with(cx, |breakpoint_store, cx| {
 9040                breakpoint_store
 9041                    .breakpoints(
 9042                        &buffer,
 9043                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 9044                        &buffer_snapshot,
 9045                        cx,
 9046                    )
 9047                    .next()
 9048                    .and_then(|(anchor, bp)| {
 9049                        let breakpoint_row = buffer_snapshot
 9050                            .summary_for_anchor::<text::PointUtf16>(anchor)
 9051                            .row;
 9052
 9053                        if breakpoint_row == row {
 9054                            snapshot
 9055                                .buffer_snapshot
 9056                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 9057                                .map(|anchor| (anchor, bp.clone()))
 9058                        } else {
 9059                            None
 9060                        }
 9061                    })
 9062            });
 9063        bp
 9064    }
 9065
 9066    pub fn edit_log_breakpoint(
 9067        &mut self,
 9068        _: &EditLogBreakpoint,
 9069        window: &mut Window,
 9070        cx: &mut Context<Self>,
 9071    ) {
 9072        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9073            let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
 9074                message: None,
 9075                state: BreakpointState::Enabled,
 9076                condition: None,
 9077                hit_condition: None,
 9078            });
 9079
 9080            self.add_edit_breakpoint_block(
 9081                anchor,
 9082                &breakpoint,
 9083                BreakpointPromptEditAction::Log,
 9084                window,
 9085                cx,
 9086            );
 9087        }
 9088    }
 9089
 9090    fn breakpoints_at_cursors(
 9091        &self,
 9092        window: &mut Window,
 9093        cx: &mut Context<Self>,
 9094    ) -> Vec<(Anchor, Option<Breakpoint>)> {
 9095        let snapshot = self.snapshot(window, cx);
 9096        let cursors = self
 9097            .selections
 9098            .disjoint_anchors()
 9099            .into_iter()
 9100            .map(|selection| {
 9101                let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
 9102
 9103                let breakpoint_position = self
 9104                    .breakpoint_at_row(cursor_position.row, window, cx)
 9105                    .map(|bp| bp.0)
 9106                    .unwrap_or_else(|| {
 9107                        snapshot
 9108                            .display_snapshot
 9109                            .buffer_snapshot
 9110                            .anchor_after(Point::new(cursor_position.row, 0))
 9111                    });
 9112
 9113                let breakpoint = self
 9114                    .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
 9115                    .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
 9116
 9117                breakpoint.unwrap_or_else(|| (breakpoint_position, None))
 9118            })
 9119            // 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.
 9120            .collect::<HashMap<Anchor, _>>();
 9121
 9122        cursors.into_iter().collect()
 9123    }
 9124
 9125    pub fn enable_breakpoint(
 9126        &mut self,
 9127        _: &crate::actions::EnableBreakpoint,
 9128        window: &mut Window,
 9129        cx: &mut Context<Self>,
 9130    ) {
 9131        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9132            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
 9133                continue;
 9134            };
 9135            self.edit_breakpoint_at_anchor(
 9136                anchor,
 9137                breakpoint,
 9138                BreakpointEditAction::InvertState,
 9139                cx,
 9140            );
 9141        }
 9142    }
 9143
 9144    pub fn disable_breakpoint(
 9145        &mut self,
 9146        _: &crate::actions::DisableBreakpoint,
 9147        window: &mut Window,
 9148        cx: &mut Context<Self>,
 9149    ) {
 9150        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9151            let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
 9152                continue;
 9153            };
 9154            self.edit_breakpoint_at_anchor(
 9155                anchor,
 9156                breakpoint,
 9157                BreakpointEditAction::InvertState,
 9158                cx,
 9159            );
 9160        }
 9161    }
 9162
 9163    pub fn toggle_breakpoint(
 9164        &mut self,
 9165        _: &crate::actions::ToggleBreakpoint,
 9166        window: &mut Window,
 9167        cx: &mut Context<Self>,
 9168    ) {
 9169        for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
 9170            if let Some(breakpoint) = breakpoint {
 9171                self.edit_breakpoint_at_anchor(
 9172                    anchor,
 9173                    breakpoint,
 9174                    BreakpointEditAction::Toggle,
 9175                    cx,
 9176                );
 9177            } else {
 9178                self.edit_breakpoint_at_anchor(
 9179                    anchor,
 9180                    Breakpoint::new_standard(),
 9181                    BreakpointEditAction::Toggle,
 9182                    cx,
 9183                );
 9184            }
 9185        }
 9186    }
 9187
 9188    pub fn edit_breakpoint_at_anchor(
 9189        &mut self,
 9190        breakpoint_position: Anchor,
 9191        breakpoint: Breakpoint,
 9192        edit_action: BreakpointEditAction,
 9193        cx: &mut Context<Self>,
 9194    ) {
 9195        let Some(breakpoint_store) = &self.breakpoint_store else {
 9196            return;
 9197        };
 9198
 9199        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 9200            if breakpoint_position == Anchor::min() {
 9201                self.buffer()
 9202                    .read(cx)
 9203                    .excerpt_buffer_ids()
 9204                    .into_iter()
 9205                    .next()
 9206            } else {
 9207                None
 9208            }
 9209        }) else {
 9210            return;
 9211        };
 9212
 9213        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 9214            return;
 9215        };
 9216
 9217        breakpoint_store.update(cx, |breakpoint_store, cx| {
 9218            breakpoint_store.toggle_breakpoint(
 9219                buffer,
 9220                (breakpoint_position.text_anchor, breakpoint),
 9221                edit_action,
 9222                cx,
 9223            );
 9224        });
 9225
 9226        cx.notify();
 9227    }
 9228
 9229    #[cfg(any(test, feature = "test-support"))]
 9230    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 9231        self.breakpoint_store.clone()
 9232    }
 9233
 9234    pub fn prepare_restore_change(
 9235        &self,
 9236        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 9237        hunk: &MultiBufferDiffHunk,
 9238        cx: &mut App,
 9239    ) -> Option<()> {
 9240        if hunk.is_created_file() {
 9241            return None;
 9242        }
 9243        let buffer = self.buffer.read(cx);
 9244        let diff = buffer.diff_for(hunk.buffer_id)?;
 9245        let buffer = buffer.buffer(hunk.buffer_id)?;
 9246        let buffer = buffer.read(cx);
 9247        let original_text = diff
 9248            .read(cx)
 9249            .base_text()
 9250            .as_rope()
 9251            .slice(hunk.diff_base_byte_range.clone());
 9252        let buffer_snapshot = buffer.snapshot();
 9253        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 9254        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 9255            probe
 9256                .0
 9257                .start
 9258                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 9259                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 9260        }) {
 9261            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 9262            Some(())
 9263        } else {
 9264            None
 9265        }
 9266    }
 9267
 9268    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 9269        self.manipulate_lines(window, cx, |lines| lines.reverse())
 9270    }
 9271
 9272    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 9273        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 9274    }
 9275
 9276    fn manipulate_lines<Fn>(
 9277        &mut self,
 9278        window: &mut Window,
 9279        cx: &mut Context<Self>,
 9280        mut callback: Fn,
 9281    ) where
 9282        Fn: FnMut(&mut Vec<&str>),
 9283    {
 9284        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9285
 9286        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9287        let buffer = self.buffer.read(cx).snapshot(cx);
 9288
 9289        let mut edits = Vec::new();
 9290
 9291        let selections = self.selections.all::<Point>(cx);
 9292        let mut selections = selections.iter().peekable();
 9293        let mut contiguous_row_selections = Vec::new();
 9294        let mut new_selections = Vec::new();
 9295        let mut added_lines = 0;
 9296        let mut removed_lines = 0;
 9297
 9298        while let Some(selection) = selections.next() {
 9299            let (start_row, end_row) = consume_contiguous_rows(
 9300                &mut contiguous_row_selections,
 9301                selection,
 9302                &display_map,
 9303                &mut selections,
 9304            );
 9305
 9306            let start_point = Point::new(start_row.0, 0);
 9307            let end_point = Point::new(
 9308                end_row.previous_row().0,
 9309                buffer.line_len(end_row.previous_row()),
 9310            );
 9311            let text = buffer
 9312                .text_for_range(start_point..end_point)
 9313                .collect::<String>();
 9314
 9315            let mut lines = text.split('\n').collect_vec();
 9316
 9317            let lines_before = lines.len();
 9318            callback(&mut lines);
 9319            let lines_after = lines.len();
 9320
 9321            edits.push((start_point..end_point, lines.join("\n")));
 9322
 9323            // Selections must change based on added and removed line count
 9324            let start_row =
 9325                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9326            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9327            new_selections.push(Selection {
 9328                id: selection.id,
 9329                start: start_row,
 9330                end: end_row,
 9331                goal: SelectionGoal::None,
 9332                reversed: selection.reversed,
 9333            });
 9334
 9335            if lines_after > lines_before {
 9336                added_lines += lines_after - lines_before;
 9337            } else if lines_before > lines_after {
 9338                removed_lines += lines_before - lines_after;
 9339            }
 9340        }
 9341
 9342        self.transact(window, cx, |this, window, cx| {
 9343            let buffer = this.buffer.update(cx, |buffer, cx| {
 9344                buffer.edit(edits, None, cx);
 9345                buffer.snapshot(cx)
 9346            });
 9347
 9348            // Recalculate offsets on newly edited buffer
 9349            let new_selections = new_selections
 9350                .iter()
 9351                .map(|s| {
 9352                    let start_point = Point::new(s.start.0, 0);
 9353                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9354                    Selection {
 9355                        id: s.id,
 9356                        start: buffer.point_to_offset(start_point),
 9357                        end: buffer.point_to_offset(end_point),
 9358                        goal: s.goal,
 9359                        reversed: s.reversed,
 9360                    }
 9361                })
 9362                .collect();
 9363
 9364            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9365                s.select(new_selections);
 9366            });
 9367
 9368            this.request_autoscroll(Autoscroll::fit(), cx);
 9369        });
 9370    }
 9371
 9372    pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
 9373        self.manipulate_text(window, cx, |text| {
 9374            let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
 9375            if has_upper_case_characters {
 9376                text.to_lowercase()
 9377            } else {
 9378                text.to_uppercase()
 9379            }
 9380        })
 9381    }
 9382
 9383    pub fn convert_to_upper_case(
 9384        &mut self,
 9385        _: &ConvertToUpperCase,
 9386        window: &mut Window,
 9387        cx: &mut Context<Self>,
 9388    ) {
 9389        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9390    }
 9391
 9392    pub fn convert_to_lower_case(
 9393        &mut self,
 9394        _: &ConvertToLowerCase,
 9395        window: &mut Window,
 9396        cx: &mut Context<Self>,
 9397    ) {
 9398        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9399    }
 9400
 9401    pub fn convert_to_title_case(
 9402        &mut self,
 9403        _: &ConvertToTitleCase,
 9404        window: &mut Window,
 9405        cx: &mut Context<Self>,
 9406    ) {
 9407        self.manipulate_text(window, cx, |text| {
 9408            text.split('\n')
 9409                .map(|line| line.to_case(Case::Title))
 9410                .join("\n")
 9411        })
 9412    }
 9413
 9414    pub fn convert_to_snake_case(
 9415        &mut self,
 9416        _: &ConvertToSnakeCase,
 9417        window: &mut Window,
 9418        cx: &mut Context<Self>,
 9419    ) {
 9420        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9421    }
 9422
 9423    pub fn convert_to_kebab_case(
 9424        &mut self,
 9425        _: &ConvertToKebabCase,
 9426        window: &mut Window,
 9427        cx: &mut Context<Self>,
 9428    ) {
 9429        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9430    }
 9431
 9432    pub fn convert_to_upper_camel_case(
 9433        &mut self,
 9434        _: &ConvertToUpperCamelCase,
 9435        window: &mut Window,
 9436        cx: &mut Context<Self>,
 9437    ) {
 9438        self.manipulate_text(window, cx, |text| {
 9439            text.split('\n')
 9440                .map(|line| line.to_case(Case::UpperCamel))
 9441                .join("\n")
 9442        })
 9443    }
 9444
 9445    pub fn convert_to_lower_camel_case(
 9446        &mut self,
 9447        _: &ConvertToLowerCamelCase,
 9448        window: &mut Window,
 9449        cx: &mut Context<Self>,
 9450    ) {
 9451        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9452    }
 9453
 9454    pub fn convert_to_opposite_case(
 9455        &mut self,
 9456        _: &ConvertToOppositeCase,
 9457        window: &mut Window,
 9458        cx: &mut Context<Self>,
 9459    ) {
 9460        self.manipulate_text(window, cx, |text| {
 9461            text.chars()
 9462                .fold(String::with_capacity(text.len()), |mut t, c| {
 9463                    if c.is_uppercase() {
 9464                        t.extend(c.to_lowercase());
 9465                    } else {
 9466                        t.extend(c.to_uppercase());
 9467                    }
 9468                    t
 9469                })
 9470        })
 9471    }
 9472
 9473    pub fn convert_to_rot13(
 9474        &mut self,
 9475        _: &ConvertToRot13,
 9476        window: &mut Window,
 9477        cx: &mut Context<Self>,
 9478    ) {
 9479        self.manipulate_text(window, cx, |text| {
 9480            text.chars()
 9481                .map(|c| match c {
 9482                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9483                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9484                    _ => c,
 9485                })
 9486                .collect()
 9487        })
 9488    }
 9489
 9490    pub fn convert_to_rot47(
 9491        &mut self,
 9492        _: &ConvertToRot47,
 9493        window: &mut Window,
 9494        cx: &mut Context<Self>,
 9495    ) {
 9496        self.manipulate_text(window, cx, |text| {
 9497            text.chars()
 9498                .map(|c| {
 9499                    let code_point = c as u32;
 9500                    if code_point >= 33 && code_point <= 126 {
 9501                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9502                    }
 9503                    c
 9504                })
 9505                .collect()
 9506        })
 9507    }
 9508
 9509    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9510    where
 9511        Fn: FnMut(&str) -> String,
 9512    {
 9513        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9514        let buffer = self.buffer.read(cx).snapshot(cx);
 9515
 9516        let mut new_selections = Vec::new();
 9517        let mut edits = Vec::new();
 9518        let mut selection_adjustment = 0i32;
 9519
 9520        for selection in self.selections.all::<usize>(cx) {
 9521            let selection_is_empty = selection.is_empty();
 9522
 9523            let (start, end) = if selection_is_empty {
 9524                let word_range = movement::surrounding_word(
 9525                    &display_map,
 9526                    selection.start.to_display_point(&display_map),
 9527                );
 9528                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9529                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9530                (start, end)
 9531            } else {
 9532                (selection.start, selection.end)
 9533            };
 9534
 9535            let text = buffer.text_for_range(start..end).collect::<String>();
 9536            let old_length = text.len() as i32;
 9537            let text = callback(&text);
 9538
 9539            new_selections.push(Selection {
 9540                start: (start as i32 - selection_adjustment) as usize,
 9541                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9542                goal: SelectionGoal::None,
 9543                ..selection
 9544            });
 9545
 9546            selection_adjustment += old_length - text.len() as i32;
 9547
 9548            edits.push((start..end, text));
 9549        }
 9550
 9551        self.transact(window, cx, |this, window, cx| {
 9552            this.buffer.update(cx, |buffer, cx| {
 9553                buffer.edit(edits, None, cx);
 9554            });
 9555
 9556            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9557                s.select(new_selections);
 9558            });
 9559
 9560            this.request_autoscroll(Autoscroll::fit(), cx);
 9561        });
 9562    }
 9563
 9564    pub fn duplicate(
 9565        &mut self,
 9566        upwards: bool,
 9567        whole_lines: bool,
 9568        window: &mut Window,
 9569        cx: &mut Context<Self>,
 9570    ) {
 9571        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9572
 9573        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9574        let buffer = &display_map.buffer_snapshot;
 9575        let selections = self.selections.all::<Point>(cx);
 9576
 9577        let mut edits = Vec::new();
 9578        let mut selections_iter = selections.iter().peekable();
 9579        while let Some(selection) = selections_iter.next() {
 9580            let mut rows = selection.spanned_rows(false, &display_map);
 9581            // duplicate line-wise
 9582            if whole_lines || selection.start == selection.end {
 9583                // Avoid duplicating the same lines twice.
 9584                while let Some(next_selection) = selections_iter.peek() {
 9585                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9586                    if next_rows.start < rows.end {
 9587                        rows.end = next_rows.end;
 9588                        selections_iter.next().unwrap();
 9589                    } else {
 9590                        break;
 9591                    }
 9592                }
 9593
 9594                // Copy the text from the selected row region and splice it either at the start
 9595                // or end of the region.
 9596                let start = Point::new(rows.start.0, 0);
 9597                let end = Point::new(
 9598                    rows.end.previous_row().0,
 9599                    buffer.line_len(rows.end.previous_row()),
 9600                );
 9601                let text = buffer
 9602                    .text_for_range(start..end)
 9603                    .chain(Some("\n"))
 9604                    .collect::<String>();
 9605                let insert_location = if upwards {
 9606                    Point::new(rows.end.0, 0)
 9607                } else {
 9608                    start
 9609                };
 9610                edits.push((insert_location..insert_location, text));
 9611            } else {
 9612                // duplicate character-wise
 9613                let start = selection.start;
 9614                let end = selection.end;
 9615                let text = buffer.text_for_range(start..end).collect::<String>();
 9616                edits.push((selection.end..selection.end, text));
 9617            }
 9618        }
 9619
 9620        self.transact(window, cx, |this, _, cx| {
 9621            this.buffer.update(cx, |buffer, cx| {
 9622                buffer.edit(edits, None, cx);
 9623            });
 9624
 9625            this.request_autoscroll(Autoscroll::fit(), cx);
 9626        });
 9627    }
 9628
 9629    pub fn duplicate_line_up(
 9630        &mut self,
 9631        _: &DuplicateLineUp,
 9632        window: &mut Window,
 9633        cx: &mut Context<Self>,
 9634    ) {
 9635        self.duplicate(true, true, window, cx);
 9636    }
 9637
 9638    pub fn duplicate_line_down(
 9639        &mut self,
 9640        _: &DuplicateLineDown,
 9641        window: &mut Window,
 9642        cx: &mut Context<Self>,
 9643    ) {
 9644        self.duplicate(false, true, window, cx);
 9645    }
 9646
 9647    pub fn duplicate_selection(
 9648        &mut self,
 9649        _: &DuplicateSelection,
 9650        window: &mut Window,
 9651        cx: &mut Context<Self>,
 9652    ) {
 9653        self.duplicate(false, false, window, cx);
 9654    }
 9655
 9656    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9657        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9658
 9659        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9660        let buffer = self.buffer.read(cx).snapshot(cx);
 9661
 9662        let mut edits = Vec::new();
 9663        let mut unfold_ranges = Vec::new();
 9664        let mut refold_creases = Vec::new();
 9665
 9666        let selections = self.selections.all::<Point>(cx);
 9667        let mut selections = selections.iter().peekable();
 9668        let mut contiguous_row_selections = Vec::new();
 9669        let mut new_selections = Vec::new();
 9670
 9671        while let Some(selection) = selections.next() {
 9672            // Find all the selections that span a contiguous row range
 9673            let (start_row, end_row) = consume_contiguous_rows(
 9674                &mut contiguous_row_selections,
 9675                selection,
 9676                &display_map,
 9677                &mut selections,
 9678            );
 9679
 9680            // Move the text spanned by the row range to be before the line preceding the row range
 9681            if start_row.0 > 0 {
 9682                let range_to_move = Point::new(
 9683                    start_row.previous_row().0,
 9684                    buffer.line_len(start_row.previous_row()),
 9685                )
 9686                    ..Point::new(
 9687                        end_row.previous_row().0,
 9688                        buffer.line_len(end_row.previous_row()),
 9689                    );
 9690                let insertion_point = display_map
 9691                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9692                    .0;
 9693
 9694                // Don't move lines across excerpts
 9695                if buffer
 9696                    .excerpt_containing(insertion_point..range_to_move.end)
 9697                    .is_some()
 9698                {
 9699                    let text = buffer
 9700                        .text_for_range(range_to_move.clone())
 9701                        .flat_map(|s| s.chars())
 9702                        .skip(1)
 9703                        .chain(['\n'])
 9704                        .collect::<String>();
 9705
 9706                    edits.push((
 9707                        buffer.anchor_after(range_to_move.start)
 9708                            ..buffer.anchor_before(range_to_move.end),
 9709                        String::new(),
 9710                    ));
 9711                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9712                    edits.push((insertion_anchor..insertion_anchor, text));
 9713
 9714                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9715
 9716                    // Move selections up
 9717                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9718                        |mut selection| {
 9719                            selection.start.row -= row_delta;
 9720                            selection.end.row -= row_delta;
 9721                            selection
 9722                        },
 9723                    ));
 9724
 9725                    // Move folds up
 9726                    unfold_ranges.push(range_to_move.clone());
 9727                    for fold in display_map.folds_in_range(
 9728                        buffer.anchor_before(range_to_move.start)
 9729                            ..buffer.anchor_after(range_to_move.end),
 9730                    ) {
 9731                        let mut start = fold.range.start.to_point(&buffer);
 9732                        let mut end = fold.range.end.to_point(&buffer);
 9733                        start.row -= row_delta;
 9734                        end.row -= row_delta;
 9735                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9736                    }
 9737                }
 9738            }
 9739
 9740            // If we didn't move line(s), preserve the existing selections
 9741            new_selections.append(&mut contiguous_row_selections);
 9742        }
 9743
 9744        self.transact(window, cx, |this, window, cx| {
 9745            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9746            this.buffer.update(cx, |buffer, cx| {
 9747                for (range, text) in edits {
 9748                    buffer.edit([(range, text)], None, cx);
 9749                }
 9750            });
 9751            this.fold_creases(refold_creases, true, window, cx);
 9752            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9753                s.select(new_selections);
 9754            })
 9755        });
 9756    }
 9757
 9758    pub fn move_line_down(
 9759        &mut self,
 9760        _: &MoveLineDown,
 9761        window: &mut Window,
 9762        cx: &mut Context<Self>,
 9763    ) {
 9764        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9765
 9766        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9767        let buffer = self.buffer.read(cx).snapshot(cx);
 9768
 9769        let mut edits = Vec::new();
 9770        let mut unfold_ranges = Vec::new();
 9771        let mut refold_creases = Vec::new();
 9772
 9773        let selections = self.selections.all::<Point>(cx);
 9774        let mut selections = selections.iter().peekable();
 9775        let mut contiguous_row_selections = Vec::new();
 9776        let mut new_selections = Vec::new();
 9777
 9778        while let Some(selection) = selections.next() {
 9779            // Find all the selections that span a contiguous row range
 9780            let (start_row, end_row) = consume_contiguous_rows(
 9781                &mut contiguous_row_selections,
 9782                selection,
 9783                &display_map,
 9784                &mut selections,
 9785            );
 9786
 9787            // Move the text spanned by the row range to be after the last line of the row range
 9788            if end_row.0 <= buffer.max_point().row {
 9789                let range_to_move =
 9790                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9791                let insertion_point = display_map
 9792                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9793                    .0;
 9794
 9795                // Don't move lines across excerpt boundaries
 9796                if buffer
 9797                    .excerpt_containing(range_to_move.start..insertion_point)
 9798                    .is_some()
 9799                {
 9800                    let mut text = String::from("\n");
 9801                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9802                    text.pop(); // Drop trailing newline
 9803                    edits.push((
 9804                        buffer.anchor_after(range_to_move.start)
 9805                            ..buffer.anchor_before(range_to_move.end),
 9806                        String::new(),
 9807                    ));
 9808                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9809                    edits.push((insertion_anchor..insertion_anchor, text));
 9810
 9811                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9812
 9813                    // Move selections down
 9814                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9815                        |mut selection| {
 9816                            selection.start.row += row_delta;
 9817                            selection.end.row += row_delta;
 9818                            selection
 9819                        },
 9820                    ));
 9821
 9822                    // Move folds down
 9823                    unfold_ranges.push(range_to_move.clone());
 9824                    for fold in display_map.folds_in_range(
 9825                        buffer.anchor_before(range_to_move.start)
 9826                            ..buffer.anchor_after(range_to_move.end),
 9827                    ) {
 9828                        let mut start = fold.range.start.to_point(&buffer);
 9829                        let mut end = fold.range.end.to_point(&buffer);
 9830                        start.row += row_delta;
 9831                        end.row += row_delta;
 9832                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9833                    }
 9834                }
 9835            }
 9836
 9837            // If we didn't move line(s), preserve the existing selections
 9838            new_selections.append(&mut contiguous_row_selections);
 9839        }
 9840
 9841        self.transact(window, cx, |this, window, cx| {
 9842            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9843            this.buffer.update(cx, |buffer, cx| {
 9844                for (range, text) in edits {
 9845                    buffer.edit([(range, text)], None, cx);
 9846                }
 9847            });
 9848            this.fold_creases(refold_creases, true, window, cx);
 9849            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9850                s.select(new_selections)
 9851            });
 9852        });
 9853    }
 9854
 9855    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9856        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9857        let text_layout_details = &self.text_layout_details(window);
 9858        self.transact(window, cx, |this, window, cx| {
 9859            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9860                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9861                s.move_with(|display_map, selection| {
 9862                    if !selection.is_empty() {
 9863                        return;
 9864                    }
 9865
 9866                    let mut head = selection.head();
 9867                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9868                    if head.column() == display_map.line_len(head.row()) {
 9869                        transpose_offset = display_map
 9870                            .buffer_snapshot
 9871                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9872                    }
 9873
 9874                    if transpose_offset == 0 {
 9875                        return;
 9876                    }
 9877
 9878                    *head.column_mut() += 1;
 9879                    head = display_map.clip_point(head, Bias::Right);
 9880                    let goal = SelectionGoal::HorizontalPosition(
 9881                        display_map
 9882                            .x_for_display_point(head, text_layout_details)
 9883                            .into(),
 9884                    );
 9885                    selection.collapse_to(head, goal);
 9886
 9887                    let transpose_start = display_map
 9888                        .buffer_snapshot
 9889                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9890                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9891                        let transpose_end = display_map
 9892                            .buffer_snapshot
 9893                            .clip_offset(transpose_offset + 1, Bias::Right);
 9894                        if let Some(ch) =
 9895                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9896                        {
 9897                            edits.push((transpose_start..transpose_offset, String::new()));
 9898                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9899                        }
 9900                    }
 9901                });
 9902                edits
 9903            });
 9904            this.buffer
 9905                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9906            let selections = this.selections.all::<usize>(cx);
 9907            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9908                s.select(selections);
 9909            });
 9910        });
 9911    }
 9912
 9913    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9914        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9915        self.rewrap_impl(RewrapOptions::default(), cx)
 9916    }
 9917
 9918    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9919        let buffer = self.buffer.read(cx).snapshot(cx);
 9920        let selections = self.selections.all::<Point>(cx);
 9921        let mut selections = selections.iter().peekable();
 9922
 9923        let mut edits = Vec::new();
 9924        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9925
 9926        while let Some(selection) = selections.next() {
 9927            let mut start_row = selection.start.row;
 9928            let mut end_row = selection.end.row;
 9929
 9930            // Skip selections that overlap with a range that has already been rewrapped.
 9931            let selection_range = start_row..end_row;
 9932            if rewrapped_row_ranges
 9933                .iter()
 9934                .any(|range| range.overlaps(&selection_range))
 9935            {
 9936                continue;
 9937            }
 9938
 9939            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9940
 9941            // Since not all lines in the selection may be at the same indent
 9942            // level, choose the indent size that is the most common between all
 9943            // of the lines.
 9944            //
 9945            // If there is a tie, we use the deepest indent.
 9946            let (indent_size, indent_end) = {
 9947                let mut indent_size_occurrences = HashMap::default();
 9948                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9949
 9950                for row in start_row..=end_row {
 9951                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9952                    rows_by_indent_size.entry(indent).or_default().push(row);
 9953                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9954                }
 9955
 9956                let indent_size = indent_size_occurrences
 9957                    .into_iter()
 9958                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9959                    .map(|(indent, _)| indent)
 9960                    .unwrap_or_default();
 9961                let row = rows_by_indent_size[&indent_size][0];
 9962                let indent_end = Point::new(row, indent_size.len);
 9963
 9964                (indent_size, indent_end)
 9965            };
 9966
 9967            let mut line_prefix = indent_size.chars().collect::<String>();
 9968
 9969            let mut inside_comment = false;
 9970            if let Some(comment_prefix) =
 9971                buffer
 9972                    .language_scope_at(selection.head())
 9973                    .and_then(|language| {
 9974                        language
 9975                            .line_comment_prefixes()
 9976                            .iter()
 9977                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9978                            .cloned()
 9979                    })
 9980            {
 9981                line_prefix.push_str(&comment_prefix);
 9982                inside_comment = true;
 9983            }
 9984
 9985            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9986            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9987                RewrapBehavior::InComments => inside_comment,
 9988                RewrapBehavior::InSelections => !selection.is_empty(),
 9989                RewrapBehavior::Anywhere => true,
 9990            };
 9991
 9992            let should_rewrap = options.override_language_settings
 9993                || allow_rewrap_based_on_language
 9994                || self.hard_wrap.is_some();
 9995            if !should_rewrap {
 9996                continue;
 9997            }
 9998
 9999            if selection.is_empty() {
10000                'expand_upwards: while start_row > 0 {
10001                    let prev_row = start_row - 1;
10002                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10003                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10004                    {
10005                        start_row = prev_row;
10006                    } else {
10007                        break 'expand_upwards;
10008                    }
10009                }
10010
10011                'expand_downwards: while end_row < buffer.max_point().row {
10012                    let next_row = end_row + 1;
10013                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10014                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10015                    {
10016                        end_row = next_row;
10017                    } else {
10018                        break 'expand_downwards;
10019                    }
10020                }
10021            }
10022
10023            let start = Point::new(start_row, 0);
10024            let start_offset = start.to_offset(&buffer);
10025            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10026            let selection_text = buffer.text_for_range(start..end).collect::<String>();
10027            let Some(lines_without_prefixes) = selection_text
10028                .lines()
10029                .map(|line| {
10030                    line.strip_prefix(&line_prefix)
10031                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10032                        .ok_or_else(|| {
10033                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10034                        })
10035                })
10036                .collect::<Result<Vec<_>, _>>()
10037                .log_err()
10038            else {
10039                continue;
10040            };
10041
10042            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10043                buffer
10044                    .language_settings_at(Point::new(start_row, 0), cx)
10045                    .preferred_line_length as usize
10046            });
10047            let wrapped_text = wrap_with_prefix(
10048                line_prefix,
10049                lines_without_prefixes.join("\n"),
10050                wrap_column,
10051                tab_size,
10052                options.preserve_existing_whitespace,
10053            );
10054
10055            // TODO: should always use char-based diff while still supporting cursor behavior that
10056            // matches vim.
10057            let mut diff_options = DiffOptions::default();
10058            if options.override_language_settings {
10059                diff_options.max_word_diff_len = 0;
10060                diff_options.max_word_diff_line_count = 0;
10061            } else {
10062                diff_options.max_word_diff_len = usize::MAX;
10063                diff_options.max_word_diff_line_count = usize::MAX;
10064            }
10065
10066            for (old_range, new_text) in
10067                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10068            {
10069                let edit_start = buffer.anchor_after(start_offset + old_range.start);
10070                let edit_end = buffer.anchor_after(start_offset + old_range.end);
10071                edits.push((edit_start..edit_end, new_text));
10072            }
10073
10074            rewrapped_row_ranges.push(start_row..=end_row);
10075        }
10076
10077        self.buffer
10078            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10079    }
10080
10081    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10082        let mut text = String::new();
10083        let buffer = self.buffer.read(cx).snapshot(cx);
10084        let mut selections = self.selections.all::<Point>(cx);
10085        let mut clipboard_selections = Vec::with_capacity(selections.len());
10086        {
10087            let max_point = buffer.max_point();
10088            let mut is_first = true;
10089            for selection in &mut selections {
10090                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10091                if is_entire_line {
10092                    selection.start = Point::new(selection.start.row, 0);
10093                    if !selection.is_empty() && selection.end.column == 0 {
10094                        selection.end = cmp::min(max_point, selection.end);
10095                    } else {
10096                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10097                    }
10098                    selection.goal = SelectionGoal::None;
10099                }
10100                if is_first {
10101                    is_first = false;
10102                } else {
10103                    text += "\n";
10104                }
10105                let mut len = 0;
10106                for chunk in buffer.text_for_range(selection.start..selection.end) {
10107                    text.push_str(chunk);
10108                    len += chunk.len();
10109                }
10110                clipboard_selections.push(ClipboardSelection {
10111                    len,
10112                    is_entire_line,
10113                    first_line_indent: buffer
10114                        .indent_size_for_line(MultiBufferRow(selection.start.row))
10115                        .len,
10116                });
10117            }
10118        }
10119
10120        self.transact(window, cx, |this, window, cx| {
10121            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10122                s.select(selections);
10123            });
10124            this.insert("", window, cx);
10125        });
10126        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10127    }
10128
10129    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10130        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10131        let item = self.cut_common(window, cx);
10132        cx.write_to_clipboard(item);
10133    }
10134
10135    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10136        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10137        self.change_selections(None, window, cx, |s| {
10138            s.move_with(|snapshot, sel| {
10139                if sel.is_empty() {
10140                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10141                }
10142            });
10143        });
10144        let item = self.cut_common(window, cx);
10145        cx.set_global(KillRing(item))
10146    }
10147
10148    pub fn kill_ring_yank(
10149        &mut self,
10150        _: &KillRingYank,
10151        window: &mut Window,
10152        cx: &mut Context<Self>,
10153    ) {
10154        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10155        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10156            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10157                (kill_ring.text().to_string(), kill_ring.metadata_json())
10158            } else {
10159                return;
10160            }
10161        } else {
10162            return;
10163        };
10164        self.do_paste(&text, metadata, false, window, cx);
10165    }
10166
10167    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10168        self.do_copy(true, cx);
10169    }
10170
10171    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10172        self.do_copy(false, cx);
10173    }
10174
10175    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10176        let selections = self.selections.all::<Point>(cx);
10177        let buffer = self.buffer.read(cx).read(cx);
10178        let mut text = String::new();
10179
10180        let mut clipboard_selections = Vec::with_capacity(selections.len());
10181        {
10182            let max_point = buffer.max_point();
10183            let mut is_first = true;
10184            for selection in &selections {
10185                let mut start = selection.start;
10186                let mut end = selection.end;
10187                let is_entire_line = selection.is_empty() || self.selections.line_mode;
10188                if is_entire_line {
10189                    start = Point::new(start.row, 0);
10190                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
10191                }
10192
10193                let mut trimmed_selections = Vec::new();
10194                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10195                    let row = MultiBufferRow(start.row);
10196                    let first_indent = buffer.indent_size_for_line(row);
10197                    if first_indent.len == 0 || start.column > first_indent.len {
10198                        trimmed_selections.push(start..end);
10199                    } else {
10200                        trimmed_selections.push(
10201                            Point::new(row.0, first_indent.len)
10202                                ..Point::new(row.0, buffer.line_len(row)),
10203                        );
10204                        for row in start.row + 1..=end.row {
10205                            let mut line_len = buffer.line_len(MultiBufferRow(row));
10206                            if row == end.row {
10207                                line_len = end.column;
10208                            }
10209                            if line_len == 0 {
10210                                trimmed_selections
10211                                    .push(Point::new(row, 0)..Point::new(row, line_len));
10212                                continue;
10213                            }
10214                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10215                            if row_indent_size.len >= first_indent.len {
10216                                trimmed_selections.push(
10217                                    Point::new(row, first_indent.len)..Point::new(row, line_len),
10218                                );
10219                            } else {
10220                                trimmed_selections.clear();
10221                                trimmed_selections.push(start..end);
10222                                break;
10223                            }
10224                        }
10225                    }
10226                } else {
10227                    trimmed_selections.push(start..end);
10228                }
10229
10230                for trimmed_range in trimmed_selections {
10231                    if is_first {
10232                        is_first = false;
10233                    } else {
10234                        text += "\n";
10235                    }
10236                    let mut len = 0;
10237                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10238                        text.push_str(chunk);
10239                        len += chunk.len();
10240                    }
10241                    clipboard_selections.push(ClipboardSelection {
10242                        len,
10243                        is_entire_line,
10244                        first_line_indent: buffer
10245                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10246                            .len,
10247                    });
10248                }
10249            }
10250        }
10251
10252        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10253            text,
10254            clipboard_selections,
10255        ));
10256    }
10257
10258    pub fn do_paste(
10259        &mut self,
10260        text: &String,
10261        clipboard_selections: Option<Vec<ClipboardSelection>>,
10262        handle_entire_lines: bool,
10263        window: &mut Window,
10264        cx: &mut Context<Self>,
10265    ) {
10266        if self.read_only(cx) {
10267            return;
10268        }
10269
10270        let clipboard_text = Cow::Borrowed(text);
10271
10272        self.transact(window, cx, |this, window, cx| {
10273            if let Some(mut clipboard_selections) = clipboard_selections {
10274                let old_selections = this.selections.all::<usize>(cx);
10275                let all_selections_were_entire_line =
10276                    clipboard_selections.iter().all(|s| s.is_entire_line);
10277                let first_selection_indent_column =
10278                    clipboard_selections.first().map(|s| s.first_line_indent);
10279                if clipboard_selections.len() != old_selections.len() {
10280                    clipboard_selections.drain(..);
10281                }
10282                let cursor_offset = this.selections.last::<usize>(cx).head();
10283                let mut auto_indent_on_paste = true;
10284
10285                this.buffer.update(cx, |buffer, cx| {
10286                    let snapshot = buffer.read(cx);
10287                    auto_indent_on_paste = snapshot
10288                        .language_settings_at(cursor_offset, cx)
10289                        .auto_indent_on_paste;
10290
10291                    let mut start_offset = 0;
10292                    let mut edits = Vec::new();
10293                    let mut original_indent_columns = Vec::new();
10294                    for (ix, selection) in old_selections.iter().enumerate() {
10295                        let to_insert;
10296                        let entire_line;
10297                        let original_indent_column;
10298                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10299                            let end_offset = start_offset + clipboard_selection.len;
10300                            to_insert = &clipboard_text[start_offset..end_offset];
10301                            entire_line = clipboard_selection.is_entire_line;
10302                            start_offset = end_offset + 1;
10303                            original_indent_column = Some(clipboard_selection.first_line_indent);
10304                        } else {
10305                            to_insert = clipboard_text.as_str();
10306                            entire_line = all_selections_were_entire_line;
10307                            original_indent_column = first_selection_indent_column
10308                        }
10309
10310                        // If the corresponding selection was empty when this slice of the
10311                        // clipboard text was written, then the entire line containing the
10312                        // selection was copied. If this selection is also currently empty,
10313                        // then paste the line before the current line of the buffer.
10314                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10315                            let column = selection.start.to_point(&snapshot).column as usize;
10316                            let line_start = selection.start - column;
10317                            line_start..line_start
10318                        } else {
10319                            selection.range()
10320                        };
10321
10322                        edits.push((range, to_insert));
10323                        original_indent_columns.push(original_indent_column);
10324                    }
10325                    drop(snapshot);
10326
10327                    buffer.edit(
10328                        edits,
10329                        if auto_indent_on_paste {
10330                            Some(AutoindentMode::Block {
10331                                original_indent_columns,
10332                            })
10333                        } else {
10334                            None
10335                        },
10336                        cx,
10337                    );
10338                });
10339
10340                let selections = this.selections.all::<usize>(cx);
10341                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10342                    s.select(selections)
10343                });
10344            } else {
10345                this.insert(&clipboard_text, window, cx);
10346            }
10347        });
10348    }
10349
10350    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10351        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10352        if let Some(item) = cx.read_from_clipboard() {
10353            let entries = item.entries();
10354
10355            match entries.first() {
10356                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10357                // of all the pasted entries.
10358                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10359                    .do_paste(
10360                        clipboard_string.text(),
10361                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10362                        true,
10363                        window,
10364                        cx,
10365                    ),
10366                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10367            }
10368        }
10369    }
10370
10371    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10372        if self.read_only(cx) {
10373            return;
10374        }
10375
10376        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10377
10378        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10379            if let Some((selections, _)) =
10380                self.selection_history.transaction(transaction_id).cloned()
10381            {
10382                self.change_selections(None, window, cx, |s| {
10383                    s.select_anchors(selections.to_vec());
10384                });
10385            } else {
10386                log::error!(
10387                    "No entry in selection_history found for undo. \
10388                     This may correspond to a bug where undo does not update the selection. \
10389                     If this is occurring, please add details to \
10390                     https://github.com/zed-industries/zed/issues/22692"
10391                );
10392            }
10393            self.request_autoscroll(Autoscroll::fit(), cx);
10394            self.unmark_text(window, cx);
10395            self.refresh_inline_completion(true, false, window, cx);
10396            cx.emit(EditorEvent::Edited { transaction_id });
10397            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10398        }
10399    }
10400
10401    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10402        if self.read_only(cx) {
10403            return;
10404        }
10405
10406        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10407
10408        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10409            if let Some((_, Some(selections))) =
10410                self.selection_history.transaction(transaction_id).cloned()
10411            {
10412                self.change_selections(None, window, cx, |s| {
10413                    s.select_anchors(selections.to_vec());
10414                });
10415            } else {
10416                log::error!(
10417                    "No entry in selection_history found for redo. \
10418                     This may correspond to a bug where undo does not update the selection. \
10419                     If this is occurring, please add details to \
10420                     https://github.com/zed-industries/zed/issues/22692"
10421                );
10422            }
10423            self.request_autoscroll(Autoscroll::fit(), cx);
10424            self.unmark_text(window, cx);
10425            self.refresh_inline_completion(true, false, window, cx);
10426            cx.emit(EditorEvent::Edited { transaction_id });
10427        }
10428    }
10429
10430    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10431        self.buffer
10432            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10433    }
10434
10435    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10436        self.buffer
10437            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10438    }
10439
10440    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10441        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10442        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10443            s.move_with(|map, selection| {
10444                let cursor = if selection.is_empty() {
10445                    movement::left(map, selection.start)
10446                } else {
10447                    selection.start
10448                };
10449                selection.collapse_to(cursor, SelectionGoal::None);
10450            });
10451        })
10452    }
10453
10454    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10455        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10456        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10457            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10458        })
10459    }
10460
10461    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10462        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10463        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10464            s.move_with(|map, selection| {
10465                let cursor = if selection.is_empty() {
10466                    movement::right(map, selection.end)
10467                } else {
10468                    selection.end
10469                };
10470                selection.collapse_to(cursor, SelectionGoal::None)
10471            });
10472        })
10473    }
10474
10475    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10476        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10477        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10478            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10479        })
10480    }
10481
10482    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10483        if self.take_rename(true, window, cx).is_some() {
10484            return;
10485        }
10486
10487        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10488            cx.propagate();
10489            return;
10490        }
10491
10492        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10493
10494        let text_layout_details = &self.text_layout_details(window);
10495        let selection_count = self.selections.count();
10496        let first_selection = self.selections.first_anchor();
10497
10498        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10499            s.move_with(|map, selection| {
10500                if !selection.is_empty() {
10501                    selection.goal = SelectionGoal::None;
10502                }
10503                let (cursor, goal) = movement::up(
10504                    map,
10505                    selection.start,
10506                    selection.goal,
10507                    false,
10508                    text_layout_details,
10509                );
10510                selection.collapse_to(cursor, goal);
10511            });
10512        });
10513
10514        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10515        {
10516            cx.propagate();
10517        }
10518    }
10519
10520    pub fn move_up_by_lines(
10521        &mut self,
10522        action: &MoveUpByLines,
10523        window: &mut Window,
10524        cx: &mut Context<Self>,
10525    ) {
10526        if self.take_rename(true, window, cx).is_some() {
10527            return;
10528        }
10529
10530        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10531            cx.propagate();
10532            return;
10533        }
10534
10535        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10536
10537        let text_layout_details = &self.text_layout_details(window);
10538
10539        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10540            s.move_with(|map, selection| {
10541                if !selection.is_empty() {
10542                    selection.goal = SelectionGoal::None;
10543                }
10544                let (cursor, goal) = movement::up_by_rows(
10545                    map,
10546                    selection.start,
10547                    action.lines,
10548                    selection.goal,
10549                    false,
10550                    text_layout_details,
10551                );
10552                selection.collapse_to(cursor, goal);
10553            });
10554        })
10555    }
10556
10557    pub fn move_down_by_lines(
10558        &mut self,
10559        action: &MoveDownByLines,
10560        window: &mut Window,
10561        cx: &mut Context<Self>,
10562    ) {
10563        if self.take_rename(true, window, cx).is_some() {
10564            return;
10565        }
10566
10567        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10568            cx.propagate();
10569            return;
10570        }
10571
10572        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10573
10574        let text_layout_details = &self.text_layout_details(window);
10575
10576        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10577            s.move_with(|map, selection| {
10578                if !selection.is_empty() {
10579                    selection.goal = SelectionGoal::None;
10580                }
10581                let (cursor, goal) = movement::down_by_rows(
10582                    map,
10583                    selection.start,
10584                    action.lines,
10585                    selection.goal,
10586                    false,
10587                    text_layout_details,
10588                );
10589                selection.collapse_to(cursor, goal);
10590            });
10591        })
10592    }
10593
10594    pub fn select_down_by_lines(
10595        &mut self,
10596        action: &SelectDownByLines,
10597        window: &mut Window,
10598        cx: &mut Context<Self>,
10599    ) {
10600        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10601        let text_layout_details = &self.text_layout_details(window);
10602        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10603            s.move_heads_with(|map, head, goal| {
10604                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10605            })
10606        })
10607    }
10608
10609    pub fn select_up_by_lines(
10610        &mut self,
10611        action: &SelectUpByLines,
10612        window: &mut Window,
10613        cx: &mut Context<Self>,
10614    ) {
10615        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10616        let text_layout_details = &self.text_layout_details(window);
10617        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10618            s.move_heads_with(|map, head, goal| {
10619                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10620            })
10621        })
10622    }
10623
10624    pub fn select_page_up(
10625        &mut self,
10626        _: &SelectPageUp,
10627        window: &mut Window,
10628        cx: &mut Context<Self>,
10629    ) {
10630        let Some(row_count) = self.visible_row_count() else {
10631            return;
10632        };
10633
10634        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10635
10636        let text_layout_details = &self.text_layout_details(window);
10637
10638        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10639            s.move_heads_with(|map, head, goal| {
10640                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10641            })
10642        })
10643    }
10644
10645    pub fn move_page_up(
10646        &mut self,
10647        action: &MovePageUp,
10648        window: &mut Window,
10649        cx: &mut Context<Self>,
10650    ) {
10651        if self.take_rename(true, window, cx).is_some() {
10652            return;
10653        }
10654
10655        if self
10656            .context_menu
10657            .borrow_mut()
10658            .as_mut()
10659            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10660            .unwrap_or(false)
10661        {
10662            return;
10663        }
10664
10665        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10666            cx.propagate();
10667            return;
10668        }
10669
10670        let Some(row_count) = self.visible_row_count() else {
10671            return;
10672        };
10673
10674        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10675
10676        let autoscroll = if action.center_cursor {
10677            Autoscroll::center()
10678        } else {
10679            Autoscroll::fit()
10680        };
10681
10682        let text_layout_details = &self.text_layout_details(window);
10683
10684        self.change_selections(Some(autoscroll), window, cx, |s| {
10685            s.move_with(|map, selection| {
10686                if !selection.is_empty() {
10687                    selection.goal = SelectionGoal::None;
10688                }
10689                let (cursor, goal) = movement::up_by_rows(
10690                    map,
10691                    selection.end,
10692                    row_count,
10693                    selection.goal,
10694                    false,
10695                    text_layout_details,
10696                );
10697                selection.collapse_to(cursor, goal);
10698            });
10699        });
10700    }
10701
10702    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10703        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10704        let text_layout_details = &self.text_layout_details(window);
10705        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10706            s.move_heads_with(|map, head, goal| {
10707                movement::up(map, head, goal, false, text_layout_details)
10708            })
10709        })
10710    }
10711
10712    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10713        self.take_rename(true, window, cx);
10714
10715        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10716            cx.propagate();
10717            return;
10718        }
10719
10720        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10721
10722        let text_layout_details = &self.text_layout_details(window);
10723        let selection_count = self.selections.count();
10724        let first_selection = self.selections.first_anchor();
10725
10726        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10727            s.move_with(|map, selection| {
10728                if !selection.is_empty() {
10729                    selection.goal = SelectionGoal::None;
10730                }
10731                let (cursor, goal) = movement::down(
10732                    map,
10733                    selection.end,
10734                    selection.goal,
10735                    false,
10736                    text_layout_details,
10737                );
10738                selection.collapse_to(cursor, goal);
10739            });
10740        });
10741
10742        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10743        {
10744            cx.propagate();
10745        }
10746    }
10747
10748    pub fn select_page_down(
10749        &mut self,
10750        _: &SelectPageDown,
10751        window: &mut Window,
10752        cx: &mut Context<Self>,
10753    ) {
10754        let Some(row_count) = self.visible_row_count() else {
10755            return;
10756        };
10757
10758        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10759
10760        let text_layout_details = &self.text_layout_details(window);
10761
10762        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10763            s.move_heads_with(|map, head, goal| {
10764                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10765            })
10766        })
10767    }
10768
10769    pub fn move_page_down(
10770        &mut self,
10771        action: &MovePageDown,
10772        window: &mut Window,
10773        cx: &mut Context<Self>,
10774    ) {
10775        if self.take_rename(true, window, cx).is_some() {
10776            return;
10777        }
10778
10779        if self
10780            .context_menu
10781            .borrow_mut()
10782            .as_mut()
10783            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10784            .unwrap_or(false)
10785        {
10786            return;
10787        }
10788
10789        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10790            cx.propagate();
10791            return;
10792        }
10793
10794        let Some(row_count) = self.visible_row_count() else {
10795            return;
10796        };
10797
10798        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10799
10800        let autoscroll = if action.center_cursor {
10801            Autoscroll::center()
10802        } else {
10803            Autoscroll::fit()
10804        };
10805
10806        let text_layout_details = &self.text_layout_details(window);
10807        self.change_selections(Some(autoscroll), window, cx, |s| {
10808            s.move_with(|map, selection| {
10809                if !selection.is_empty() {
10810                    selection.goal = SelectionGoal::None;
10811                }
10812                let (cursor, goal) = movement::down_by_rows(
10813                    map,
10814                    selection.end,
10815                    row_count,
10816                    selection.goal,
10817                    false,
10818                    text_layout_details,
10819                );
10820                selection.collapse_to(cursor, goal);
10821            });
10822        });
10823    }
10824
10825    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10826        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10827        let text_layout_details = &self.text_layout_details(window);
10828        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10829            s.move_heads_with(|map, head, goal| {
10830                movement::down(map, head, goal, false, text_layout_details)
10831            })
10832        });
10833    }
10834
10835    pub fn context_menu_first(
10836        &mut self,
10837        _: &ContextMenuFirst,
10838        _window: &mut Window,
10839        cx: &mut Context<Self>,
10840    ) {
10841        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10842            context_menu.select_first(self.completion_provider.as_deref(), cx);
10843        }
10844    }
10845
10846    pub fn context_menu_prev(
10847        &mut self,
10848        _: &ContextMenuPrevious,
10849        _window: &mut Window,
10850        cx: &mut Context<Self>,
10851    ) {
10852        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10853            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10854        }
10855    }
10856
10857    pub fn context_menu_next(
10858        &mut self,
10859        _: &ContextMenuNext,
10860        _window: &mut Window,
10861        cx: &mut Context<Self>,
10862    ) {
10863        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10864            context_menu.select_next(self.completion_provider.as_deref(), cx);
10865        }
10866    }
10867
10868    pub fn context_menu_last(
10869        &mut self,
10870        _: &ContextMenuLast,
10871        _window: &mut Window,
10872        cx: &mut Context<Self>,
10873    ) {
10874        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10875            context_menu.select_last(self.completion_provider.as_deref(), cx);
10876        }
10877    }
10878
10879    pub fn move_to_previous_word_start(
10880        &mut self,
10881        _: &MoveToPreviousWordStart,
10882        window: &mut Window,
10883        cx: &mut Context<Self>,
10884    ) {
10885        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10886        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10887            s.move_cursors_with(|map, head, _| {
10888                (
10889                    movement::previous_word_start(map, head),
10890                    SelectionGoal::None,
10891                )
10892            });
10893        })
10894    }
10895
10896    pub fn move_to_previous_subword_start(
10897        &mut self,
10898        _: &MoveToPreviousSubwordStart,
10899        window: &mut Window,
10900        cx: &mut Context<Self>,
10901    ) {
10902        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10903        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10904            s.move_cursors_with(|map, head, _| {
10905                (
10906                    movement::previous_subword_start(map, head),
10907                    SelectionGoal::None,
10908                )
10909            });
10910        })
10911    }
10912
10913    pub fn select_to_previous_word_start(
10914        &mut self,
10915        _: &SelectToPreviousWordStart,
10916        window: &mut Window,
10917        cx: &mut Context<Self>,
10918    ) {
10919        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10920        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10921            s.move_heads_with(|map, head, _| {
10922                (
10923                    movement::previous_word_start(map, head),
10924                    SelectionGoal::None,
10925                )
10926            });
10927        })
10928    }
10929
10930    pub fn select_to_previous_subword_start(
10931        &mut self,
10932        _: &SelectToPreviousSubwordStart,
10933        window: &mut Window,
10934        cx: &mut Context<Self>,
10935    ) {
10936        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10937        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10938            s.move_heads_with(|map, head, _| {
10939                (
10940                    movement::previous_subword_start(map, head),
10941                    SelectionGoal::None,
10942                )
10943            });
10944        })
10945    }
10946
10947    pub fn delete_to_previous_word_start(
10948        &mut self,
10949        action: &DeleteToPreviousWordStart,
10950        window: &mut Window,
10951        cx: &mut Context<Self>,
10952    ) {
10953        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10954        self.transact(window, cx, |this, window, cx| {
10955            this.select_autoclose_pair(window, cx);
10956            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10957                s.move_with(|map, selection| {
10958                    if selection.is_empty() {
10959                        let cursor = if action.ignore_newlines {
10960                            movement::previous_word_start(map, selection.head())
10961                        } else {
10962                            movement::previous_word_start_or_newline(map, selection.head())
10963                        };
10964                        selection.set_head(cursor, SelectionGoal::None);
10965                    }
10966                });
10967            });
10968            this.insert("", window, cx);
10969        });
10970    }
10971
10972    pub fn delete_to_previous_subword_start(
10973        &mut self,
10974        _: &DeleteToPreviousSubwordStart,
10975        window: &mut Window,
10976        cx: &mut Context<Self>,
10977    ) {
10978        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10979        self.transact(window, cx, |this, window, cx| {
10980            this.select_autoclose_pair(window, cx);
10981            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10982                s.move_with(|map, selection| {
10983                    if selection.is_empty() {
10984                        let cursor = movement::previous_subword_start(map, selection.head());
10985                        selection.set_head(cursor, SelectionGoal::None);
10986                    }
10987                });
10988            });
10989            this.insert("", window, cx);
10990        });
10991    }
10992
10993    pub fn move_to_next_word_end(
10994        &mut self,
10995        _: &MoveToNextWordEnd,
10996        window: &mut Window,
10997        cx: &mut Context<Self>,
10998    ) {
10999        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11000        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11001            s.move_cursors_with(|map, head, _| {
11002                (movement::next_word_end(map, head), SelectionGoal::None)
11003            });
11004        })
11005    }
11006
11007    pub fn move_to_next_subword_end(
11008        &mut self,
11009        _: &MoveToNextSubwordEnd,
11010        window: &mut Window,
11011        cx: &mut Context<Self>,
11012    ) {
11013        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11014        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11015            s.move_cursors_with(|map, head, _| {
11016                (movement::next_subword_end(map, head), SelectionGoal::None)
11017            });
11018        })
11019    }
11020
11021    pub fn select_to_next_word_end(
11022        &mut self,
11023        _: &SelectToNextWordEnd,
11024        window: &mut Window,
11025        cx: &mut Context<Self>,
11026    ) {
11027        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11028        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11029            s.move_heads_with(|map, head, _| {
11030                (movement::next_word_end(map, head), SelectionGoal::None)
11031            });
11032        })
11033    }
11034
11035    pub fn select_to_next_subword_end(
11036        &mut self,
11037        _: &SelectToNextSubwordEnd,
11038        window: &mut Window,
11039        cx: &mut Context<Self>,
11040    ) {
11041        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11042        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11043            s.move_heads_with(|map, head, _| {
11044                (movement::next_subword_end(map, head), SelectionGoal::None)
11045            });
11046        })
11047    }
11048
11049    pub fn delete_to_next_word_end(
11050        &mut self,
11051        action: &DeleteToNextWordEnd,
11052        window: &mut Window,
11053        cx: &mut Context<Self>,
11054    ) {
11055        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11056        self.transact(window, cx, |this, window, cx| {
11057            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11058                s.move_with(|map, selection| {
11059                    if selection.is_empty() {
11060                        let cursor = if action.ignore_newlines {
11061                            movement::next_word_end(map, selection.head())
11062                        } else {
11063                            movement::next_word_end_or_newline(map, selection.head())
11064                        };
11065                        selection.set_head(cursor, SelectionGoal::None);
11066                    }
11067                });
11068            });
11069            this.insert("", window, cx);
11070        });
11071    }
11072
11073    pub fn delete_to_next_subword_end(
11074        &mut self,
11075        _: &DeleteToNextSubwordEnd,
11076        window: &mut Window,
11077        cx: &mut Context<Self>,
11078    ) {
11079        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11080        self.transact(window, cx, |this, window, cx| {
11081            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11082                s.move_with(|map, selection| {
11083                    if selection.is_empty() {
11084                        let cursor = movement::next_subword_end(map, selection.head());
11085                        selection.set_head(cursor, SelectionGoal::None);
11086                    }
11087                });
11088            });
11089            this.insert("", window, cx);
11090        });
11091    }
11092
11093    pub fn move_to_beginning_of_line(
11094        &mut self,
11095        action: &MoveToBeginningOfLine,
11096        window: &mut Window,
11097        cx: &mut Context<Self>,
11098    ) {
11099        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11100        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11101            s.move_cursors_with(|map, head, _| {
11102                (
11103                    movement::indented_line_beginning(
11104                        map,
11105                        head,
11106                        action.stop_at_soft_wraps,
11107                        action.stop_at_indent,
11108                    ),
11109                    SelectionGoal::None,
11110                )
11111            });
11112        })
11113    }
11114
11115    pub fn select_to_beginning_of_line(
11116        &mut self,
11117        action: &SelectToBeginningOfLine,
11118        window: &mut Window,
11119        cx: &mut Context<Self>,
11120    ) {
11121        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11122        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11123            s.move_heads_with(|map, head, _| {
11124                (
11125                    movement::indented_line_beginning(
11126                        map,
11127                        head,
11128                        action.stop_at_soft_wraps,
11129                        action.stop_at_indent,
11130                    ),
11131                    SelectionGoal::None,
11132                )
11133            });
11134        });
11135    }
11136
11137    pub fn delete_to_beginning_of_line(
11138        &mut self,
11139        action: &DeleteToBeginningOfLine,
11140        window: &mut Window,
11141        cx: &mut Context<Self>,
11142    ) {
11143        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11144        self.transact(window, cx, |this, window, cx| {
11145            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11146                s.move_with(|_, selection| {
11147                    selection.reversed = true;
11148                });
11149            });
11150
11151            this.select_to_beginning_of_line(
11152                &SelectToBeginningOfLine {
11153                    stop_at_soft_wraps: false,
11154                    stop_at_indent: action.stop_at_indent,
11155                },
11156                window,
11157                cx,
11158            );
11159            this.backspace(&Backspace, window, cx);
11160        });
11161    }
11162
11163    pub fn move_to_end_of_line(
11164        &mut self,
11165        action: &MoveToEndOfLine,
11166        window: &mut Window,
11167        cx: &mut Context<Self>,
11168    ) {
11169        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11170        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11171            s.move_cursors_with(|map, head, _| {
11172                (
11173                    movement::line_end(map, head, action.stop_at_soft_wraps),
11174                    SelectionGoal::None,
11175                )
11176            });
11177        })
11178    }
11179
11180    pub fn select_to_end_of_line(
11181        &mut self,
11182        action: &SelectToEndOfLine,
11183        window: &mut Window,
11184        cx: &mut Context<Self>,
11185    ) {
11186        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11187        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11188            s.move_heads_with(|map, head, _| {
11189                (
11190                    movement::line_end(map, head, action.stop_at_soft_wraps),
11191                    SelectionGoal::None,
11192                )
11193            });
11194        })
11195    }
11196
11197    pub fn delete_to_end_of_line(
11198        &mut self,
11199        _: &DeleteToEndOfLine,
11200        window: &mut Window,
11201        cx: &mut Context<Self>,
11202    ) {
11203        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11204        self.transact(window, cx, |this, window, cx| {
11205            this.select_to_end_of_line(
11206                &SelectToEndOfLine {
11207                    stop_at_soft_wraps: false,
11208                },
11209                window,
11210                cx,
11211            );
11212            this.delete(&Delete, window, cx);
11213        });
11214    }
11215
11216    pub fn cut_to_end_of_line(
11217        &mut self,
11218        _: &CutToEndOfLine,
11219        window: &mut Window,
11220        cx: &mut Context<Self>,
11221    ) {
11222        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11223        self.transact(window, cx, |this, window, cx| {
11224            this.select_to_end_of_line(
11225                &SelectToEndOfLine {
11226                    stop_at_soft_wraps: false,
11227                },
11228                window,
11229                cx,
11230            );
11231            this.cut(&Cut, window, cx);
11232        });
11233    }
11234
11235    pub fn move_to_start_of_paragraph(
11236        &mut self,
11237        _: &MoveToStartOfParagraph,
11238        window: &mut Window,
11239        cx: &mut Context<Self>,
11240    ) {
11241        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11242            cx.propagate();
11243            return;
11244        }
11245        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11246        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11247            s.move_with(|map, selection| {
11248                selection.collapse_to(
11249                    movement::start_of_paragraph(map, selection.head(), 1),
11250                    SelectionGoal::None,
11251                )
11252            });
11253        })
11254    }
11255
11256    pub fn move_to_end_of_paragraph(
11257        &mut self,
11258        _: &MoveToEndOfParagraph,
11259        window: &mut Window,
11260        cx: &mut Context<Self>,
11261    ) {
11262        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11263            cx.propagate();
11264            return;
11265        }
11266        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11267        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11268            s.move_with(|map, selection| {
11269                selection.collapse_to(
11270                    movement::end_of_paragraph(map, selection.head(), 1),
11271                    SelectionGoal::None,
11272                )
11273            });
11274        })
11275    }
11276
11277    pub fn select_to_start_of_paragraph(
11278        &mut self,
11279        _: &SelectToStartOfParagraph,
11280        window: &mut Window,
11281        cx: &mut Context<Self>,
11282    ) {
11283        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11284            cx.propagate();
11285            return;
11286        }
11287        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11288        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11289            s.move_heads_with(|map, head, _| {
11290                (
11291                    movement::start_of_paragraph(map, head, 1),
11292                    SelectionGoal::None,
11293                )
11294            });
11295        })
11296    }
11297
11298    pub fn select_to_end_of_paragraph(
11299        &mut self,
11300        _: &SelectToEndOfParagraph,
11301        window: &mut Window,
11302        cx: &mut Context<Self>,
11303    ) {
11304        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11305            cx.propagate();
11306            return;
11307        }
11308        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11309        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11310            s.move_heads_with(|map, head, _| {
11311                (
11312                    movement::end_of_paragraph(map, head, 1),
11313                    SelectionGoal::None,
11314                )
11315            });
11316        })
11317    }
11318
11319    pub fn move_to_start_of_excerpt(
11320        &mut self,
11321        _: &MoveToStartOfExcerpt,
11322        window: &mut Window,
11323        cx: &mut Context<Self>,
11324    ) {
11325        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11326            cx.propagate();
11327            return;
11328        }
11329        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11330        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11331            s.move_with(|map, selection| {
11332                selection.collapse_to(
11333                    movement::start_of_excerpt(
11334                        map,
11335                        selection.head(),
11336                        workspace::searchable::Direction::Prev,
11337                    ),
11338                    SelectionGoal::None,
11339                )
11340            });
11341        })
11342    }
11343
11344    pub fn move_to_start_of_next_excerpt(
11345        &mut self,
11346        _: &MoveToStartOfNextExcerpt,
11347        window: &mut Window,
11348        cx: &mut Context<Self>,
11349    ) {
11350        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11351            cx.propagate();
11352            return;
11353        }
11354
11355        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11356            s.move_with(|map, selection| {
11357                selection.collapse_to(
11358                    movement::start_of_excerpt(
11359                        map,
11360                        selection.head(),
11361                        workspace::searchable::Direction::Next,
11362                    ),
11363                    SelectionGoal::None,
11364                )
11365            });
11366        })
11367    }
11368
11369    pub fn move_to_end_of_excerpt(
11370        &mut self,
11371        _: &MoveToEndOfExcerpt,
11372        window: &mut Window,
11373        cx: &mut Context<Self>,
11374    ) {
11375        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11376            cx.propagate();
11377            return;
11378        }
11379        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11380        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11381            s.move_with(|map, selection| {
11382                selection.collapse_to(
11383                    movement::end_of_excerpt(
11384                        map,
11385                        selection.head(),
11386                        workspace::searchable::Direction::Next,
11387                    ),
11388                    SelectionGoal::None,
11389                )
11390            });
11391        })
11392    }
11393
11394    pub fn move_to_end_of_previous_excerpt(
11395        &mut self,
11396        _: &MoveToEndOfPreviousExcerpt,
11397        window: &mut Window,
11398        cx: &mut Context<Self>,
11399    ) {
11400        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11401            cx.propagate();
11402            return;
11403        }
11404        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11405        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11406            s.move_with(|map, selection| {
11407                selection.collapse_to(
11408                    movement::end_of_excerpt(
11409                        map,
11410                        selection.head(),
11411                        workspace::searchable::Direction::Prev,
11412                    ),
11413                    SelectionGoal::None,
11414                )
11415            });
11416        })
11417    }
11418
11419    pub fn select_to_start_of_excerpt(
11420        &mut self,
11421        _: &SelectToStartOfExcerpt,
11422        window: &mut Window,
11423        cx: &mut Context<Self>,
11424    ) {
11425        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11426            cx.propagate();
11427            return;
11428        }
11429        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11430        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11431            s.move_heads_with(|map, head, _| {
11432                (
11433                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11434                    SelectionGoal::None,
11435                )
11436            });
11437        })
11438    }
11439
11440    pub fn select_to_start_of_next_excerpt(
11441        &mut self,
11442        _: &SelectToStartOfNextExcerpt,
11443        window: &mut Window,
11444        cx: &mut Context<Self>,
11445    ) {
11446        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11447            cx.propagate();
11448            return;
11449        }
11450        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11451        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11452            s.move_heads_with(|map, head, _| {
11453                (
11454                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11455                    SelectionGoal::None,
11456                )
11457            });
11458        })
11459    }
11460
11461    pub fn select_to_end_of_excerpt(
11462        &mut self,
11463        _: &SelectToEndOfExcerpt,
11464        window: &mut Window,
11465        cx: &mut Context<Self>,
11466    ) {
11467        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11468            cx.propagate();
11469            return;
11470        }
11471        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11472        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11473            s.move_heads_with(|map, head, _| {
11474                (
11475                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11476                    SelectionGoal::None,
11477                )
11478            });
11479        })
11480    }
11481
11482    pub fn select_to_end_of_previous_excerpt(
11483        &mut self,
11484        _: &SelectToEndOfPreviousExcerpt,
11485        window: &mut Window,
11486        cx: &mut Context<Self>,
11487    ) {
11488        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11489            cx.propagate();
11490            return;
11491        }
11492        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11493        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11494            s.move_heads_with(|map, head, _| {
11495                (
11496                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11497                    SelectionGoal::None,
11498                )
11499            });
11500        })
11501    }
11502
11503    pub fn move_to_beginning(
11504        &mut self,
11505        _: &MoveToBeginning,
11506        window: &mut Window,
11507        cx: &mut Context<Self>,
11508    ) {
11509        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11510            cx.propagate();
11511            return;
11512        }
11513        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11514        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11515            s.select_ranges(vec![0..0]);
11516        });
11517    }
11518
11519    pub fn select_to_beginning(
11520        &mut self,
11521        _: &SelectToBeginning,
11522        window: &mut Window,
11523        cx: &mut Context<Self>,
11524    ) {
11525        let mut selection = self.selections.last::<Point>(cx);
11526        selection.set_head(Point::zero(), SelectionGoal::None);
11527        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11528        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11529            s.select(vec![selection]);
11530        });
11531    }
11532
11533    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11534        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11535            cx.propagate();
11536            return;
11537        }
11538        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11539        let cursor = self.buffer.read(cx).read(cx).len();
11540        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11541            s.select_ranges(vec![cursor..cursor])
11542        });
11543    }
11544
11545    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11546        self.nav_history = nav_history;
11547    }
11548
11549    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11550        self.nav_history.as_ref()
11551    }
11552
11553    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11554        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11555    }
11556
11557    fn push_to_nav_history(
11558        &mut self,
11559        cursor_anchor: Anchor,
11560        new_position: Option<Point>,
11561        is_deactivate: bool,
11562        cx: &mut Context<Self>,
11563    ) {
11564        if let Some(nav_history) = self.nav_history.as_mut() {
11565            let buffer = self.buffer.read(cx).read(cx);
11566            let cursor_position = cursor_anchor.to_point(&buffer);
11567            let scroll_state = self.scroll_manager.anchor();
11568            let scroll_top_row = scroll_state.top_row(&buffer);
11569            drop(buffer);
11570
11571            if let Some(new_position) = new_position {
11572                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11573                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11574                    return;
11575                }
11576            }
11577
11578            nav_history.push(
11579                Some(NavigationData {
11580                    cursor_anchor,
11581                    cursor_position,
11582                    scroll_anchor: scroll_state,
11583                    scroll_top_row,
11584                }),
11585                cx,
11586            );
11587            cx.emit(EditorEvent::PushedToNavHistory {
11588                anchor: cursor_anchor,
11589                is_deactivate,
11590            })
11591        }
11592    }
11593
11594    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11595        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11596        let buffer = self.buffer.read(cx).snapshot(cx);
11597        let mut selection = self.selections.first::<usize>(cx);
11598        selection.set_head(buffer.len(), SelectionGoal::None);
11599        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11600            s.select(vec![selection]);
11601        });
11602    }
11603
11604    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11605        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11606        let end = self.buffer.read(cx).read(cx).len();
11607        self.change_selections(None, window, cx, |s| {
11608            s.select_ranges(vec![0..end]);
11609        });
11610    }
11611
11612    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11613        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11614        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11615        let mut selections = self.selections.all::<Point>(cx);
11616        let max_point = display_map.buffer_snapshot.max_point();
11617        for selection in &mut selections {
11618            let rows = selection.spanned_rows(true, &display_map);
11619            selection.start = Point::new(rows.start.0, 0);
11620            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11621            selection.reversed = false;
11622        }
11623        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11624            s.select(selections);
11625        });
11626    }
11627
11628    pub fn split_selection_into_lines(
11629        &mut self,
11630        _: &SplitSelectionIntoLines,
11631        window: &mut Window,
11632        cx: &mut Context<Self>,
11633    ) {
11634        let selections = self
11635            .selections
11636            .all::<Point>(cx)
11637            .into_iter()
11638            .map(|selection| selection.start..selection.end)
11639            .collect::<Vec<_>>();
11640        self.unfold_ranges(&selections, true, true, cx);
11641
11642        let mut new_selection_ranges = Vec::new();
11643        {
11644            let buffer = self.buffer.read(cx).read(cx);
11645            for selection in selections {
11646                for row in selection.start.row..selection.end.row {
11647                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11648                    new_selection_ranges.push(cursor..cursor);
11649                }
11650
11651                let is_multiline_selection = selection.start.row != selection.end.row;
11652                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11653                // so this action feels more ergonomic when paired with other selection operations
11654                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11655                if !should_skip_last {
11656                    new_selection_ranges.push(selection.end..selection.end);
11657                }
11658            }
11659        }
11660        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11661            s.select_ranges(new_selection_ranges);
11662        });
11663    }
11664
11665    pub fn add_selection_above(
11666        &mut self,
11667        _: &AddSelectionAbove,
11668        window: &mut Window,
11669        cx: &mut Context<Self>,
11670    ) {
11671        self.add_selection(true, window, cx);
11672    }
11673
11674    pub fn add_selection_below(
11675        &mut self,
11676        _: &AddSelectionBelow,
11677        window: &mut Window,
11678        cx: &mut Context<Self>,
11679    ) {
11680        self.add_selection(false, window, cx);
11681    }
11682
11683    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11684        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11685
11686        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11687        let mut selections = self.selections.all::<Point>(cx);
11688        let text_layout_details = self.text_layout_details(window);
11689        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11690            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11691            let range = oldest_selection.display_range(&display_map).sorted();
11692
11693            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11694            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11695            let positions = start_x.min(end_x)..start_x.max(end_x);
11696
11697            selections.clear();
11698            let mut stack = Vec::new();
11699            for row in range.start.row().0..=range.end.row().0 {
11700                if let Some(selection) = self.selections.build_columnar_selection(
11701                    &display_map,
11702                    DisplayRow(row),
11703                    &positions,
11704                    oldest_selection.reversed,
11705                    &text_layout_details,
11706                ) {
11707                    stack.push(selection.id);
11708                    selections.push(selection);
11709                }
11710            }
11711
11712            if above {
11713                stack.reverse();
11714            }
11715
11716            AddSelectionsState { above, stack }
11717        });
11718
11719        let last_added_selection = *state.stack.last().unwrap();
11720        let mut new_selections = Vec::new();
11721        if above == state.above {
11722            let end_row = if above {
11723                DisplayRow(0)
11724            } else {
11725                display_map.max_point().row()
11726            };
11727
11728            'outer: for selection in selections {
11729                if selection.id == last_added_selection {
11730                    let range = selection.display_range(&display_map).sorted();
11731                    debug_assert_eq!(range.start.row(), range.end.row());
11732                    let mut row = range.start.row();
11733                    let positions =
11734                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11735                            px(start)..px(end)
11736                        } else {
11737                            let start_x =
11738                                display_map.x_for_display_point(range.start, &text_layout_details);
11739                            let end_x =
11740                                display_map.x_for_display_point(range.end, &text_layout_details);
11741                            start_x.min(end_x)..start_x.max(end_x)
11742                        };
11743
11744                    while row != end_row {
11745                        if above {
11746                            row.0 -= 1;
11747                        } else {
11748                            row.0 += 1;
11749                        }
11750
11751                        if let Some(new_selection) = self.selections.build_columnar_selection(
11752                            &display_map,
11753                            row,
11754                            &positions,
11755                            selection.reversed,
11756                            &text_layout_details,
11757                        ) {
11758                            state.stack.push(new_selection.id);
11759                            if above {
11760                                new_selections.push(new_selection);
11761                                new_selections.push(selection);
11762                            } else {
11763                                new_selections.push(selection);
11764                                new_selections.push(new_selection);
11765                            }
11766
11767                            continue 'outer;
11768                        }
11769                    }
11770                }
11771
11772                new_selections.push(selection);
11773            }
11774        } else {
11775            new_selections = selections;
11776            new_selections.retain(|s| s.id != last_added_selection);
11777            state.stack.pop();
11778        }
11779
11780        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11781            s.select(new_selections);
11782        });
11783        if state.stack.len() > 1 {
11784            self.add_selections_state = Some(state);
11785        }
11786    }
11787
11788    pub fn select_next_match_internal(
11789        &mut self,
11790        display_map: &DisplaySnapshot,
11791        replace_newest: bool,
11792        autoscroll: Option<Autoscroll>,
11793        window: &mut Window,
11794        cx: &mut Context<Self>,
11795    ) -> Result<()> {
11796        fn select_next_match_ranges(
11797            this: &mut Editor,
11798            range: Range<usize>,
11799            replace_newest: bool,
11800            auto_scroll: Option<Autoscroll>,
11801            window: &mut Window,
11802            cx: &mut Context<Editor>,
11803        ) {
11804            this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11805            this.change_selections(auto_scroll, window, cx, |s| {
11806                if replace_newest {
11807                    s.delete(s.newest_anchor().id);
11808                }
11809                s.insert_range(range.clone());
11810            });
11811        }
11812
11813        let buffer = &display_map.buffer_snapshot;
11814        let mut selections = self.selections.all::<usize>(cx);
11815        if let Some(mut select_next_state) = self.select_next_state.take() {
11816            let query = &select_next_state.query;
11817            if !select_next_state.done {
11818                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11819                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11820                let mut next_selected_range = None;
11821
11822                let bytes_after_last_selection =
11823                    buffer.bytes_in_range(last_selection.end..buffer.len());
11824                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11825                let query_matches = query
11826                    .stream_find_iter(bytes_after_last_selection)
11827                    .map(|result| (last_selection.end, result))
11828                    .chain(
11829                        query
11830                            .stream_find_iter(bytes_before_first_selection)
11831                            .map(|result| (0, result)),
11832                    );
11833
11834                for (start_offset, query_match) in query_matches {
11835                    let query_match = query_match.unwrap(); // can only fail due to I/O
11836                    let offset_range =
11837                        start_offset + query_match.start()..start_offset + query_match.end();
11838                    let display_range = offset_range.start.to_display_point(display_map)
11839                        ..offset_range.end.to_display_point(display_map);
11840
11841                    if !select_next_state.wordwise
11842                        || (!movement::is_inside_word(display_map, display_range.start)
11843                            && !movement::is_inside_word(display_map, display_range.end))
11844                    {
11845                        // TODO: This is n^2, because we might check all the selections
11846                        if !selections
11847                            .iter()
11848                            .any(|selection| selection.range().overlaps(&offset_range))
11849                        {
11850                            next_selected_range = Some(offset_range);
11851                            break;
11852                        }
11853                    }
11854                }
11855
11856                if let Some(next_selected_range) = next_selected_range {
11857                    select_next_match_ranges(
11858                        self,
11859                        next_selected_range,
11860                        replace_newest,
11861                        autoscroll,
11862                        window,
11863                        cx,
11864                    );
11865                } else {
11866                    select_next_state.done = true;
11867                }
11868            }
11869
11870            self.select_next_state = Some(select_next_state);
11871        } else {
11872            let mut only_carets = true;
11873            let mut same_text_selected = true;
11874            let mut selected_text = None;
11875
11876            let mut selections_iter = selections.iter().peekable();
11877            while let Some(selection) = selections_iter.next() {
11878                if selection.start != selection.end {
11879                    only_carets = false;
11880                }
11881
11882                if same_text_selected {
11883                    if selected_text.is_none() {
11884                        selected_text =
11885                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11886                    }
11887
11888                    if let Some(next_selection) = selections_iter.peek() {
11889                        if next_selection.range().len() == selection.range().len() {
11890                            let next_selected_text = buffer
11891                                .text_for_range(next_selection.range())
11892                                .collect::<String>();
11893                            if Some(next_selected_text) != selected_text {
11894                                same_text_selected = false;
11895                                selected_text = None;
11896                            }
11897                        } else {
11898                            same_text_selected = false;
11899                            selected_text = None;
11900                        }
11901                    }
11902                }
11903            }
11904
11905            if only_carets {
11906                for selection in &mut selections {
11907                    let word_range = movement::surrounding_word(
11908                        display_map,
11909                        selection.start.to_display_point(display_map),
11910                    );
11911                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11912                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11913                    selection.goal = SelectionGoal::None;
11914                    selection.reversed = false;
11915                    select_next_match_ranges(
11916                        self,
11917                        selection.start..selection.end,
11918                        replace_newest,
11919                        autoscroll,
11920                        window,
11921                        cx,
11922                    );
11923                }
11924
11925                if selections.len() == 1 {
11926                    let selection = selections
11927                        .last()
11928                        .expect("ensured that there's only one selection");
11929                    let query = buffer
11930                        .text_for_range(selection.start..selection.end)
11931                        .collect::<String>();
11932                    let is_empty = query.is_empty();
11933                    let select_state = SelectNextState {
11934                        query: AhoCorasick::new(&[query])?,
11935                        wordwise: true,
11936                        done: is_empty,
11937                    };
11938                    self.select_next_state = Some(select_state);
11939                } else {
11940                    self.select_next_state = None;
11941                }
11942            } else if let Some(selected_text) = selected_text {
11943                self.select_next_state = Some(SelectNextState {
11944                    query: AhoCorasick::new(&[selected_text])?,
11945                    wordwise: false,
11946                    done: false,
11947                });
11948                self.select_next_match_internal(
11949                    display_map,
11950                    replace_newest,
11951                    autoscroll,
11952                    window,
11953                    cx,
11954                )?;
11955            }
11956        }
11957        Ok(())
11958    }
11959
11960    pub fn select_all_matches(
11961        &mut self,
11962        _action: &SelectAllMatches,
11963        window: &mut Window,
11964        cx: &mut Context<Self>,
11965    ) -> Result<()> {
11966        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11967
11968        self.push_to_selection_history();
11969        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11970
11971        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11972        let Some(select_next_state) = self.select_next_state.as_mut() else {
11973            return Ok(());
11974        };
11975        if select_next_state.done {
11976            return Ok(());
11977        }
11978
11979        let mut new_selections = Vec::new();
11980
11981        let reversed = self.selections.oldest::<usize>(cx).reversed;
11982        let buffer = &display_map.buffer_snapshot;
11983        let query_matches = select_next_state
11984            .query
11985            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11986
11987        for query_match in query_matches.into_iter() {
11988            let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11989            let offset_range = if reversed {
11990                query_match.end()..query_match.start()
11991            } else {
11992                query_match.start()..query_match.end()
11993            };
11994            let display_range = offset_range.start.to_display_point(&display_map)
11995                ..offset_range.end.to_display_point(&display_map);
11996
11997            if !select_next_state.wordwise
11998                || (!movement::is_inside_word(&display_map, display_range.start)
11999                    && !movement::is_inside_word(&display_map, display_range.end))
12000            {
12001                new_selections.push(offset_range.start..offset_range.end);
12002            }
12003        }
12004
12005        select_next_state.done = true;
12006        self.unfold_ranges(&new_selections.clone(), false, false, cx);
12007        self.change_selections(None, window, cx, |selections| {
12008            selections.select_ranges(new_selections)
12009        });
12010
12011        Ok(())
12012    }
12013
12014    pub fn select_next(
12015        &mut self,
12016        action: &SelectNext,
12017        window: &mut Window,
12018        cx: &mut Context<Self>,
12019    ) -> Result<()> {
12020        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12021        self.push_to_selection_history();
12022        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12023        self.select_next_match_internal(
12024            &display_map,
12025            action.replace_newest,
12026            Some(Autoscroll::newest()),
12027            window,
12028            cx,
12029        )?;
12030        Ok(())
12031    }
12032
12033    pub fn select_previous(
12034        &mut self,
12035        action: &SelectPrevious,
12036        window: &mut Window,
12037        cx: &mut Context<Self>,
12038    ) -> Result<()> {
12039        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12040        self.push_to_selection_history();
12041        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12042        let buffer = &display_map.buffer_snapshot;
12043        let mut selections = self.selections.all::<usize>(cx);
12044        if let Some(mut select_prev_state) = self.select_prev_state.take() {
12045            let query = &select_prev_state.query;
12046            if !select_prev_state.done {
12047                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12048                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12049                let mut next_selected_range = None;
12050                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12051                let bytes_before_last_selection =
12052                    buffer.reversed_bytes_in_range(0..last_selection.start);
12053                let bytes_after_first_selection =
12054                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12055                let query_matches = query
12056                    .stream_find_iter(bytes_before_last_selection)
12057                    .map(|result| (last_selection.start, result))
12058                    .chain(
12059                        query
12060                            .stream_find_iter(bytes_after_first_selection)
12061                            .map(|result| (buffer.len(), result)),
12062                    );
12063                for (end_offset, query_match) in query_matches {
12064                    let query_match = query_match.unwrap(); // can only fail due to I/O
12065                    let offset_range =
12066                        end_offset - query_match.end()..end_offset - query_match.start();
12067                    let display_range = offset_range.start.to_display_point(&display_map)
12068                        ..offset_range.end.to_display_point(&display_map);
12069
12070                    if !select_prev_state.wordwise
12071                        || (!movement::is_inside_word(&display_map, display_range.start)
12072                            && !movement::is_inside_word(&display_map, display_range.end))
12073                    {
12074                        next_selected_range = Some(offset_range);
12075                        break;
12076                    }
12077                }
12078
12079                if let Some(next_selected_range) = next_selected_range {
12080                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12081                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12082                        if action.replace_newest {
12083                            s.delete(s.newest_anchor().id);
12084                        }
12085                        s.insert_range(next_selected_range);
12086                    });
12087                } else {
12088                    select_prev_state.done = true;
12089                }
12090            }
12091
12092            self.select_prev_state = Some(select_prev_state);
12093        } else {
12094            let mut only_carets = true;
12095            let mut same_text_selected = true;
12096            let mut selected_text = None;
12097
12098            let mut selections_iter = selections.iter().peekable();
12099            while let Some(selection) = selections_iter.next() {
12100                if selection.start != selection.end {
12101                    only_carets = false;
12102                }
12103
12104                if same_text_selected {
12105                    if selected_text.is_none() {
12106                        selected_text =
12107                            Some(buffer.text_for_range(selection.range()).collect::<String>());
12108                    }
12109
12110                    if let Some(next_selection) = selections_iter.peek() {
12111                        if next_selection.range().len() == selection.range().len() {
12112                            let next_selected_text = buffer
12113                                .text_for_range(next_selection.range())
12114                                .collect::<String>();
12115                            if Some(next_selected_text) != selected_text {
12116                                same_text_selected = false;
12117                                selected_text = None;
12118                            }
12119                        } else {
12120                            same_text_selected = false;
12121                            selected_text = None;
12122                        }
12123                    }
12124                }
12125            }
12126
12127            if only_carets {
12128                for selection in &mut selections {
12129                    let word_range = movement::surrounding_word(
12130                        &display_map,
12131                        selection.start.to_display_point(&display_map),
12132                    );
12133                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12134                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12135                    selection.goal = SelectionGoal::None;
12136                    selection.reversed = false;
12137                }
12138                if selections.len() == 1 {
12139                    let selection = selections
12140                        .last()
12141                        .expect("ensured that there's only one selection");
12142                    let query = buffer
12143                        .text_for_range(selection.start..selection.end)
12144                        .collect::<String>();
12145                    let is_empty = query.is_empty();
12146                    let select_state = SelectNextState {
12147                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12148                        wordwise: true,
12149                        done: is_empty,
12150                    };
12151                    self.select_prev_state = Some(select_state);
12152                } else {
12153                    self.select_prev_state = None;
12154                }
12155
12156                self.unfold_ranges(
12157                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12158                    false,
12159                    true,
12160                    cx,
12161                );
12162                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12163                    s.select(selections);
12164                });
12165            } else if let Some(selected_text) = selected_text {
12166                self.select_prev_state = Some(SelectNextState {
12167                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12168                    wordwise: false,
12169                    done: false,
12170                });
12171                self.select_previous(action, window, cx)?;
12172            }
12173        }
12174        Ok(())
12175    }
12176
12177    pub fn find_next_match(
12178        &mut self,
12179        _: &FindNextMatch,
12180        window: &mut Window,
12181        cx: &mut Context<Self>,
12182    ) -> Result<()> {
12183        let selections = self.selections.disjoint_anchors();
12184        match selections.first() {
12185            Some(first) if selections.len() >= 2 => {
12186                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12187                    s.select_ranges([first.range()]);
12188                });
12189            }
12190            _ => self.select_next(
12191                &SelectNext {
12192                    replace_newest: true,
12193                },
12194                window,
12195                cx,
12196            )?,
12197        }
12198        Ok(())
12199    }
12200
12201    pub fn find_previous_match(
12202        &mut self,
12203        _: &FindPreviousMatch,
12204        window: &mut Window,
12205        cx: &mut Context<Self>,
12206    ) -> Result<()> {
12207        let selections = self.selections.disjoint_anchors();
12208        match selections.last() {
12209            Some(last) if selections.len() >= 2 => {
12210                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12211                    s.select_ranges([last.range()]);
12212                });
12213            }
12214            _ => self.select_previous(
12215                &SelectPrevious {
12216                    replace_newest: true,
12217                },
12218                window,
12219                cx,
12220            )?,
12221        }
12222        Ok(())
12223    }
12224
12225    pub fn toggle_comments(
12226        &mut self,
12227        action: &ToggleComments,
12228        window: &mut Window,
12229        cx: &mut Context<Self>,
12230    ) {
12231        if self.read_only(cx) {
12232            return;
12233        }
12234        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12235        let text_layout_details = &self.text_layout_details(window);
12236        self.transact(window, cx, |this, window, cx| {
12237            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12238            let mut edits = Vec::new();
12239            let mut selection_edit_ranges = Vec::new();
12240            let mut last_toggled_row = None;
12241            let snapshot = this.buffer.read(cx).read(cx);
12242            let empty_str: Arc<str> = Arc::default();
12243            let mut suffixes_inserted = Vec::new();
12244            let ignore_indent = action.ignore_indent;
12245
12246            fn comment_prefix_range(
12247                snapshot: &MultiBufferSnapshot,
12248                row: MultiBufferRow,
12249                comment_prefix: &str,
12250                comment_prefix_whitespace: &str,
12251                ignore_indent: bool,
12252            ) -> Range<Point> {
12253                let indent_size = if ignore_indent {
12254                    0
12255                } else {
12256                    snapshot.indent_size_for_line(row).len
12257                };
12258
12259                let start = Point::new(row.0, indent_size);
12260
12261                let mut line_bytes = snapshot
12262                    .bytes_in_range(start..snapshot.max_point())
12263                    .flatten()
12264                    .copied();
12265
12266                // If this line currently begins with the line comment prefix, then record
12267                // the range containing the prefix.
12268                if line_bytes
12269                    .by_ref()
12270                    .take(comment_prefix.len())
12271                    .eq(comment_prefix.bytes())
12272                {
12273                    // Include any whitespace that matches the comment prefix.
12274                    let matching_whitespace_len = line_bytes
12275                        .zip(comment_prefix_whitespace.bytes())
12276                        .take_while(|(a, b)| a == b)
12277                        .count() as u32;
12278                    let end = Point::new(
12279                        start.row,
12280                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12281                    );
12282                    start..end
12283                } else {
12284                    start..start
12285                }
12286            }
12287
12288            fn comment_suffix_range(
12289                snapshot: &MultiBufferSnapshot,
12290                row: MultiBufferRow,
12291                comment_suffix: &str,
12292                comment_suffix_has_leading_space: bool,
12293            ) -> Range<Point> {
12294                let end = Point::new(row.0, snapshot.line_len(row));
12295                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12296
12297                let mut line_end_bytes = snapshot
12298                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12299                    .flatten()
12300                    .copied();
12301
12302                let leading_space_len = if suffix_start_column > 0
12303                    && line_end_bytes.next() == Some(b' ')
12304                    && comment_suffix_has_leading_space
12305                {
12306                    1
12307                } else {
12308                    0
12309                };
12310
12311                // If this line currently begins with the line comment prefix, then record
12312                // the range containing the prefix.
12313                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12314                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
12315                    start..end
12316                } else {
12317                    end..end
12318                }
12319            }
12320
12321            // TODO: Handle selections that cross excerpts
12322            for selection in &mut selections {
12323                let start_column = snapshot
12324                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12325                    .len;
12326                let language = if let Some(language) =
12327                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12328                {
12329                    language
12330                } else {
12331                    continue;
12332                };
12333
12334                selection_edit_ranges.clear();
12335
12336                // If multiple selections contain a given row, avoid processing that
12337                // row more than once.
12338                let mut start_row = MultiBufferRow(selection.start.row);
12339                if last_toggled_row == Some(start_row) {
12340                    start_row = start_row.next_row();
12341                }
12342                let end_row =
12343                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12344                        MultiBufferRow(selection.end.row - 1)
12345                    } else {
12346                        MultiBufferRow(selection.end.row)
12347                    };
12348                last_toggled_row = Some(end_row);
12349
12350                if start_row > end_row {
12351                    continue;
12352                }
12353
12354                // If the language has line comments, toggle those.
12355                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12356
12357                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12358                if ignore_indent {
12359                    full_comment_prefixes = full_comment_prefixes
12360                        .into_iter()
12361                        .map(|s| Arc::from(s.trim_end()))
12362                        .collect();
12363                }
12364
12365                if !full_comment_prefixes.is_empty() {
12366                    let first_prefix = full_comment_prefixes
12367                        .first()
12368                        .expect("prefixes is non-empty");
12369                    let prefix_trimmed_lengths = full_comment_prefixes
12370                        .iter()
12371                        .map(|p| p.trim_end_matches(' ').len())
12372                        .collect::<SmallVec<[usize; 4]>>();
12373
12374                    let mut all_selection_lines_are_comments = true;
12375
12376                    for row in start_row.0..=end_row.0 {
12377                        let row = MultiBufferRow(row);
12378                        if start_row < end_row && snapshot.is_line_blank(row) {
12379                            continue;
12380                        }
12381
12382                        let prefix_range = full_comment_prefixes
12383                            .iter()
12384                            .zip(prefix_trimmed_lengths.iter().copied())
12385                            .map(|(prefix, trimmed_prefix_len)| {
12386                                comment_prefix_range(
12387                                    snapshot.deref(),
12388                                    row,
12389                                    &prefix[..trimmed_prefix_len],
12390                                    &prefix[trimmed_prefix_len..],
12391                                    ignore_indent,
12392                                )
12393                            })
12394                            .max_by_key(|range| range.end.column - range.start.column)
12395                            .expect("prefixes is non-empty");
12396
12397                        if prefix_range.is_empty() {
12398                            all_selection_lines_are_comments = false;
12399                        }
12400
12401                        selection_edit_ranges.push(prefix_range);
12402                    }
12403
12404                    if all_selection_lines_are_comments {
12405                        edits.extend(
12406                            selection_edit_ranges
12407                                .iter()
12408                                .cloned()
12409                                .map(|range| (range, empty_str.clone())),
12410                        );
12411                    } else {
12412                        let min_column = selection_edit_ranges
12413                            .iter()
12414                            .map(|range| range.start.column)
12415                            .min()
12416                            .unwrap_or(0);
12417                        edits.extend(selection_edit_ranges.iter().map(|range| {
12418                            let position = Point::new(range.start.row, min_column);
12419                            (position..position, first_prefix.clone())
12420                        }));
12421                    }
12422                } else if let Some((full_comment_prefix, comment_suffix)) =
12423                    language.block_comment_delimiters()
12424                {
12425                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12426                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12427                    let prefix_range = comment_prefix_range(
12428                        snapshot.deref(),
12429                        start_row,
12430                        comment_prefix,
12431                        comment_prefix_whitespace,
12432                        ignore_indent,
12433                    );
12434                    let suffix_range = comment_suffix_range(
12435                        snapshot.deref(),
12436                        end_row,
12437                        comment_suffix.trim_start_matches(' '),
12438                        comment_suffix.starts_with(' '),
12439                    );
12440
12441                    if prefix_range.is_empty() || suffix_range.is_empty() {
12442                        edits.push((
12443                            prefix_range.start..prefix_range.start,
12444                            full_comment_prefix.clone(),
12445                        ));
12446                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12447                        suffixes_inserted.push((end_row, comment_suffix.len()));
12448                    } else {
12449                        edits.push((prefix_range, empty_str.clone()));
12450                        edits.push((suffix_range, empty_str.clone()));
12451                    }
12452                } else {
12453                    continue;
12454                }
12455            }
12456
12457            drop(snapshot);
12458            this.buffer.update(cx, |buffer, cx| {
12459                buffer.edit(edits, None, cx);
12460            });
12461
12462            // Adjust selections so that they end before any comment suffixes that
12463            // were inserted.
12464            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12465            let mut selections = this.selections.all::<Point>(cx);
12466            let snapshot = this.buffer.read(cx).read(cx);
12467            for selection in &mut selections {
12468                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12469                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12470                        Ordering::Less => {
12471                            suffixes_inserted.next();
12472                            continue;
12473                        }
12474                        Ordering::Greater => break,
12475                        Ordering::Equal => {
12476                            if selection.end.column == snapshot.line_len(row) {
12477                                if selection.is_empty() {
12478                                    selection.start.column -= suffix_len as u32;
12479                                }
12480                                selection.end.column -= suffix_len as u32;
12481                            }
12482                            break;
12483                        }
12484                    }
12485                }
12486            }
12487
12488            drop(snapshot);
12489            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12490                s.select(selections)
12491            });
12492
12493            let selections = this.selections.all::<Point>(cx);
12494            let selections_on_single_row = selections.windows(2).all(|selections| {
12495                selections[0].start.row == selections[1].start.row
12496                    && selections[0].end.row == selections[1].end.row
12497                    && selections[0].start.row == selections[0].end.row
12498            });
12499            let selections_selecting = selections
12500                .iter()
12501                .any(|selection| selection.start != selection.end);
12502            let advance_downwards = action.advance_downwards
12503                && selections_on_single_row
12504                && !selections_selecting
12505                && !matches!(this.mode, EditorMode::SingleLine { .. });
12506
12507            if advance_downwards {
12508                let snapshot = this.buffer.read(cx).snapshot(cx);
12509
12510                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12511                    s.move_cursors_with(|display_snapshot, display_point, _| {
12512                        let mut point = display_point.to_point(display_snapshot);
12513                        point.row += 1;
12514                        point = snapshot.clip_point(point, Bias::Left);
12515                        let display_point = point.to_display_point(display_snapshot);
12516                        let goal = SelectionGoal::HorizontalPosition(
12517                            display_snapshot
12518                                .x_for_display_point(display_point, text_layout_details)
12519                                .into(),
12520                        );
12521                        (display_point, goal)
12522                    })
12523                });
12524            }
12525        });
12526    }
12527
12528    pub fn select_enclosing_symbol(
12529        &mut self,
12530        _: &SelectEnclosingSymbol,
12531        window: &mut Window,
12532        cx: &mut Context<Self>,
12533    ) {
12534        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12535
12536        let buffer = self.buffer.read(cx).snapshot(cx);
12537        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12538
12539        fn update_selection(
12540            selection: &Selection<usize>,
12541            buffer_snap: &MultiBufferSnapshot,
12542        ) -> Option<Selection<usize>> {
12543            let cursor = selection.head();
12544            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12545            for symbol in symbols.iter().rev() {
12546                let start = symbol.range.start.to_offset(buffer_snap);
12547                let end = symbol.range.end.to_offset(buffer_snap);
12548                let new_range = start..end;
12549                if start < selection.start || end > selection.end {
12550                    return Some(Selection {
12551                        id: selection.id,
12552                        start: new_range.start,
12553                        end: new_range.end,
12554                        goal: SelectionGoal::None,
12555                        reversed: selection.reversed,
12556                    });
12557                }
12558            }
12559            None
12560        }
12561
12562        let mut selected_larger_symbol = false;
12563        let new_selections = old_selections
12564            .iter()
12565            .map(|selection| match update_selection(selection, &buffer) {
12566                Some(new_selection) => {
12567                    if new_selection.range() != selection.range() {
12568                        selected_larger_symbol = true;
12569                    }
12570                    new_selection
12571                }
12572                None => selection.clone(),
12573            })
12574            .collect::<Vec<_>>();
12575
12576        if selected_larger_symbol {
12577            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12578                s.select(new_selections);
12579            });
12580        }
12581    }
12582
12583    pub fn select_larger_syntax_node(
12584        &mut self,
12585        _: &SelectLargerSyntaxNode,
12586        window: &mut Window,
12587        cx: &mut Context<Self>,
12588    ) {
12589        let Some(visible_row_count) = self.visible_row_count() else {
12590            return;
12591        };
12592        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12593        if old_selections.is_empty() {
12594            return;
12595        }
12596
12597        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12598
12599        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12600        let buffer = self.buffer.read(cx).snapshot(cx);
12601
12602        let mut selected_larger_node = false;
12603        let mut new_selections = old_selections
12604            .iter()
12605            .map(|selection| {
12606                let old_range = selection.start..selection.end;
12607
12608                if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12609                    // manually select word at selection
12610                    if ["string_content", "inline"].contains(&node.kind()) {
12611                        let word_range = {
12612                            let display_point = buffer
12613                                .offset_to_point(old_range.start)
12614                                .to_display_point(&display_map);
12615                            let Range { start, end } =
12616                                movement::surrounding_word(&display_map, display_point);
12617                            start.to_point(&display_map).to_offset(&buffer)
12618                                ..end.to_point(&display_map).to_offset(&buffer)
12619                        };
12620                        // ignore if word is already selected
12621                        if !word_range.is_empty() && old_range != word_range {
12622                            let last_word_range = {
12623                                let display_point = buffer
12624                                    .offset_to_point(old_range.end)
12625                                    .to_display_point(&display_map);
12626                                let Range { start, end } =
12627                                    movement::surrounding_word(&display_map, display_point);
12628                                start.to_point(&display_map).to_offset(&buffer)
12629                                    ..end.to_point(&display_map).to_offset(&buffer)
12630                            };
12631                            // only select word if start and end point belongs to same word
12632                            if word_range == last_word_range {
12633                                selected_larger_node = true;
12634                                return Selection {
12635                                    id: selection.id,
12636                                    start: word_range.start,
12637                                    end: word_range.end,
12638                                    goal: SelectionGoal::None,
12639                                    reversed: selection.reversed,
12640                                };
12641                            }
12642                        }
12643                    }
12644                }
12645
12646                let mut new_range = old_range.clone();
12647                let mut new_node = None;
12648                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12649                {
12650                    new_node = Some(node);
12651                    new_range = match containing_range {
12652                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12653                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12654                    };
12655                    if !display_map.intersects_fold(new_range.start)
12656                        && !display_map.intersects_fold(new_range.end)
12657                    {
12658                        break;
12659                    }
12660                }
12661
12662                if let Some(node) = new_node {
12663                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12664                    // nodes. Parent and grandparent are also logged because this operation will not
12665                    // visit nodes that have the same range as their parent.
12666                    log::info!("Node: {node:?}");
12667                    let parent = node.parent();
12668                    log::info!("Parent: {parent:?}");
12669                    let grandparent = parent.and_then(|x| x.parent());
12670                    log::info!("Grandparent: {grandparent:?}");
12671                }
12672
12673                selected_larger_node |= new_range != old_range;
12674                Selection {
12675                    id: selection.id,
12676                    start: new_range.start,
12677                    end: new_range.end,
12678                    goal: SelectionGoal::None,
12679                    reversed: selection.reversed,
12680                }
12681            })
12682            .collect::<Vec<_>>();
12683
12684        if !selected_larger_node {
12685            return; // don't put this call in the history
12686        }
12687
12688        // scroll based on transformation done to the last selection created by the user
12689        let (last_old, last_new) = old_selections
12690            .last()
12691            .zip(new_selections.last().cloned())
12692            .expect("old_selections isn't empty");
12693
12694        // revert selection
12695        let is_selection_reversed = {
12696            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12697            new_selections.last_mut().expect("checked above").reversed =
12698                should_newest_selection_be_reversed;
12699            should_newest_selection_be_reversed
12700        };
12701
12702        if selected_larger_node {
12703            self.select_syntax_node_history.disable_clearing = true;
12704            self.change_selections(None, window, cx, |s| {
12705                s.select(new_selections.clone());
12706            });
12707            self.select_syntax_node_history.disable_clearing = false;
12708        }
12709
12710        let start_row = last_new.start.to_display_point(&display_map).row().0;
12711        let end_row = last_new.end.to_display_point(&display_map).row().0;
12712        let selection_height = end_row - start_row + 1;
12713        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12714
12715        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12716        let scroll_behavior = if fits_on_the_screen {
12717            self.request_autoscroll(Autoscroll::fit(), cx);
12718            SelectSyntaxNodeScrollBehavior::FitSelection
12719        } else if is_selection_reversed {
12720            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12721            SelectSyntaxNodeScrollBehavior::CursorTop
12722        } else {
12723            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12724            SelectSyntaxNodeScrollBehavior::CursorBottom
12725        };
12726
12727        self.select_syntax_node_history.push((
12728            old_selections,
12729            scroll_behavior,
12730            is_selection_reversed,
12731        ));
12732    }
12733
12734    pub fn select_smaller_syntax_node(
12735        &mut self,
12736        _: &SelectSmallerSyntaxNode,
12737        window: &mut Window,
12738        cx: &mut Context<Self>,
12739    ) {
12740        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12741
12742        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12743            self.select_syntax_node_history.pop()
12744        {
12745            if let Some(selection) = selections.last_mut() {
12746                selection.reversed = is_selection_reversed;
12747            }
12748
12749            self.select_syntax_node_history.disable_clearing = true;
12750            self.change_selections(None, window, cx, |s| {
12751                s.select(selections.to_vec());
12752            });
12753            self.select_syntax_node_history.disable_clearing = false;
12754
12755            match scroll_behavior {
12756                SelectSyntaxNodeScrollBehavior::CursorTop => {
12757                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12758                }
12759                SelectSyntaxNodeScrollBehavior::FitSelection => {
12760                    self.request_autoscroll(Autoscroll::fit(), cx);
12761                }
12762                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12763                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12764                }
12765            }
12766        }
12767    }
12768
12769    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12770        if !EditorSettings::get_global(cx).gutter.runnables {
12771            self.clear_tasks();
12772            return Task::ready(());
12773        }
12774        let project = self.project.as_ref().map(Entity::downgrade);
12775        let task_sources = self.lsp_task_sources(cx);
12776        cx.spawn_in(window, async move |editor, cx| {
12777            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12778            let Some(project) = project.and_then(|p| p.upgrade()) else {
12779                return;
12780            };
12781            let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12782                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12783            }) else {
12784                return;
12785            };
12786
12787            let hide_runnables = project
12788                .update(cx, |project, cx| {
12789                    // Do not display any test indicators in non-dev server remote projects.
12790                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12791                })
12792                .unwrap_or(true);
12793            if hide_runnables {
12794                return;
12795            }
12796            let new_rows =
12797                cx.background_spawn({
12798                    let snapshot = display_snapshot.clone();
12799                    async move {
12800                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12801                    }
12802                })
12803                    .await;
12804            let Ok(lsp_tasks) =
12805                cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12806            else {
12807                return;
12808            };
12809            let lsp_tasks = lsp_tasks.await;
12810
12811            let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12812                lsp_tasks
12813                    .into_iter()
12814                    .flat_map(|(kind, tasks)| {
12815                        tasks.into_iter().filter_map(move |(location, task)| {
12816                            Some((kind.clone(), location?, task))
12817                        })
12818                    })
12819                    .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12820                        let buffer = location.target.buffer;
12821                        let buffer_snapshot = buffer.read(cx).snapshot();
12822                        let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12823                            |(excerpt_id, snapshot, _)| {
12824                                if snapshot.remote_id() == buffer_snapshot.remote_id() {
12825                                    display_snapshot
12826                                        .buffer_snapshot
12827                                        .anchor_in_excerpt(excerpt_id, location.target.range.start)
12828                                } else {
12829                                    None
12830                                }
12831                            },
12832                        );
12833                        if let Some(offset) = offset {
12834                            let task_buffer_range =
12835                                location.target.range.to_point(&buffer_snapshot);
12836                            let context_buffer_range =
12837                                task_buffer_range.to_offset(&buffer_snapshot);
12838                            let context_range = BufferOffset(context_buffer_range.start)
12839                                ..BufferOffset(context_buffer_range.end);
12840
12841                            acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12842                                .or_insert_with(|| RunnableTasks {
12843                                    templates: Vec::new(),
12844                                    offset,
12845                                    column: task_buffer_range.start.column,
12846                                    extra_variables: HashMap::default(),
12847                                    context_range,
12848                                })
12849                                .templates
12850                                .push((kind, task.original_task().clone()));
12851                        }
12852
12853                        acc
12854                    })
12855            }) else {
12856                return;
12857            };
12858
12859            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12860            editor
12861                .update(cx, |editor, _| {
12862                    editor.clear_tasks();
12863                    for (key, mut value) in rows {
12864                        if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12865                            value.templates.extend(lsp_tasks.templates);
12866                        }
12867
12868                        editor.insert_tasks(key, value);
12869                    }
12870                    for (key, value) in lsp_tasks_by_rows {
12871                        editor.insert_tasks(key, value);
12872                    }
12873                })
12874                .ok();
12875        })
12876    }
12877    fn fetch_runnable_ranges(
12878        snapshot: &DisplaySnapshot,
12879        range: Range<Anchor>,
12880    ) -> Vec<language::RunnableRange> {
12881        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12882    }
12883
12884    fn runnable_rows(
12885        project: Entity<Project>,
12886        snapshot: DisplaySnapshot,
12887        runnable_ranges: Vec<RunnableRange>,
12888        mut cx: AsyncWindowContext,
12889    ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12890        runnable_ranges
12891            .into_iter()
12892            .filter_map(|mut runnable| {
12893                let tasks = cx
12894                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12895                    .ok()?;
12896                if tasks.is_empty() {
12897                    return None;
12898                }
12899
12900                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12901
12902                let row = snapshot
12903                    .buffer_snapshot
12904                    .buffer_line_for_row(MultiBufferRow(point.row))?
12905                    .1
12906                    .start
12907                    .row;
12908
12909                let context_range =
12910                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12911                Some((
12912                    (runnable.buffer_id, row),
12913                    RunnableTasks {
12914                        templates: tasks,
12915                        offset: snapshot
12916                            .buffer_snapshot
12917                            .anchor_before(runnable.run_range.start),
12918                        context_range,
12919                        column: point.column,
12920                        extra_variables: runnable.extra_captures,
12921                    },
12922                ))
12923            })
12924            .collect()
12925    }
12926
12927    fn templates_with_tags(
12928        project: &Entity<Project>,
12929        runnable: &mut Runnable,
12930        cx: &mut App,
12931    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12932        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12933            let (worktree_id, file) = project
12934                .buffer_for_id(runnable.buffer, cx)
12935                .and_then(|buffer| buffer.read(cx).file())
12936                .map(|file| (file.worktree_id(cx), file.clone()))
12937                .unzip();
12938
12939            (
12940                project.task_store().read(cx).task_inventory().cloned(),
12941                worktree_id,
12942                file,
12943            )
12944        });
12945
12946        let mut templates_with_tags = mem::take(&mut runnable.tags)
12947            .into_iter()
12948            .flat_map(|RunnableTag(tag)| {
12949                inventory
12950                    .as_ref()
12951                    .into_iter()
12952                    .flat_map(|inventory| {
12953                        inventory.read(cx).list_tasks(
12954                            file.clone(),
12955                            Some(runnable.language.clone()),
12956                            worktree_id,
12957                            cx,
12958                        )
12959                    })
12960                    .filter(move |(_, template)| {
12961                        template.tags.iter().any(|source_tag| source_tag == &tag)
12962                    })
12963            })
12964            .sorted_by_key(|(kind, _)| kind.to_owned())
12965            .collect::<Vec<_>>();
12966        if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12967            // Strongest source wins; if we have worktree tag binding, prefer that to
12968            // global and language bindings;
12969            // if we have a global binding, prefer that to language binding.
12970            let first_mismatch = templates_with_tags
12971                .iter()
12972                .position(|(tag_source, _)| tag_source != leading_tag_source);
12973            if let Some(index) = first_mismatch {
12974                templates_with_tags.truncate(index);
12975            }
12976        }
12977
12978        templates_with_tags
12979    }
12980
12981    pub fn move_to_enclosing_bracket(
12982        &mut self,
12983        _: &MoveToEnclosingBracket,
12984        window: &mut Window,
12985        cx: &mut Context<Self>,
12986    ) {
12987        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12988        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12989            s.move_offsets_with(|snapshot, selection| {
12990                let Some(enclosing_bracket_ranges) =
12991                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12992                else {
12993                    return;
12994                };
12995
12996                let mut best_length = usize::MAX;
12997                let mut best_inside = false;
12998                let mut best_in_bracket_range = false;
12999                let mut best_destination = None;
13000                for (open, close) in enclosing_bracket_ranges {
13001                    let close = close.to_inclusive();
13002                    let length = close.end() - open.start;
13003                    let inside = selection.start >= open.end && selection.end <= *close.start();
13004                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
13005                        || close.contains(&selection.head());
13006
13007                    // If best is next to a bracket and current isn't, skip
13008                    if !in_bracket_range && best_in_bracket_range {
13009                        continue;
13010                    }
13011
13012                    // Prefer smaller lengths unless best is inside and current isn't
13013                    if length > best_length && (best_inside || !inside) {
13014                        continue;
13015                    }
13016
13017                    best_length = length;
13018                    best_inside = inside;
13019                    best_in_bracket_range = in_bracket_range;
13020                    best_destination = Some(
13021                        if close.contains(&selection.start) && close.contains(&selection.end) {
13022                            if inside { open.end } else { open.start }
13023                        } else if inside {
13024                            *close.start()
13025                        } else {
13026                            *close.end()
13027                        },
13028                    );
13029                }
13030
13031                if let Some(destination) = best_destination {
13032                    selection.collapse_to(destination, SelectionGoal::None);
13033                }
13034            })
13035        });
13036    }
13037
13038    pub fn undo_selection(
13039        &mut self,
13040        _: &UndoSelection,
13041        window: &mut Window,
13042        cx: &mut Context<Self>,
13043    ) {
13044        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13045        self.end_selection(window, cx);
13046        self.selection_history.mode = SelectionHistoryMode::Undoing;
13047        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13048            self.change_selections(None, window, cx, |s| {
13049                s.select_anchors(entry.selections.to_vec())
13050            });
13051            self.select_next_state = entry.select_next_state;
13052            self.select_prev_state = entry.select_prev_state;
13053            self.add_selections_state = entry.add_selections_state;
13054            self.request_autoscroll(Autoscroll::newest(), cx);
13055        }
13056        self.selection_history.mode = SelectionHistoryMode::Normal;
13057    }
13058
13059    pub fn redo_selection(
13060        &mut self,
13061        _: &RedoSelection,
13062        window: &mut Window,
13063        cx: &mut Context<Self>,
13064    ) {
13065        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13066        self.end_selection(window, cx);
13067        self.selection_history.mode = SelectionHistoryMode::Redoing;
13068        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13069            self.change_selections(None, window, cx, |s| {
13070                s.select_anchors(entry.selections.to_vec())
13071            });
13072            self.select_next_state = entry.select_next_state;
13073            self.select_prev_state = entry.select_prev_state;
13074            self.add_selections_state = entry.add_selections_state;
13075            self.request_autoscroll(Autoscroll::newest(), cx);
13076        }
13077        self.selection_history.mode = SelectionHistoryMode::Normal;
13078    }
13079
13080    pub fn expand_excerpts(
13081        &mut self,
13082        action: &ExpandExcerpts,
13083        _: &mut Window,
13084        cx: &mut Context<Self>,
13085    ) {
13086        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13087    }
13088
13089    pub fn expand_excerpts_down(
13090        &mut self,
13091        action: &ExpandExcerptsDown,
13092        _: &mut Window,
13093        cx: &mut Context<Self>,
13094    ) {
13095        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13096    }
13097
13098    pub fn expand_excerpts_up(
13099        &mut self,
13100        action: &ExpandExcerptsUp,
13101        _: &mut Window,
13102        cx: &mut Context<Self>,
13103    ) {
13104        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13105    }
13106
13107    pub fn expand_excerpts_for_direction(
13108        &mut self,
13109        lines: u32,
13110        direction: ExpandExcerptDirection,
13111
13112        cx: &mut Context<Self>,
13113    ) {
13114        let selections = self.selections.disjoint_anchors();
13115
13116        let lines = if lines == 0 {
13117            EditorSettings::get_global(cx).expand_excerpt_lines
13118        } else {
13119            lines
13120        };
13121
13122        self.buffer.update(cx, |buffer, cx| {
13123            let snapshot = buffer.snapshot(cx);
13124            let mut excerpt_ids = selections
13125                .iter()
13126                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13127                .collect::<Vec<_>>();
13128            excerpt_ids.sort();
13129            excerpt_ids.dedup();
13130            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13131        })
13132    }
13133
13134    pub fn expand_excerpt(
13135        &mut self,
13136        excerpt: ExcerptId,
13137        direction: ExpandExcerptDirection,
13138        window: &mut Window,
13139        cx: &mut Context<Self>,
13140    ) {
13141        let current_scroll_position = self.scroll_position(cx);
13142        let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13143        let mut should_scroll_up = false;
13144
13145        if direction == ExpandExcerptDirection::Down {
13146            let multi_buffer = self.buffer.read(cx);
13147            let snapshot = multi_buffer.snapshot(cx);
13148            if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13149                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13150                    if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13151                        let buffer_snapshot = buffer.read(cx).snapshot();
13152                        let excerpt_end_row =
13153                            Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13154                        let last_row = buffer_snapshot.max_point().row;
13155                        let lines_below = last_row.saturating_sub(excerpt_end_row);
13156                        should_scroll_up = lines_below >= lines_to_expand;
13157                    }
13158                }
13159            }
13160        }
13161
13162        self.buffer.update(cx, |buffer, cx| {
13163            buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13164        });
13165
13166        if should_scroll_up {
13167            let new_scroll_position =
13168                current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13169            self.set_scroll_position(new_scroll_position, window, cx);
13170        }
13171    }
13172
13173    pub fn go_to_singleton_buffer_point(
13174        &mut self,
13175        point: Point,
13176        window: &mut Window,
13177        cx: &mut Context<Self>,
13178    ) {
13179        self.go_to_singleton_buffer_range(point..point, window, cx);
13180    }
13181
13182    pub fn go_to_singleton_buffer_range(
13183        &mut self,
13184        range: Range<Point>,
13185        window: &mut Window,
13186        cx: &mut Context<Self>,
13187    ) {
13188        let multibuffer = self.buffer().read(cx);
13189        let Some(buffer) = multibuffer.as_singleton() else {
13190            return;
13191        };
13192        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13193            return;
13194        };
13195        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13196            return;
13197        };
13198        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13199            s.select_anchor_ranges([start..end])
13200        });
13201    }
13202
13203    pub fn go_to_diagnostic(
13204        &mut self,
13205        _: &GoToDiagnostic,
13206        window: &mut Window,
13207        cx: &mut Context<Self>,
13208    ) {
13209        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13210        self.go_to_diagnostic_impl(Direction::Next, window, cx)
13211    }
13212
13213    pub fn go_to_prev_diagnostic(
13214        &mut self,
13215        _: &GoToPreviousDiagnostic,
13216        window: &mut Window,
13217        cx: &mut Context<Self>,
13218    ) {
13219        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13220        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13221    }
13222
13223    pub fn go_to_diagnostic_impl(
13224        &mut self,
13225        direction: Direction,
13226        window: &mut Window,
13227        cx: &mut Context<Self>,
13228    ) {
13229        let buffer = self.buffer.read(cx).snapshot(cx);
13230        let selection = self.selections.newest::<usize>(cx);
13231
13232        let mut active_group_id = None;
13233        if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13234            if active_group.active_range.start.to_offset(&buffer) == selection.start {
13235                active_group_id = Some(active_group.group_id);
13236            }
13237        }
13238
13239        fn filtered(
13240            snapshot: EditorSnapshot,
13241            diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13242        ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13243            diagnostics
13244                .filter(|entry| entry.range.start != entry.range.end)
13245                .filter(|entry| !entry.diagnostic.is_unnecessary)
13246                .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13247        }
13248
13249        let snapshot = self.snapshot(window, cx);
13250        let before = filtered(
13251            snapshot.clone(),
13252            buffer
13253                .diagnostics_in_range(0..selection.start)
13254                .filter(|entry| entry.range.start <= selection.start),
13255        );
13256        let after = filtered(
13257            snapshot,
13258            buffer
13259                .diagnostics_in_range(selection.start..buffer.len())
13260                .filter(|entry| entry.range.start >= selection.start),
13261        );
13262
13263        let mut found: Option<DiagnosticEntry<usize>> = None;
13264        if direction == Direction::Prev {
13265            'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13266            {
13267                for diagnostic in prev_diagnostics.into_iter().rev() {
13268                    if diagnostic.range.start != selection.start
13269                        || active_group_id
13270                            .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13271                    {
13272                        found = Some(diagnostic);
13273                        break 'outer;
13274                    }
13275                }
13276            }
13277        } else {
13278            for diagnostic in after.chain(before) {
13279                if diagnostic.range.start != selection.start
13280                    || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13281                {
13282                    found = Some(diagnostic);
13283                    break;
13284                }
13285            }
13286        }
13287        let Some(next_diagnostic) = found else {
13288            return;
13289        };
13290
13291        let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13292            return;
13293        };
13294        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13295            s.select_ranges(vec![
13296                next_diagnostic.range.start..next_diagnostic.range.start,
13297            ])
13298        });
13299        self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13300        self.refresh_inline_completion(false, true, window, cx);
13301    }
13302
13303    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13304        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13305        let snapshot = self.snapshot(window, cx);
13306        let selection = self.selections.newest::<Point>(cx);
13307        self.go_to_hunk_before_or_after_position(
13308            &snapshot,
13309            selection.head(),
13310            Direction::Next,
13311            window,
13312            cx,
13313        );
13314    }
13315
13316    pub fn go_to_hunk_before_or_after_position(
13317        &mut self,
13318        snapshot: &EditorSnapshot,
13319        position: Point,
13320        direction: Direction,
13321        window: &mut Window,
13322        cx: &mut Context<Editor>,
13323    ) {
13324        let row = if direction == Direction::Next {
13325            self.hunk_after_position(snapshot, position)
13326                .map(|hunk| hunk.row_range.start)
13327        } else {
13328            self.hunk_before_position(snapshot, position)
13329        };
13330
13331        if let Some(row) = row {
13332            let destination = Point::new(row.0, 0);
13333            let autoscroll = Autoscroll::center();
13334
13335            self.unfold_ranges(&[destination..destination], false, false, cx);
13336            self.change_selections(Some(autoscroll), window, cx, |s| {
13337                s.select_ranges([destination..destination]);
13338            });
13339        }
13340    }
13341
13342    fn hunk_after_position(
13343        &mut self,
13344        snapshot: &EditorSnapshot,
13345        position: Point,
13346    ) -> Option<MultiBufferDiffHunk> {
13347        snapshot
13348            .buffer_snapshot
13349            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13350            .find(|hunk| hunk.row_range.start.0 > position.row)
13351            .or_else(|| {
13352                snapshot
13353                    .buffer_snapshot
13354                    .diff_hunks_in_range(Point::zero()..position)
13355                    .find(|hunk| hunk.row_range.end.0 < position.row)
13356            })
13357    }
13358
13359    fn go_to_prev_hunk(
13360        &mut self,
13361        _: &GoToPreviousHunk,
13362        window: &mut Window,
13363        cx: &mut Context<Self>,
13364    ) {
13365        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13366        let snapshot = self.snapshot(window, cx);
13367        let selection = self.selections.newest::<Point>(cx);
13368        self.go_to_hunk_before_or_after_position(
13369            &snapshot,
13370            selection.head(),
13371            Direction::Prev,
13372            window,
13373            cx,
13374        );
13375    }
13376
13377    fn hunk_before_position(
13378        &mut self,
13379        snapshot: &EditorSnapshot,
13380        position: Point,
13381    ) -> Option<MultiBufferRow> {
13382        snapshot
13383            .buffer_snapshot
13384            .diff_hunk_before(position)
13385            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13386    }
13387
13388    fn go_to_next_change(
13389        &mut self,
13390        _: &GoToNextChange,
13391        window: &mut Window,
13392        cx: &mut Context<Self>,
13393    ) {
13394        if let Some(selections) = self
13395            .change_list
13396            .next_change(1, Direction::Next)
13397            .map(|s| s.to_vec())
13398        {
13399            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13400                let map = s.display_map();
13401                s.select_display_ranges(selections.iter().map(|a| {
13402                    let point = a.to_display_point(&map);
13403                    point..point
13404                }))
13405            })
13406        }
13407    }
13408
13409    fn go_to_previous_change(
13410        &mut self,
13411        _: &GoToPreviousChange,
13412        window: &mut Window,
13413        cx: &mut Context<Self>,
13414    ) {
13415        if let Some(selections) = self
13416            .change_list
13417            .next_change(1, Direction::Prev)
13418            .map(|s| s.to_vec())
13419        {
13420            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13421                let map = s.display_map();
13422                s.select_display_ranges(selections.iter().map(|a| {
13423                    let point = a.to_display_point(&map);
13424                    point..point
13425                }))
13426            })
13427        }
13428    }
13429
13430    fn go_to_line<T: 'static>(
13431        &mut self,
13432        position: Anchor,
13433        highlight_color: Option<Hsla>,
13434        window: &mut Window,
13435        cx: &mut Context<Self>,
13436    ) {
13437        let snapshot = self.snapshot(window, cx).display_snapshot;
13438        let position = position.to_point(&snapshot.buffer_snapshot);
13439        let start = snapshot
13440            .buffer_snapshot
13441            .clip_point(Point::new(position.row, 0), Bias::Left);
13442        let end = start + Point::new(1, 0);
13443        let start = snapshot.buffer_snapshot.anchor_before(start);
13444        let end = snapshot.buffer_snapshot.anchor_before(end);
13445
13446        self.highlight_rows::<T>(
13447            start..end,
13448            highlight_color
13449                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13450            false,
13451            cx,
13452        );
13453        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13454    }
13455
13456    pub fn go_to_definition(
13457        &mut self,
13458        _: &GoToDefinition,
13459        window: &mut Window,
13460        cx: &mut Context<Self>,
13461    ) -> Task<Result<Navigated>> {
13462        let definition =
13463            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13464        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13465        cx.spawn_in(window, async move |editor, cx| {
13466            if definition.await? == Navigated::Yes {
13467                return Ok(Navigated::Yes);
13468            }
13469            match fallback_strategy {
13470                GoToDefinitionFallback::None => Ok(Navigated::No),
13471                GoToDefinitionFallback::FindAllReferences => {
13472                    match editor.update_in(cx, |editor, window, cx| {
13473                        editor.find_all_references(&FindAllReferences, window, cx)
13474                    })? {
13475                        Some(references) => references.await,
13476                        None => Ok(Navigated::No),
13477                    }
13478                }
13479            }
13480        })
13481    }
13482
13483    pub fn go_to_declaration(
13484        &mut self,
13485        _: &GoToDeclaration,
13486        window: &mut Window,
13487        cx: &mut Context<Self>,
13488    ) -> Task<Result<Navigated>> {
13489        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13490    }
13491
13492    pub fn go_to_declaration_split(
13493        &mut self,
13494        _: &GoToDeclaration,
13495        window: &mut Window,
13496        cx: &mut Context<Self>,
13497    ) -> Task<Result<Navigated>> {
13498        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13499    }
13500
13501    pub fn go_to_implementation(
13502        &mut self,
13503        _: &GoToImplementation,
13504        window: &mut Window,
13505        cx: &mut Context<Self>,
13506    ) -> Task<Result<Navigated>> {
13507        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13508    }
13509
13510    pub fn go_to_implementation_split(
13511        &mut self,
13512        _: &GoToImplementationSplit,
13513        window: &mut Window,
13514        cx: &mut Context<Self>,
13515    ) -> Task<Result<Navigated>> {
13516        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13517    }
13518
13519    pub fn go_to_type_definition(
13520        &mut self,
13521        _: &GoToTypeDefinition,
13522        window: &mut Window,
13523        cx: &mut Context<Self>,
13524    ) -> Task<Result<Navigated>> {
13525        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13526    }
13527
13528    pub fn go_to_definition_split(
13529        &mut self,
13530        _: &GoToDefinitionSplit,
13531        window: &mut Window,
13532        cx: &mut Context<Self>,
13533    ) -> Task<Result<Navigated>> {
13534        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13535    }
13536
13537    pub fn go_to_type_definition_split(
13538        &mut self,
13539        _: &GoToTypeDefinitionSplit,
13540        window: &mut Window,
13541        cx: &mut Context<Self>,
13542    ) -> Task<Result<Navigated>> {
13543        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13544    }
13545
13546    fn go_to_definition_of_kind(
13547        &mut self,
13548        kind: GotoDefinitionKind,
13549        split: bool,
13550        window: &mut Window,
13551        cx: &mut Context<Self>,
13552    ) -> Task<Result<Navigated>> {
13553        let Some(provider) = self.semantics_provider.clone() else {
13554            return Task::ready(Ok(Navigated::No));
13555        };
13556        let head = self.selections.newest::<usize>(cx).head();
13557        let buffer = self.buffer.read(cx);
13558        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13559            text_anchor
13560        } else {
13561            return Task::ready(Ok(Navigated::No));
13562        };
13563
13564        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13565            return Task::ready(Ok(Navigated::No));
13566        };
13567
13568        cx.spawn_in(window, async move |editor, cx| {
13569            let definitions = definitions.await?;
13570            let navigated = editor
13571                .update_in(cx, |editor, window, cx| {
13572                    editor.navigate_to_hover_links(
13573                        Some(kind),
13574                        definitions
13575                            .into_iter()
13576                            .filter(|location| {
13577                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13578                            })
13579                            .map(HoverLink::Text)
13580                            .collect::<Vec<_>>(),
13581                        split,
13582                        window,
13583                        cx,
13584                    )
13585                })?
13586                .await?;
13587            anyhow::Ok(navigated)
13588        })
13589    }
13590
13591    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13592        let selection = self.selections.newest_anchor();
13593        let head = selection.head();
13594        let tail = selection.tail();
13595
13596        let Some((buffer, start_position)) =
13597            self.buffer.read(cx).text_anchor_for_position(head, cx)
13598        else {
13599            return;
13600        };
13601
13602        let end_position = if head != tail {
13603            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13604                return;
13605            };
13606            Some(pos)
13607        } else {
13608            None
13609        };
13610
13611        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13612            let url = if let Some(end_pos) = end_position {
13613                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13614            } else {
13615                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13616            };
13617
13618            if let Some(url) = url {
13619                editor.update(cx, |_, cx| {
13620                    cx.open_url(&url);
13621                })
13622            } else {
13623                Ok(())
13624            }
13625        });
13626
13627        url_finder.detach();
13628    }
13629
13630    pub fn open_selected_filename(
13631        &mut self,
13632        _: &OpenSelectedFilename,
13633        window: &mut Window,
13634        cx: &mut Context<Self>,
13635    ) {
13636        let Some(workspace) = self.workspace() else {
13637            return;
13638        };
13639
13640        let position = self.selections.newest_anchor().head();
13641
13642        let Some((buffer, buffer_position)) =
13643            self.buffer.read(cx).text_anchor_for_position(position, cx)
13644        else {
13645            return;
13646        };
13647
13648        let project = self.project.clone();
13649
13650        cx.spawn_in(window, async move |_, cx| {
13651            let result = find_file(&buffer, project, buffer_position, cx).await;
13652
13653            if let Some((_, path)) = result {
13654                workspace
13655                    .update_in(cx, |workspace, window, cx| {
13656                        workspace.open_resolved_path(path, window, cx)
13657                    })?
13658                    .await?;
13659            }
13660            anyhow::Ok(())
13661        })
13662        .detach();
13663    }
13664
13665    pub(crate) fn navigate_to_hover_links(
13666        &mut self,
13667        kind: Option<GotoDefinitionKind>,
13668        mut definitions: Vec<HoverLink>,
13669        split: bool,
13670        window: &mut Window,
13671        cx: &mut Context<Editor>,
13672    ) -> Task<Result<Navigated>> {
13673        // If there is one definition, just open it directly
13674        if definitions.len() == 1 {
13675            let definition = definitions.pop().unwrap();
13676
13677            enum TargetTaskResult {
13678                Location(Option<Location>),
13679                AlreadyNavigated,
13680            }
13681
13682            let target_task = match definition {
13683                HoverLink::Text(link) => {
13684                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13685                }
13686                HoverLink::InlayHint(lsp_location, server_id) => {
13687                    let computation =
13688                        self.compute_target_location(lsp_location, server_id, window, cx);
13689                    cx.background_spawn(async move {
13690                        let location = computation.await?;
13691                        Ok(TargetTaskResult::Location(location))
13692                    })
13693                }
13694                HoverLink::Url(url) => {
13695                    cx.open_url(&url);
13696                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13697                }
13698                HoverLink::File(path) => {
13699                    if let Some(workspace) = self.workspace() {
13700                        cx.spawn_in(window, async move |_, cx| {
13701                            workspace
13702                                .update_in(cx, |workspace, window, cx| {
13703                                    workspace.open_resolved_path(path, window, cx)
13704                                })?
13705                                .await
13706                                .map(|_| TargetTaskResult::AlreadyNavigated)
13707                        })
13708                    } else {
13709                        Task::ready(Ok(TargetTaskResult::Location(None)))
13710                    }
13711                }
13712            };
13713            cx.spawn_in(window, async move |editor, cx| {
13714                let target = match target_task.await.context("target resolution task")? {
13715                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13716                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13717                    TargetTaskResult::Location(Some(target)) => target,
13718                };
13719
13720                editor.update_in(cx, |editor, window, cx| {
13721                    let Some(workspace) = editor.workspace() else {
13722                        return Navigated::No;
13723                    };
13724                    let pane = workspace.read(cx).active_pane().clone();
13725
13726                    let range = target.range.to_point(target.buffer.read(cx));
13727                    let range = editor.range_for_match(&range);
13728                    let range = collapse_multiline_range(range);
13729
13730                    if !split
13731                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13732                    {
13733                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13734                    } else {
13735                        window.defer(cx, move |window, cx| {
13736                            let target_editor: Entity<Self> =
13737                                workspace.update(cx, |workspace, cx| {
13738                                    let pane = if split {
13739                                        workspace.adjacent_pane(window, cx)
13740                                    } else {
13741                                        workspace.active_pane().clone()
13742                                    };
13743
13744                                    workspace.open_project_item(
13745                                        pane,
13746                                        target.buffer.clone(),
13747                                        true,
13748                                        true,
13749                                        window,
13750                                        cx,
13751                                    )
13752                                });
13753                            target_editor.update(cx, |target_editor, cx| {
13754                                // When selecting a definition in a different buffer, disable the nav history
13755                                // to avoid creating a history entry at the previous cursor location.
13756                                pane.update(cx, |pane, _| pane.disable_history());
13757                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13758                                pane.update(cx, |pane, _| pane.enable_history());
13759                            });
13760                        });
13761                    }
13762                    Navigated::Yes
13763                })
13764            })
13765        } else if !definitions.is_empty() {
13766            cx.spawn_in(window, async move |editor, cx| {
13767                let (title, location_tasks, workspace) = editor
13768                    .update_in(cx, |editor, window, cx| {
13769                        let tab_kind = match kind {
13770                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13771                            _ => "Definitions",
13772                        };
13773                        let title = definitions
13774                            .iter()
13775                            .find_map(|definition| match definition {
13776                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13777                                    let buffer = origin.buffer.read(cx);
13778                                    format!(
13779                                        "{} for {}",
13780                                        tab_kind,
13781                                        buffer
13782                                            .text_for_range(origin.range.clone())
13783                                            .collect::<String>()
13784                                    )
13785                                }),
13786                                HoverLink::InlayHint(_, _) => None,
13787                                HoverLink::Url(_) => None,
13788                                HoverLink::File(_) => None,
13789                            })
13790                            .unwrap_or(tab_kind.to_string());
13791                        let location_tasks = definitions
13792                            .into_iter()
13793                            .map(|definition| match definition {
13794                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13795                                HoverLink::InlayHint(lsp_location, server_id) => editor
13796                                    .compute_target_location(lsp_location, server_id, window, cx),
13797                                HoverLink::Url(_) => Task::ready(Ok(None)),
13798                                HoverLink::File(_) => Task::ready(Ok(None)),
13799                            })
13800                            .collect::<Vec<_>>();
13801                        (title, location_tasks, editor.workspace().clone())
13802                    })
13803                    .context("location tasks preparation")?;
13804
13805                let locations = future::join_all(location_tasks)
13806                    .await
13807                    .into_iter()
13808                    .filter_map(|location| location.transpose())
13809                    .collect::<Result<_>>()
13810                    .context("location tasks")?;
13811
13812                let Some(workspace) = workspace else {
13813                    return Ok(Navigated::No);
13814                };
13815                let opened = workspace
13816                    .update_in(cx, |workspace, window, cx| {
13817                        Self::open_locations_in_multibuffer(
13818                            workspace,
13819                            locations,
13820                            title,
13821                            split,
13822                            MultibufferSelectionMode::First,
13823                            window,
13824                            cx,
13825                        )
13826                    })
13827                    .ok();
13828
13829                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13830            })
13831        } else {
13832            Task::ready(Ok(Navigated::No))
13833        }
13834    }
13835
13836    fn compute_target_location(
13837        &self,
13838        lsp_location: lsp::Location,
13839        server_id: LanguageServerId,
13840        window: &mut Window,
13841        cx: &mut Context<Self>,
13842    ) -> Task<anyhow::Result<Option<Location>>> {
13843        let Some(project) = self.project.clone() else {
13844            return Task::ready(Ok(None));
13845        };
13846
13847        cx.spawn_in(window, async move |editor, cx| {
13848            let location_task = editor.update(cx, |_, cx| {
13849                project.update(cx, |project, cx| {
13850                    let language_server_name = project
13851                        .language_server_statuses(cx)
13852                        .find(|(id, _)| server_id == *id)
13853                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13854                    language_server_name.map(|language_server_name| {
13855                        project.open_local_buffer_via_lsp(
13856                            lsp_location.uri.clone(),
13857                            server_id,
13858                            language_server_name,
13859                            cx,
13860                        )
13861                    })
13862                })
13863            })?;
13864            let location = match location_task {
13865                Some(task) => Some({
13866                    let target_buffer_handle = task.await.context("open local buffer")?;
13867                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13868                        let target_start = target_buffer
13869                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13870                        let target_end = target_buffer
13871                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13872                        target_buffer.anchor_after(target_start)
13873                            ..target_buffer.anchor_before(target_end)
13874                    })?;
13875                    Location {
13876                        buffer: target_buffer_handle,
13877                        range,
13878                    }
13879                }),
13880                None => None,
13881            };
13882            Ok(location)
13883        })
13884    }
13885
13886    pub fn find_all_references(
13887        &mut self,
13888        _: &FindAllReferences,
13889        window: &mut Window,
13890        cx: &mut Context<Self>,
13891    ) -> Option<Task<Result<Navigated>>> {
13892        let selection = self.selections.newest::<usize>(cx);
13893        let multi_buffer = self.buffer.read(cx);
13894        let head = selection.head();
13895
13896        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13897        let head_anchor = multi_buffer_snapshot.anchor_at(
13898            head,
13899            if head < selection.tail() {
13900                Bias::Right
13901            } else {
13902                Bias::Left
13903            },
13904        );
13905
13906        match self
13907            .find_all_references_task_sources
13908            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13909        {
13910            Ok(_) => {
13911                log::info!(
13912                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13913                );
13914                return None;
13915            }
13916            Err(i) => {
13917                self.find_all_references_task_sources.insert(i, head_anchor);
13918            }
13919        }
13920
13921        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13922        let workspace = self.workspace()?;
13923        let project = workspace.read(cx).project().clone();
13924        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13925        Some(cx.spawn_in(window, async move |editor, cx| {
13926            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13927                if let Ok(i) = editor
13928                    .find_all_references_task_sources
13929                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13930                {
13931                    editor.find_all_references_task_sources.remove(i);
13932                }
13933            });
13934
13935            let locations = references.await?;
13936            if locations.is_empty() {
13937                return anyhow::Ok(Navigated::No);
13938            }
13939
13940            workspace.update_in(cx, |workspace, window, cx| {
13941                let title = locations
13942                    .first()
13943                    .as_ref()
13944                    .map(|location| {
13945                        let buffer = location.buffer.read(cx);
13946                        format!(
13947                            "References to `{}`",
13948                            buffer
13949                                .text_for_range(location.range.clone())
13950                                .collect::<String>()
13951                        )
13952                    })
13953                    .unwrap();
13954                Self::open_locations_in_multibuffer(
13955                    workspace,
13956                    locations,
13957                    title,
13958                    false,
13959                    MultibufferSelectionMode::First,
13960                    window,
13961                    cx,
13962                );
13963                Navigated::Yes
13964            })
13965        }))
13966    }
13967
13968    /// Opens a multibuffer with the given project locations in it
13969    pub fn open_locations_in_multibuffer(
13970        workspace: &mut Workspace,
13971        mut locations: Vec<Location>,
13972        title: String,
13973        split: bool,
13974        multibuffer_selection_mode: MultibufferSelectionMode,
13975        window: &mut Window,
13976        cx: &mut Context<Workspace>,
13977    ) {
13978        // If there are multiple definitions, open them in a multibuffer
13979        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13980        let mut locations = locations.into_iter().peekable();
13981        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13982        let capability = workspace.project().read(cx).capability();
13983
13984        let excerpt_buffer = cx.new(|cx| {
13985            let mut multibuffer = MultiBuffer::new(capability);
13986            while let Some(location) = locations.next() {
13987                let buffer = location.buffer.read(cx);
13988                let mut ranges_for_buffer = Vec::new();
13989                let range = location.range.to_point(buffer);
13990                ranges_for_buffer.push(range.clone());
13991
13992                while let Some(next_location) = locations.peek() {
13993                    if next_location.buffer == location.buffer {
13994                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13995                        locations.next();
13996                    } else {
13997                        break;
13998                    }
13999                }
14000
14001                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14002                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14003                    PathKey::for_buffer(&location.buffer, cx),
14004                    location.buffer.clone(),
14005                    ranges_for_buffer,
14006                    DEFAULT_MULTIBUFFER_CONTEXT,
14007                    cx,
14008                );
14009                ranges.extend(new_ranges)
14010            }
14011
14012            multibuffer.with_title(title)
14013        });
14014
14015        let editor = cx.new(|cx| {
14016            Editor::for_multibuffer(
14017                excerpt_buffer,
14018                Some(workspace.project().clone()),
14019                window,
14020                cx,
14021            )
14022        });
14023        editor.update(cx, |editor, cx| {
14024            match multibuffer_selection_mode {
14025                MultibufferSelectionMode::First => {
14026                    if let Some(first_range) = ranges.first() {
14027                        editor.change_selections(None, window, cx, |selections| {
14028                            selections.clear_disjoint();
14029                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14030                        });
14031                    }
14032                    editor.highlight_background::<Self>(
14033                        &ranges,
14034                        |theme| theme.editor_highlighted_line_background,
14035                        cx,
14036                    );
14037                }
14038                MultibufferSelectionMode::All => {
14039                    editor.change_selections(None, window, cx, |selections| {
14040                        selections.clear_disjoint();
14041                        selections.select_anchor_ranges(ranges);
14042                    });
14043                }
14044            }
14045            editor.register_buffers_with_language_servers(cx);
14046        });
14047
14048        let item = Box::new(editor);
14049        let item_id = item.item_id();
14050
14051        if split {
14052            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14053        } else {
14054            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14055                let (preview_item_id, preview_item_idx) =
14056                    workspace.active_pane().update(cx, |pane, _| {
14057                        (pane.preview_item_id(), pane.preview_item_idx())
14058                    });
14059
14060                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14061
14062                if let Some(preview_item_id) = preview_item_id {
14063                    workspace.active_pane().update(cx, |pane, cx| {
14064                        pane.remove_item(preview_item_id, false, false, window, cx);
14065                    });
14066                }
14067            } else {
14068                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14069            }
14070        }
14071        workspace.active_pane().update(cx, |pane, cx| {
14072            pane.set_preview_item_id(Some(item_id), cx);
14073        });
14074    }
14075
14076    pub fn rename(
14077        &mut self,
14078        _: &Rename,
14079        window: &mut Window,
14080        cx: &mut Context<Self>,
14081    ) -> Option<Task<Result<()>>> {
14082        use language::ToOffset as _;
14083
14084        let provider = self.semantics_provider.clone()?;
14085        let selection = self.selections.newest_anchor().clone();
14086        let (cursor_buffer, cursor_buffer_position) = self
14087            .buffer
14088            .read(cx)
14089            .text_anchor_for_position(selection.head(), cx)?;
14090        let (tail_buffer, cursor_buffer_position_end) = self
14091            .buffer
14092            .read(cx)
14093            .text_anchor_for_position(selection.tail(), cx)?;
14094        if tail_buffer != cursor_buffer {
14095            return None;
14096        }
14097
14098        let snapshot = cursor_buffer.read(cx).snapshot();
14099        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14100        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14101        let prepare_rename = provider
14102            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14103            .unwrap_or_else(|| Task::ready(Ok(None)));
14104        drop(snapshot);
14105
14106        Some(cx.spawn_in(window, async move |this, cx| {
14107            let rename_range = if let Some(range) = prepare_rename.await? {
14108                Some(range)
14109            } else {
14110                this.update(cx, |this, cx| {
14111                    let buffer = this.buffer.read(cx).snapshot(cx);
14112                    let mut buffer_highlights = this
14113                        .document_highlights_for_position(selection.head(), &buffer)
14114                        .filter(|highlight| {
14115                            highlight.start.excerpt_id == selection.head().excerpt_id
14116                                && highlight.end.excerpt_id == selection.head().excerpt_id
14117                        });
14118                    buffer_highlights
14119                        .next()
14120                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14121                })?
14122            };
14123            if let Some(rename_range) = rename_range {
14124                this.update_in(cx, |this, window, cx| {
14125                    let snapshot = cursor_buffer.read(cx).snapshot();
14126                    let rename_buffer_range = rename_range.to_offset(&snapshot);
14127                    let cursor_offset_in_rename_range =
14128                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14129                    let cursor_offset_in_rename_range_end =
14130                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14131
14132                    this.take_rename(false, window, cx);
14133                    let buffer = this.buffer.read(cx).read(cx);
14134                    let cursor_offset = selection.head().to_offset(&buffer);
14135                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14136                    let rename_end = rename_start + rename_buffer_range.len();
14137                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14138                    let mut old_highlight_id = None;
14139                    let old_name: Arc<str> = buffer
14140                        .chunks(rename_start..rename_end, true)
14141                        .map(|chunk| {
14142                            if old_highlight_id.is_none() {
14143                                old_highlight_id = chunk.syntax_highlight_id;
14144                            }
14145                            chunk.text
14146                        })
14147                        .collect::<String>()
14148                        .into();
14149
14150                    drop(buffer);
14151
14152                    // Position the selection in the rename editor so that it matches the current selection.
14153                    this.show_local_selections = false;
14154                    let rename_editor = cx.new(|cx| {
14155                        let mut editor = Editor::single_line(window, cx);
14156                        editor.buffer.update(cx, |buffer, cx| {
14157                            buffer.edit([(0..0, old_name.clone())], None, cx)
14158                        });
14159                        let rename_selection_range = match cursor_offset_in_rename_range
14160                            .cmp(&cursor_offset_in_rename_range_end)
14161                        {
14162                            Ordering::Equal => {
14163                                editor.select_all(&SelectAll, window, cx);
14164                                return editor;
14165                            }
14166                            Ordering::Less => {
14167                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14168                            }
14169                            Ordering::Greater => {
14170                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14171                            }
14172                        };
14173                        if rename_selection_range.end > old_name.len() {
14174                            editor.select_all(&SelectAll, window, cx);
14175                        } else {
14176                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14177                                s.select_ranges([rename_selection_range]);
14178                            });
14179                        }
14180                        editor
14181                    });
14182                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14183                        if e == &EditorEvent::Focused {
14184                            cx.emit(EditorEvent::FocusedIn)
14185                        }
14186                    })
14187                    .detach();
14188
14189                    let write_highlights =
14190                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14191                    let read_highlights =
14192                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
14193                    let ranges = write_highlights
14194                        .iter()
14195                        .flat_map(|(_, ranges)| ranges.iter())
14196                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14197                        .cloned()
14198                        .collect();
14199
14200                    this.highlight_text::<Rename>(
14201                        ranges,
14202                        HighlightStyle {
14203                            fade_out: Some(0.6),
14204                            ..Default::default()
14205                        },
14206                        cx,
14207                    );
14208                    let rename_focus_handle = rename_editor.focus_handle(cx);
14209                    window.focus(&rename_focus_handle);
14210                    let block_id = this.insert_blocks(
14211                        [BlockProperties {
14212                            style: BlockStyle::Flex,
14213                            placement: BlockPlacement::Below(range.start),
14214                            height: Some(1),
14215                            render: Arc::new({
14216                                let rename_editor = rename_editor.clone();
14217                                move |cx: &mut BlockContext| {
14218                                    let mut text_style = cx.editor_style.text.clone();
14219                                    if let Some(highlight_style) = old_highlight_id
14220                                        .and_then(|h| h.style(&cx.editor_style.syntax))
14221                                    {
14222                                        text_style = text_style.highlight(highlight_style);
14223                                    }
14224                                    div()
14225                                        .block_mouse_down()
14226                                        .pl(cx.anchor_x)
14227                                        .child(EditorElement::new(
14228                                            &rename_editor,
14229                                            EditorStyle {
14230                                                background: cx.theme().system().transparent,
14231                                                local_player: cx.editor_style.local_player,
14232                                                text: text_style,
14233                                                scrollbar_width: cx.editor_style.scrollbar_width,
14234                                                syntax: cx.editor_style.syntax.clone(),
14235                                                status: cx.editor_style.status.clone(),
14236                                                inlay_hints_style: HighlightStyle {
14237                                                    font_weight: Some(FontWeight::BOLD),
14238                                                    ..make_inlay_hints_style(cx.app)
14239                                                },
14240                                                inline_completion_styles: make_suggestion_styles(
14241                                                    cx.app,
14242                                                ),
14243                                                ..EditorStyle::default()
14244                                            },
14245                                        ))
14246                                        .into_any_element()
14247                                }
14248                            }),
14249                            priority: 0,
14250                        }],
14251                        Some(Autoscroll::fit()),
14252                        cx,
14253                    )[0];
14254                    this.pending_rename = Some(RenameState {
14255                        range,
14256                        old_name,
14257                        editor: rename_editor,
14258                        block_id,
14259                    });
14260                })?;
14261            }
14262
14263            Ok(())
14264        }))
14265    }
14266
14267    pub fn confirm_rename(
14268        &mut self,
14269        _: &ConfirmRename,
14270        window: &mut Window,
14271        cx: &mut Context<Self>,
14272    ) -> Option<Task<Result<()>>> {
14273        let rename = self.take_rename(false, window, cx)?;
14274        let workspace = self.workspace()?.downgrade();
14275        let (buffer, start) = self
14276            .buffer
14277            .read(cx)
14278            .text_anchor_for_position(rename.range.start, cx)?;
14279        let (end_buffer, _) = self
14280            .buffer
14281            .read(cx)
14282            .text_anchor_for_position(rename.range.end, cx)?;
14283        if buffer != end_buffer {
14284            return None;
14285        }
14286
14287        let old_name = rename.old_name;
14288        let new_name = rename.editor.read(cx).text(cx);
14289
14290        let rename = self.semantics_provider.as_ref()?.perform_rename(
14291            &buffer,
14292            start,
14293            new_name.clone(),
14294            cx,
14295        )?;
14296
14297        Some(cx.spawn_in(window, async move |editor, cx| {
14298            let project_transaction = rename.await?;
14299            Self::open_project_transaction(
14300                &editor,
14301                workspace,
14302                project_transaction,
14303                format!("Rename: {}{}", old_name, new_name),
14304                cx,
14305            )
14306            .await?;
14307
14308            editor.update(cx, |editor, cx| {
14309                editor.refresh_document_highlights(cx);
14310            })?;
14311            Ok(())
14312        }))
14313    }
14314
14315    fn take_rename(
14316        &mut self,
14317        moving_cursor: bool,
14318        window: &mut Window,
14319        cx: &mut Context<Self>,
14320    ) -> Option<RenameState> {
14321        let rename = self.pending_rename.take()?;
14322        if rename.editor.focus_handle(cx).is_focused(window) {
14323            window.focus(&self.focus_handle);
14324        }
14325
14326        self.remove_blocks(
14327            [rename.block_id].into_iter().collect(),
14328            Some(Autoscroll::fit()),
14329            cx,
14330        );
14331        self.clear_highlights::<Rename>(cx);
14332        self.show_local_selections = true;
14333
14334        if moving_cursor {
14335            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14336                editor.selections.newest::<usize>(cx).head()
14337            });
14338
14339            // Update the selection to match the position of the selection inside
14340            // the rename editor.
14341            let snapshot = self.buffer.read(cx).read(cx);
14342            let rename_range = rename.range.to_offset(&snapshot);
14343            let cursor_in_editor = snapshot
14344                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14345                .min(rename_range.end);
14346            drop(snapshot);
14347
14348            self.change_selections(None, window, cx, |s| {
14349                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14350            });
14351        } else {
14352            self.refresh_document_highlights(cx);
14353        }
14354
14355        Some(rename)
14356    }
14357
14358    pub fn pending_rename(&self) -> Option<&RenameState> {
14359        self.pending_rename.as_ref()
14360    }
14361
14362    fn format(
14363        &mut self,
14364        _: &Format,
14365        window: &mut Window,
14366        cx: &mut Context<Self>,
14367    ) -> Option<Task<Result<()>>> {
14368        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14369
14370        let project = match &self.project {
14371            Some(project) => project.clone(),
14372            None => return None,
14373        };
14374
14375        Some(self.perform_format(
14376            project,
14377            FormatTrigger::Manual,
14378            FormatTarget::Buffers,
14379            window,
14380            cx,
14381        ))
14382    }
14383
14384    fn format_selections(
14385        &mut self,
14386        _: &FormatSelections,
14387        window: &mut Window,
14388        cx: &mut Context<Self>,
14389    ) -> Option<Task<Result<()>>> {
14390        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14391
14392        let project = match &self.project {
14393            Some(project) => project.clone(),
14394            None => return None,
14395        };
14396
14397        let ranges = self
14398            .selections
14399            .all_adjusted(cx)
14400            .into_iter()
14401            .map(|selection| selection.range())
14402            .collect_vec();
14403
14404        Some(self.perform_format(
14405            project,
14406            FormatTrigger::Manual,
14407            FormatTarget::Ranges(ranges),
14408            window,
14409            cx,
14410        ))
14411    }
14412
14413    fn perform_format(
14414        &mut self,
14415        project: Entity<Project>,
14416        trigger: FormatTrigger,
14417        target: FormatTarget,
14418        window: &mut Window,
14419        cx: &mut Context<Self>,
14420    ) -> Task<Result<()>> {
14421        let buffer = self.buffer.clone();
14422        let (buffers, target) = match target {
14423            FormatTarget::Buffers => {
14424                let mut buffers = buffer.read(cx).all_buffers();
14425                if trigger == FormatTrigger::Save {
14426                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14427                }
14428                (buffers, LspFormatTarget::Buffers)
14429            }
14430            FormatTarget::Ranges(selection_ranges) => {
14431                let multi_buffer = buffer.read(cx);
14432                let snapshot = multi_buffer.read(cx);
14433                let mut buffers = HashSet::default();
14434                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14435                    BTreeMap::new();
14436                for selection_range in selection_ranges {
14437                    for (buffer, buffer_range, _) in
14438                        snapshot.range_to_buffer_ranges(selection_range)
14439                    {
14440                        let buffer_id = buffer.remote_id();
14441                        let start = buffer.anchor_before(buffer_range.start);
14442                        let end = buffer.anchor_after(buffer_range.end);
14443                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14444                        buffer_id_to_ranges
14445                            .entry(buffer_id)
14446                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14447                            .or_insert_with(|| vec![start..end]);
14448                    }
14449                }
14450                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14451            }
14452        };
14453
14454        let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14455        let selections_prev = transaction_id_prev
14456            .and_then(|transaction_id_prev| {
14457                // default to selections as they were after the last edit, if we have them,
14458                // instead of how they are now.
14459                // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14460                // will take you back to where you made the last edit, instead of staying where you scrolled
14461                self.selection_history
14462                    .transaction(transaction_id_prev)
14463                    .map(|t| t.0.clone())
14464            })
14465            .unwrap_or_else(|| {
14466                log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14467                self.selections.disjoint_anchors()
14468            });
14469
14470        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14471        let format = project.update(cx, |project, cx| {
14472            project.format(buffers, target, true, trigger, cx)
14473        });
14474
14475        cx.spawn_in(window, async move |editor, cx| {
14476            let transaction = futures::select_biased! {
14477                transaction = format.log_err().fuse() => transaction,
14478                () = timeout => {
14479                    log::warn!("timed out waiting for formatting");
14480                    None
14481                }
14482            };
14483
14484            buffer
14485                .update(cx, |buffer, cx| {
14486                    if let Some(transaction) = transaction {
14487                        if !buffer.is_singleton() {
14488                            buffer.push_transaction(&transaction.0, cx);
14489                        }
14490                    }
14491                    cx.notify();
14492                })
14493                .ok();
14494
14495            if let Some(transaction_id_now) =
14496                buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14497            {
14498                let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14499                if has_new_transaction {
14500                    _ = editor.update(cx, |editor, _| {
14501                        editor
14502                            .selection_history
14503                            .insert_transaction(transaction_id_now, selections_prev);
14504                    });
14505                }
14506            }
14507
14508            Ok(())
14509        })
14510    }
14511
14512    fn organize_imports(
14513        &mut self,
14514        _: &OrganizeImports,
14515        window: &mut Window,
14516        cx: &mut Context<Self>,
14517    ) -> Option<Task<Result<()>>> {
14518        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14519        let project = match &self.project {
14520            Some(project) => project.clone(),
14521            None => return None,
14522        };
14523        Some(self.perform_code_action_kind(
14524            project,
14525            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14526            window,
14527            cx,
14528        ))
14529    }
14530
14531    fn perform_code_action_kind(
14532        &mut self,
14533        project: Entity<Project>,
14534        kind: CodeActionKind,
14535        window: &mut Window,
14536        cx: &mut Context<Self>,
14537    ) -> Task<Result<()>> {
14538        let buffer = self.buffer.clone();
14539        let buffers = buffer.read(cx).all_buffers();
14540        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14541        let apply_action = project.update(cx, |project, cx| {
14542            project.apply_code_action_kind(buffers, kind, true, cx)
14543        });
14544        cx.spawn_in(window, async move |_, cx| {
14545            let transaction = futures::select_biased! {
14546                () = timeout => {
14547                    log::warn!("timed out waiting for executing code action");
14548                    None
14549                }
14550                transaction = apply_action.log_err().fuse() => transaction,
14551            };
14552            buffer
14553                .update(cx, |buffer, cx| {
14554                    // check if we need this
14555                    if let Some(transaction) = transaction {
14556                        if !buffer.is_singleton() {
14557                            buffer.push_transaction(&transaction.0, cx);
14558                        }
14559                    }
14560                    cx.notify();
14561                })
14562                .ok();
14563            Ok(())
14564        })
14565    }
14566
14567    fn restart_language_server(
14568        &mut self,
14569        _: &RestartLanguageServer,
14570        _: &mut Window,
14571        cx: &mut Context<Self>,
14572    ) {
14573        if let Some(project) = self.project.clone() {
14574            self.buffer.update(cx, |multi_buffer, cx| {
14575                project.update(cx, |project, cx| {
14576                    project.restart_language_servers_for_buffers(
14577                        multi_buffer.all_buffers().into_iter().collect(),
14578                        cx,
14579                    );
14580                });
14581            })
14582        }
14583    }
14584
14585    fn stop_language_server(
14586        &mut self,
14587        _: &StopLanguageServer,
14588        _: &mut Window,
14589        cx: &mut Context<Self>,
14590    ) {
14591        if let Some(project) = self.project.clone() {
14592            self.buffer.update(cx, |multi_buffer, cx| {
14593                project.update(cx, |project, cx| {
14594                    project.stop_language_servers_for_buffers(
14595                        multi_buffer.all_buffers().into_iter().collect(),
14596                        cx,
14597                    );
14598                    cx.emit(project::Event::RefreshInlayHints);
14599                });
14600            });
14601        }
14602    }
14603
14604    fn cancel_language_server_work(
14605        workspace: &mut Workspace,
14606        _: &actions::CancelLanguageServerWork,
14607        _: &mut Window,
14608        cx: &mut Context<Workspace>,
14609    ) {
14610        let project = workspace.project();
14611        let buffers = workspace
14612            .active_item(cx)
14613            .and_then(|item| item.act_as::<Editor>(cx))
14614            .map_or(HashSet::default(), |editor| {
14615                editor.read(cx).buffer.read(cx).all_buffers()
14616            });
14617        project.update(cx, |project, cx| {
14618            project.cancel_language_server_work_for_buffers(buffers, cx);
14619        });
14620    }
14621
14622    fn show_character_palette(
14623        &mut self,
14624        _: &ShowCharacterPalette,
14625        window: &mut Window,
14626        _: &mut Context<Self>,
14627    ) {
14628        window.show_character_palette();
14629    }
14630
14631    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14632        if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14633            let buffer = self.buffer.read(cx).snapshot(cx);
14634            let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14635            let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14636            let is_valid = buffer
14637                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14638                .any(|entry| {
14639                    entry.diagnostic.is_primary
14640                        && !entry.range.is_empty()
14641                        && entry.range.start == primary_range_start
14642                        && entry.diagnostic.message == active_diagnostics.active_message
14643                });
14644
14645            if !is_valid {
14646                self.dismiss_diagnostics(cx);
14647            }
14648        }
14649    }
14650
14651    pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14652        match &self.active_diagnostics {
14653            ActiveDiagnostic::Group(group) => Some(group),
14654            _ => None,
14655        }
14656    }
14657
14658    pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14659        self.dismiss_diagnostics(cx);
14660        self.active_diagnostics = ActiveDiagnostic::All;
14661    }
14662
14663    fn activate_diagnostics(
14664        &mut self,
14665        buffer_id: BufferId,
14666        diagnostic: DiagnosticEntry<usize>,
14667        window: &mut Window,
14668        cx: &mut Context<Self>,
14669    ) {
14670        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14671            return;
14672        }
14673        self.dismiss_diagnostics(cx);
14674        let snapshot = self.snapshot(window, cx);
14675        let Some(diagnostic_renderer) = cx
14676            .try_global::<GlobalDiagnosticRenderer>()
14677            .map(|g| g.0.clone())
14678        else {
14679            return;
14680        };
14681        let buffer = self.buffer.read(cx).snapshot(cx);
14682
14683        let diagnostic_group = buffer
14684            .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14685            .collect::<Vec<_>>();
14686
14687        let blocks = diagnostic_renderer.render_group(
14688            diagnostic_group,
14689            buffer_id,
14690            snapshot,
14691            cx.weak_entity(),
14692            cx,
14693        );
14694
14695        let blocks = self.display_map.update(cx, |display_map, cx| {
14696            display_map.insert_blocks(blocks, cx).into_iter().collect()
14697        });
14698        self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14699            active_range: buffer.anchor_before(diagnostic.range.start)
14700                ..buffer.anchor_after(diagnostic.range.end),
14701            active_message: diagnostic.diagnostic.message.clone(),
14702            group_id: diagnostic.diagnostic.group_id,
14703            blocks,
14704        });
14705        cx.notify();
14706    }
14707
14708    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14709        if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14710            return;
14711        };
14712
14713        let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14714        if let ActiveDiagnostic::Group(group) = prev {
14715            self.display_map.update(cx, |display_map, cx| {
14716                display_map.remove_blocks(group.blocks, cx);
14717            });
14718            cx.notify();
14719        }
14720    }
14721
14722    /// Disable inline diagnostics rendering for this editor.
14723    pub fn disable_inline_diagnostics(&mut self) {
14724        self.inline_diagnostics_enabled = false;
14725        self.inline_diagnostics_update = Task::ready(());
14726        self.inline_diagnostics.clear();
14727    }
14728
14729    pub fn inline_diagnostics_enabled(&self) -> bool {
14730        self.inline_diagnostics_enabled
14731    }
14732
14733    pub fn show_inline_diagnostics(&self) -> bool {
14734        self.show_inline_diagnostics
14735    }
14736
14737    pub fn toggle_inline_diagnostics(
14738        &mut self,
14739        _: &ToggleInlineDiagnostics,
14740        window: &mut Window,
14741        cx: &mut Context<Editor>,
14742    ) {
14743        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14744        self.refresh_inline_diagnostics(false, window, cx);
14745    }
14746
14747    fn refresh_inline_diagnostics(
14748        &mut self,
14749        debounce: bool,
14750        window: &mut Window,
14751        cx: &mut Context<Self>,
14752    ) {
14753        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14754            self.inline_diagnostics_update = Task::ready(());
14755            self.inline_diagnostics.clear();
14756            return;
14757        }
14758
14759        let debounce_ms = ProjectSettings::get_global(cx)
14760            .diagnostics
14761            .inline
14762            .update_debounce_ms;
14763        let debounce = if debounce && debounce_ms > 0 {
14764            Some(Duration::from_millis(debounce_ms))
14765        } else {
14766            None
14767        };
14768        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14769            let editor = editor.upgrade().unwrap();
14770
14771            if let Some(debounce) = debounce {
14772                cx.background_executor().timer(debounce).await;
14773            }
14774            let Some(snapshot) = editor
14775                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14776                .ok()
14777            else {
14778                return;
14779            };
14780
14781            let new_inline_diagnostics = cx
14782                .background_spawn(async move {
14783                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14784                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14785                        let message = diagnostic_entry
14786                            .diagnostic
14787                            .message
14788                            .split_once('\n')
14789                            .map(|(line, _)| line)
14790                            .map(SharedString::new)
14791                            .unwrap_or_else(|| {
14792                                SharedString::from(diagnostic_entry.diagnostic.message)
14793                            });
14794                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14795                        let (Ok(i) | Err(i)) = inline_diagnostics
14796                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14797                        inline_diagnostics.insert(
14798                            i,
14799                            (
14800                                start_anchor,
14801                                InlineDiagnostic {
14802                                    message,
14803                                    group_id: diagnostic_entry.diagnostic.group_id,
14804                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14805                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14806                                    severity: diagnostic_entry.diagnostic.severity,
14807                                },
14808                            ),
14809                        );
14810                    }
14811                    inline_diagnostics
14812                })
14813                .await;
14814
14815            editor
14816                .update(cx, |editor, cx| {
14817                    editor.inline_diagnostics = new_inline_diagnostics;
14818                    cx.notify();
14819                })
14820                .ok();
14821        });
14822    }
14823
14824    pub fn set_selections_from_remote(
14825        &mut self,
14826        selections: Vec<Selection<Anchor>>,
14827        pending_selection: Option<Selection<Anchor>>,
14828        window: &mut Window,
14829        cx: &mut Context<Self>,
14830    ) {
14831        let old_cursor_position = self.selections.newest_anchor().head();
14832        self.selections.change_with(cx, |s| {
14833            s.select_anchors(selections);
14834            if let Some(pending_selection) = pending_selection {
14835                s.set_pending(pending_selection, SelectMode::Character);
14836            } else {
14837                s.clear_pending();
14838            }
14839        });
14840        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14841    }
14842
14843    fn push_to_selection_history(&mut self) {
14844        self.selection_history.push(SelectionHistoryEntry {
14845            selections: self.selections.disjoint_anchors(),
14846            select_next_state: self.select_next_state.clone(),
14847            select_prev_state: self.select_prev_state.clone(),
14848            add_selections_state: self.add_selections_state.clone(),
14849        });
14850    }
14851
14852    pub fn transact(
14853        &mut self,
14854        window: &mut Window,
14855        cx: &mut Context<Self>,
14856        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14857    ) -> Option<TransactionId> {
14858        self.start_transaction_at(Instant::now(), window, cx);
14859        update(self, window, cx);
14860        self.end_transaction_at(Instant::now(), cx)
14861    }
14862
14863    pub fn start_transaction_at(
14864        &mut self,
14865        now: Instant,
14866        window: &mut Window,
14867        cx: &mut Context<Self>,
14868    ) {
14869        self.end_selection(window, cx);
14870        if let Some(tx_id) = self
14871            .buffer
14872            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14873        {
14874            self.selection_history
14875                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14876            cx.emit(EditorEvent::TransactionBegun {
14877                transaction_id: tx_id,
14878            })
14879        }
14880    }
14881
14882    pub fn end_transaction_at(
14883        &mut self,
14884        now: Instant,
14885        cx: &mut Context<Self>,
14886    ) -> Option<TransactionId> {
14887        if let Some(transaction_id) = self
14888            .buffer
14889            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14890        {
14891            if let Some((_, end_selections)) =
14892                self.selection_history.transaction_mut(transaction_id)
14893            {
14894                *end_selections = Some(self.selections.disjoint_anchors());
14895            } else {
14896                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14897            }
14898
14899            cx.emit(EditorEvent::Edited { transaction_id });
14900            Some(transaction_id)
14901        } else {
14902            None
14903        }
14904    }
14905
14906    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14907        if self.selection_mark_mode {
14908            self.change_selections(None, window, cx, |s| {
14909                s.move_with(|_, sel| {
14910                    sel.collapse_to(sel.head(), SelectionGoal::None);
14911                });
14912            })
14913        }
14914        self.selection_mark_mode = true;
14915        cx.notify();
14916    }
14917
14918    pub fn swap_selection_ends(
14919        &mut self,
14920        _: &actions::SwapSelectionEnds,
14921        window: &mut Window,
14922        cx: &mut Context<Self>,
14923    ) {
14924        self.change_selections(None, window, cx, |s| {
14925            s.move_with(|_, sel| {
14926                if sel.start != sel.end {
14927                    sel.reversed = !sel.reversed
14928                }
14929            });
14930        });
14931        self.request_autoscroll(Autoscroll::newest(), cx);
14932        cx.notify();
14933    }
14934
14935    pub fn toggle_fold(
14936        &mut self,
14937        _: &actions::ToggleFold,
14938        window: &mut Window,
14939        cx: &mut Context<Self>,
14940    ) {
14941        if self.is_singleton(cx) {
14942            let selection = self.selections.newest::<Point>(cx);
14943
14944            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14945            let range = if selection.is_empty() {
14946                let point = selection.head().to_display_point(&display_map);
14947                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14948                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14949                    .to_point(&display_map);
14950                start..end
14951            } else {
14952                selection.range()
14953            };
14954            if display_map.folds_in_range(range).next().is_some() {
14955                self.unfold_lines(&Default::default(), window, cx)
14956            } else {
14957                self.fold(&Default::default(), window, cx)
14958            }
14959        } else {
14960            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14961            let buffer_ids: HashSet<_> = self
14962                .selections
14963                .disjoint_anchor_ranges()
14964                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14965                .collect();
14966
14967            let should_unfold = buffer_ids
14968                .iter()
14969                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14970
14971            for buffer_id in buffer_ids {
14972                if should_unfold {
14973                    self.unfold_buffer(buffer_id, cx);
14974                } else {
14975                    self.fold_buffer(buffer_id, cx);
14976                }
14977            }
14978        }
14979    }
14980
14981    pub fn toggle_fold_recursive(
14982        &mut self,
14983        _: &actions::ToggleFoldRecursive,
14984        window: &mut Window,
14985        cx: &mut Context<Self>,
14986    ) {
14987        let selection = self.selections.newest::<Point>(cx);
14988
14989        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14990        let range = if selection.is_empty() {
14991            let point = selection.head().to_display_point(&display_map);
14992            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14993            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14994                .to_point(&display_map);
14995            start..end
14996        } else {
14997            selection.range()
14998        };
14999        if display_map.folds_in_range(range).next().is_some() {
15000            self.unfold_recursive(&Default::default(), window, cx)
15001        } else {
15002            self.fold_recursive(&Default::default(), window, cx)
15003        }
15004    }
15005
15006    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15007        if self.is_singleton(cx) {
15008            let mut to_fold = Vec::new();
15009            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15010            let selections = self.selections.all_adjusted(cx);
15011
15012            for selection in selections {
15013                let range = selection.range().sorted();
15014                let buffer_start_row = range.start.row;
15015
15016                if range.start.row != range.end.row {
15017                    let mut found = false;
15018                    let mut row = range.start.row;
15019                    while row <= range.end.row {
15020                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15021                        {
15022                            found = true;
15023                            row = crease.range().end.row + 1;
15024                            to_fold.push(crease);
15025                        } else {
15026                            row += 1
15027                        }
15028                    }
15029                    if found {
15030                        continue;
15031                    }
15032                }
15033
15034                for row in (0..=range.start.row).rev() {
15035                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15036                        if crease.range().end.row >= buffer_start_row {
15037                            to_fold.push(crease);
15038                            if row <= range.start.row {
15039                                break;
15040                            }
15041                        }
15042                    }
15043                }
15044            }
15045
15046            self.fold_creases(to_fold, true, window, cx);
15047        } else {
15048            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15049            let buffer_ids = self
15050                .selections
15051                .disjoint_anchor_ranges()
15052                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15053                .collect::<HashSet<_>>();
15054            for buffer_id in buffer_ids {
15055                self.fold_buffer(buffer_id, cx);
15056            }
15057        }
15058    }
15059
15060    fn fold_at_level(
15061        &mut self,
15062        fold_at: &FoldAtLevel,
15063        window: &mut Window,
15064        cx: &mut Context<Self>,
15065    ) {
15066        if !self.buffer.read(cx).is_singleton() {
15067            return;
15068        }
15069
15070        let fold_at_level = fold_at.0;
15071        let snapshot = self.buffer.read(cx).snapshot(cx);
15072        let mut to_fold = Vec::new();
15073        let mut stack = vec![(0, snapshot.max_row().0, 1)];
15074
15075        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15076            while start_row < end_row {
15077                match self
15078                    .snapshot(window, cx)
15079                    .crease_for_buffer_row(MultiBufferRow(start_row))
15080                {
15081                    Some(crease) => {
15082                        let nested_start_row = crease.range().start.row + 1;
15083                        let nested_end_row = crease.range().end.row;
15084
15085                        if current_level < fold_at_level {
15086                            stack.push((nested_start_row, nested_end_row, current_level + 1));
15087                        } else if current_level == fold_at_level {
15088                            to_fold.push(crease);
15089                        }
15090
15091                        start_row = nested_end_row + 1;
15092                    }
15093                    None => start_row += 1,
15094                }
15095            }
15096        }
15097
15098        self.fold_creases(to_fold, true, window, cx);
15099    }
15100
15101    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15102        if self.buffer.read(cx).is_singleton() {
15103            let mut fold_ranges = Vec::new();
15104            let snapshot = self.buffer.read(cx).snapshot(cx);
15105
15106            for row in 0..snapshot.max_row().0 {
15107                if let Some(foldable_range) = self
15108                    .snapshot(window, cx)
15109                    .crease_for_buffer_row(MultiBufferRow(row))
15110                {
15111                    fold_ranges.push(foldable_range);
15112                }
15113            }
15114
15115            self.fold_creases(fold_ranges, true, window, cx);
15116        } else {
15117            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15118                editor
15119                    .update_in(cx, |editor, _, cx| {
15120                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15121                            editor.fold_buffer(buffer_id, cx);
15122                        }
15123                    })
15124                    .ok();
15125            });
15126        }
15127    }
15128
15129    pub fn fold_function_bodies(
15130        &mut self,
15131        _: &actions::FoldFunctionBodies,
15132        window: &mut Window,
15133        cx: &mut Context<Self>,
15134    ) {
15135        let snapshot = self.buffer.read(cx).snapshot(cx);
15136
15137        let ranges = snapshot
15138            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15139            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15140            .collect::<Vec<_>>();
15141
15142        let creases = ranges
15143            .into_iter()
15144            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15145            .collect();
15146
15147        self.fold_creases(creases, true, window, cx);
15148    }
15149
15150    pub fn fold_recursive(
15151        &mut self,
15152        _: &actions::FoldRecursive,
15153        window: &mut Window,
15154        cx: &mut Context<Self>,
15155    ) {
15156        let mut to_fold = Vec::new();
15157        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15158        let selections = self.selections.all_adjusted(cx);
15159
15160        for selection in selections {
15161            let range = selection.range().sorted();
15162            let buffer_start_row = range.start.row;
15163
15164            if range.start.row != range.end.row {
15165                let mut found = false;
15166                for row in range.start.row..=range.end.row {
15167                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15168                        found = true;
15169                        to_fold.push(crease);
15170                    }
15171                }
15172                if found {
15173                    continue;
15174                }
15175            }
15176
15177            for row in (0..=range.start.row).rev() {
15178                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15179                    if crease.range().end.row >= buffer_start_row {
15180                        to_fold.push(crease);
15181                    } else {
15182                        break;
15183                    }
15184                }
15185            }
15186        }
15187
15188        self.fold_creases(to_fold, true, window, cx);
15189    }
15190
15191    pub fn fold_at(
15192        &mut self,
15193        buffer_row: MultiBufferRow,
15194        window: &mut Window,
15195        cx: &mut Context<Self>,
15196    ) {
15197        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15198
15199        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15200            let autoscroll = self
15201                .selections
15202                .all::<Point>(cx)
15203                .iter()
15204                .any(|selection| crease.range().overlaps(&selection.range()));
15205
15206            self.fold_creases(vec![crease], autoscroll, window, cx);
15207        }
15208    }
15209
15210    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15211        if self.is_singleton(cx) {
15212            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15213            let buffer = &display_map.buffer_snapshot;
15214            let selections = self.selections.all::<Point>(cx);
15215            let ranges = selections
15216                .iter()
15217                .map(|s| {
15218                    let range = s.display_range(&display_map).sorted();
15219                    let mut start = range.start.to_point(&display_map);
15220                    let mut end = range.end.to_point(&display_map);
15221                    start.column = 0;
15222                    end.column = buffer.line_len(MultiBufferRow(end.row));
15223                    start..end
15224                })
15225                .collect::<Vec<_>>();
15226
15227            self.unfold_ranges(&ranges, true, true, cx);
15228        } else {
15229            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15230            let buffer_ids = self
15231                .selections
15232                .disjoint_anchor_ranges()
15233                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15234                .collect::<HashSet<_>>();
15235            for buffer_id in buffer_ids {
15236                self.unfold_buffer(buffer_id, cx);
15237            }
15238        }
15239    }
15240
15241    pub fn unfold_recursive(
15242        &mut self,
15243        _: &UnfoldRecursive,
15244        _window: &mut Window,
15245        cx: &mut Context<Self>,
15246    ) {
15247        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15248        let selections = self.selections.all::<Point>(cx);
15249        let ranges = selections
15250            .iter()
15251            .map(|s| {
15252                let mut range = s.display_range(&display_map).sorted();
15253                *range.start.column_mut() = 0;
15254                *range.end.column_mut() = display_map.line_len(range.end.row());
15255                let start = range.start.to_point(&display_map);
15256                let end = range.end.to_point(&display_map);
15257                start..end
15258            })
15259            .collect::<Vec<_>>();
15260
15261        self.unfold_ranges(&ranges, true, true, cx);
15262    }
15263
15264    pub fn unfold_at(
15265        &mut self,
15266        buffer_row: MultiBufferRow,
15267        _window: &mut Window,
15268        cx: &mut Context<Self>,
15269    ) {
15270        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15271
15272        let intersection_range = Point::new(buffer_row.0, 0)
15273            ..Point::new(
15274                buffer_row.0,
15275                display_map.buffer_snapshot.line_len(buffer_row),
15276            );
15277
15278        let autoscroll = self
15279            .selections
15280            .all::<Point>(cx)
15281            .iter()
15282            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15283
15284        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15285    }
15286
15287    pub fn unfold_all(
15288        &mut self,
15289        _: &actions::UnfoldAll,
15290        _window: &mut Window,
15291        cx: &mut Context<Self>,
15292    ) {
15293        if self.buffer.read(cx).is_singleton() {
15294            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15295            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15296        } else {
15297            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15298                editor
15299                    .update(cx, |editor, cx| {
15300                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15301                            editor.unfold_buffer(buffer_id, cx);
15302                        }
15303                    })
15304                    .ok();
15305            });
15306        }
15307    }
15308
15309    pub fn fold_selected_ranges(
15310        &mut self,
15311        _: &FoldSelectedRanges,
15312        window: &mut Window,
15313        cx: &mut Context<Self>,
15314    ) {
15315        let selections = self.selections.all_adjusted(cx);
15316        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15317        let ranges = selections
15318            .into_iter()
15319            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15320            .collect::<Vec<_>>();
15321        self.fold_creases(ranges, true, window, cx);
15322    }
15323
15324    pub fn fold_ranges<T: ToOffset + Clone>(
15325        &mut self,
15326        ranges: Vec<Range<T>>,
15327        auto_scroll: bool,
15328        window: &mut Window,
15329        cx: &mut Context<Self>,
15330    ) {
15331        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15332        let ranges = ranges
15333            .into_iter()
15334            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15335            .collect::<Vec<_>>();
15336        self.fold_creases(ranges, auto_scroll, window, cx);
15337    }
15338
15339    pub fn fold_creases<T: ToOffset + Clone>(
15340        &mut self,
15341        creases: Vec<Crease<T>>,
15342        auto_scroll: bool,
15343        _window: &mut Window,
15344        cx: &mut Context<Self>,
15345    ) {
15346        if creases.is_empty() {
15347            return;
15348        }
15349
15350        let mut buffers_affected = HashSet::default();
15351        let multi_buffer = self.buffer().read(cx);
15352        for crease in &creases {
15353            if let Some((_, buffer, _)) =
15354                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15355            {
15356                buffers_affected.insert(buffer.read(cx).remote_id());
15357            };
15358        }
15359
15360        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15361
15362        if auto_scroll {
15363            self.request_autoscroll(Autoscroll::fit(), cx);
15364        }
15365
15366        cx.notify();
15367
15368        self.scrollbar_marker_state.dirty = true;
15369        self.folds_did_change(cx);
15370    }
15371
15372    /// Removes any folds whose ranges intersect any of the given ranges.
15373    pub fn unfold_ranges<T: ToOffset + Clone>(
15374        &mut self,
15375        ranges: &[Range<T>],
15376        inclusive: bool,
15377        auto_scroll: bool,
15378        cx: &mut Context<Self>,
15379    ) {
15380        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15381            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15382        });
15383        self.folds_did_change(cx);
15384    }
15385
15386    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15387        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15388            return;
15389        }
15390        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15391        self.display_map.update(cx, |display_map, cx| {
15392            display_map.fold_buffers([buffer_id], cx)
15393        });
15394        cx.emit(EditorEvent::BufferFoldToggled {
15395            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15396            folded: true,
15397        });
15398        cx.notify();
15399    }
15400
15401    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15402        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15403            return;
15404        }
15405        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15406        self.display_map.update(cx, |display_map, cx| {
15407            display_map.unfold_buffers([buffer_id], cx);
15408        });
15409        cx.emit(EditorEvent::BufferFoldToggled {
15410            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15411            folded: false,
15412        });
15413        cx.notify();
15414    }
15415
15416    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15417        self.display_map.read(cx).is_buffer_folded(buffer)
15418    }
15419
15420    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15421        self.display_map.read(cx).folded_buffers()
15422    }
15423
15424    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15425        self.display_map.update(cx, |display_map, cx| {
15426            display_map.disable_header_for_buffer(buffer_id, cx);
15427        });
15428        cx.notify();
15429    }
15430
15431    /// Removes any folds with the given ranges.
15432    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15433        &mut self,
15434        ranges: &[Range<T>],
15435        type_id: TypeId,
15436        auto_scroll: bool,
15437        cx: &mut Context<Self>,
15438    ) {
15439        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15440            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15441        });
15442        self.folds_did_change(cx);
15443    }
15444
15445    fn remove_folds_with<T: ToOffset + Clone>(
15446        &mut self,
15447        ranges: &[Range<T>],
15448        auto_scroll: bool,
15449        cx: &mut Context<Self>,
15450        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15451    ) {
15452        if ranges.is_empty() {
15453            return;
15454        }
15455
15456        let mut buffers_affected = HashSet::default();
15457        let multi_buffer = self.buffer().read(cx);
15458        for range in ranges {
15459            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15460                buffers_affected.insert(buffer.read(cx).remote_id());
15461            };
15462        }
15463
15464        self.display_map.update(cx, update);
15465
15466        if auto_scroll {
15467            self.request_autoscroll(Autoscroll::fit(), cx);
15468        }
15469
15470        cx.notify();
15471        self.scrollbar_marker_state.dirty = true;
15472        self.active_indent_guides_state.dirty = true;
15473    }
15474
15475    pub fn update_fold_widths(
15476        &mut self,
15477        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15478        cx: &mut Context<Self>,
15479    ) -> bool {
15480        self.display_map
15481            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15482    }
15483
15484    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15485        self.display_map.read(cx).fold_placeholder.clone()
15486    }
15487
15488    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15489        self.buffer.update(cx, |buffer, cx| {
15490            buffer.set_all_diff_hunks_expanded(cx);
15491        });
15492    }
15493
15494    pub fn expand_all_diff_hunks(
15495        &mut self,
15496        _: &ExpandAllDiffHunks,
15497        _window: &mut Window,
15498        cx: &mut Context<Self>,
15499    ) {
15500        self.buffer.update(cx, |buffer, cx| {
15501            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15502        });
15503    }
15504
15505    pub fn toggle_selected_diff_hunks(
15506        &mut self,
15507        _: &ToggleSelectedDiffHunks,
15508        _window: &mut Window,
15509        cx: &mut Context<Self>,
15510    ) {
15511        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15512        self.toggle_diff_hunks_in_ranges(ranges, cx);
15513    }
15514
15515    pub fn diff_hunks_in_ranges<'a>(
15516        &'a self,
15517        ranges: &'a [Range<Anchor>],
15518        buffer: &'a MultiBufferSnapshot,
15519    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15520        ranges.iter().flat_map(move |range| {
15521            let end_excerpt_id = range.end.excerpt_id;
15522            let range = range.to_point(buffer);
15523            let mut peek_end = range.end;
15524            if range.end.row < buffer.max_row().0 {
15525                peek_end = Point::new(range.end.row + 1, 0);
15526            }
15527            buffer
15528                .diff_hunks_in_range(range.start..peek_end)
15529                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15530        })
15531    }
15532
15533    pub fn has_stageable_diff_hunks_in_ranges(
15534        &self,
15535        ranges: &[Range<Anchor>],
15536        snapshot: &MultiBufferSnapshot,
15537    ) -> bool {
15538        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15539        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15540    }
15541
15542    pub fn toggle_staged_selected_diff_hunks(
15543        &mut self,
15544        _: &::git::ToggleStaged,
15545        _: &mut Window,
15546        cx: &mut Context<Self>,
15547    ) {
15548        let snapshot = self.buffer.read(cx).snapshot(cx);
15549        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15550        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15551        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15552    }
15553
15554    pub fn set_render_diff_hunk_controls(
15555        &mut self,
15556        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15557        cx: &mut Context<Self>,
15558    ) {
15559        self.render_diff_hunk_controls = render_diff_hunk_controls;
15560        cx.notify();
15561    }
15562
15563    pub fn stage_and_next(
15564        &mut self,
15565        _: &::git::StageAndNext,
15566        window: &mut Window,
15567        cx: &mut Context<Self>,
15568    ) {
15569        self.do_stage_or_unstage_and_next(true, window, cx);
15570    }
15571
15572    pub fn unstage_and_next(
15573        &mut self,
15574        _: &::git::UnstageAndNext,
15575        window: &mut Window,
15576        cx: &mut Context<Self>,
15577    ) {
15578        self.do_stage_or_unstage_and_next(false, window, cx);
15579    }
15580
15581    pub fn stage_or_unstage_diff_hunks(
15582        &mut self,
15583        stage: bool,
15584        ranges: Vec<Range<Anchor>>,
15585        cx: &mut Context<Self>,
15586    ) {
15587        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15588        cx.spawn(async move |this, cx| {
15589            task.await?;
15590            this.update(cx, |this, cx| {
15591                let snapshot = this.buffer.read(cx).snapshot(cx);
15592                let chunk_by = this
15593                    .diff_hunks_in_ranges(&ranges, &snapshot)
15594                    .chunk_by(|hunk| hunk.buffer_id);
15595                for (buffer_id, hunks) in &chunk_by {
15596                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15597                }
15598            })
15599        })
15600        .detach_and_log_err(cx);
15601    }
15602
15603    fn save_buffers_for_ranges_if_needed(
15604        &mut self,
15605        ranges: &[Range<Anchor>],
15606        cx: &mut Context<Editor>,
15607    ) -> Task<Result<()>> {
15608        let multibuffer = self.buffer.read(cx);
15609        let snapshot = multibuffer.read(cx);
15610        let buffer_ids: HashSet<_> = ranges
15611            .iter()
15612            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15613            .collect();
15614        drop(snapshot);
15615
15616        let mut buffers = HashSet::default();
15617        for buffer_id in buffer_ids {
15618            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15619                let buffer = buffer_entity.read(cx);
15620                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15621                {
15622                    buffers.insert(buffer_entity);
15623                }
15624            }
15625        }
15626
15627        if let Some(project) = &self.project {
15628            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15629        } else {
15630            Task::ready(Ok(()))
15631        }
15632    }
15633
15634    fn do_stage_or_unstage_and_next(
15635        &mut self,
15636        stage: bool,
15637        window: &mut Window,
15638        cx: &mut Context<Self>,
15639    ) {
15640        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15641
15642        if ranges.iter().any(|range| range.start != range.end) {
15643            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15644            return;
15645        }
15646
15647        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15648        let snapshot = self.snapshot(window, cx);
15649        let position = self.selections.newest::<Point>(cx).head();
15650        let mut row = snapshot
15651            .buffer_snapshot
15652            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15653            .find(|hunk| hunk.row_range.start.0 > position.row)
15654            .map(|hunk| hunk.row_range.start);
15655
15656        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15657        // Outside of the project diff editor, wrap around to the beginning.
15658        if !all_diff_hunks_expanded {
15659            row = row.or_else(|| {
15660                snapshot
15661                    .buffer_snapshot
15662                    .diff_hunks_in_range(Point::zero()..position)
15663                    .find(|hunk| hunk.row_range.end.0 < position.row)
15664                    .map(|hunk| hunk.row_range.start)
15665            });
15666        }
15667
15668        if let Some(row) = row {
15669            let destination = Point::new(row.0, 0);
15670            let autoscroll = Autoscroll::center();
15671
15672            self.unfold_ranges(&[destination..destination], false, false, cx);
15673            self.change_selections(Some(autoscroll), window, cx, |s| {
15674                s.select_ranges([destination..destination]);
15675            });
15676        }
15677    }
15678
15679    fn do_stage_or_unstage(
15680        &self,
15681        stage: bool,
15682        buffer_id: BufferId,
15683        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15684        cx: &mut App,
15685    ) -> Option<()> {
15686        let project = self.project.as_ref()?;
15687        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15688        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15689        let buffer_snapshot = buffer.read(cx).snapshot();
15690        let file_exists = buffer_snapshot
15691            .file()
15692            .is_some_and(|file| file.disk_state().exists());
15693        diff.update(cx, |diff, cx| {
15694            diff.stage_or_unstage_hunks(
15695                stage,
15696                &hunks
15697                    .map(|hunk| buffer_diff::DiffHunk {
15698                        buffer_range: hunk.buffer_range,
15699                        diff_base_byte_range: hunk.diff_base_byte_range,
15700                        secondary_status: hunk.secondary_status,
15701                        range: Point::zero()..Point::zero(), // unused
15702                    })
15703                    .collect::<Vec<_>>(),
15704                &buffer_snapshot,
15705                file_exists,
15706                cx,
15707            )
15708        });
15709        None
15710    }
15711
15712    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15713        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15714        self.buffer
15715            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15716    }
15717
15718    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15719        self.buffer.update(cx, |buffer, cx| {
15720            let ranges = vec![Anchor::min()..Anchor::max()];
15721            if !buffer.all_diff_hunks_expanded()
15722                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15723            {
15724                buffer.collapse_diff_hunks(ranges, cx);
15725                true
15726            } else {
15727                false
15728            }
15729        })
15730    }
15731
15732    fn toggle_diff_hunks_in_ranges(
15733        &mut self,
15734        ranges: Vec<Range<Anchor>>,
15735        cx: &mut Context<Editor>,
15736    ) {
15737        self.buffer.update(cx, |buffer, cx| {
15738            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15739            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15740        })
15741    }
15742
15743    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15744        self.buffer.update(cx, |buffer, cx| {
15745            let snapshot = buffer.snapshot(cx);
15746            let excerpt_id = range.end.excerpt_id;
15747            let point_range = range.to_point(&snapshot);
15748            let expand = !buffer.single_hunk_is_expanded(range, cx);
15749            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15750        })
15751    }
15752
15753    pub(crate) fn apply_all_diff_hunks(
15754        &mut self,
15755        _: &ApplyAllDiffHunks,
15756        window: &mut Window,
15757        cx: &mut Context<Self>,
15758    ) {
15759        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15760
15761        let buffers = self.buffer.read(cx).all_buffers();
15762        for branch_buffer in buffers {
15763            branch_buffer.update(cx, |branch_buffer, cx| {
15764                branch_buffer.merge_into_base(Vec::new(), cx);
15765            });
15766        }
15767
15768        if let Some(project) = self.project.clone() {
15769            self.save(true, project, window, cx).detach_and_log_err(cx);
15770        }
15771    }
15772
15773    pub(crate) fn apply_selected_diff_hunks(
15774        &mut self,
15775        _: &ApplyDiffHunk,
15776        window: &mut Window,
15777        cx: &mut Context<Self>,
15778    ) {
15779        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15780        let snapshot = self.snapshot(window, cx);
15781        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15782        let mut ranges_by_buffer = HashMap::default();
15783        self.transact(window, cx, |editor, _window, cx| {
15784            for hunk in hunks {
15785                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15786                    ranges_by_buffer
15787                        .entry(buffer.clone())
15788                        .or_insert_with(Vec::new)
15789                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15790                }
15791            }
15792
15793            for (buffer, ranges) in ranges_by_buffer {
15794                buffer.update(cx, |buffer, cx| {
15795                    buffer.merge_into_base(ranges, cx);
15796                });
15797            }
15798        });
15799
15800        if let Some(project) = self.project.clone() {
15801            self.save(true, project, window, cx).detach_and_log_err(cx);
15802        }
15803    }
15804
15805    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15806        if hovered != self.gutter_hovered {
15807            self.gutter_hovered = hovered;
15808            cx.notify();
15809        }
15810    }
15811
15812    pub fn insert_blocks(
15813        &mut self,
15814        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15815        autoscroll: Option<Autoscroll>,
15816        cx: &mut Context<Self>,
15817    ) -> Vec<CustomBlockId> {
15818        let blocks = self
15819            .display_map
15820            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15821        if let Some(autoscroll) = autoscroll {
15822            self.request_autoscroll(autoscroll, cx);
15823        }
15824        cx.notify();
15825        blocks
15826    }
15827
15828    pub fn resize_blocks(
15829        &mut self,
15830        heights: HashMap<CustomBlockId, u32>,
15831        autoscroll: Option<Autoscroll>,
15832        cx: &mut Context<Self>,
15833    ) {
15834        self.display_map
15835            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15836        if let Some(autoscroll) = autoscroll {
15837            self.request_autoscroll(autoscroll, cx);
15838        }
15839        cx.notify();
15840    }
15841
15842    pub fn replace_blocks(
15843        &mut self,
15844        renderers: HashMap<CustomBlockId, RenderBlock>,
15845        autoscroll: Option<Autoscroll>,
15846        cx: &mut Context<Self>,
15847    ) {
15848        self.display_map
15849            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15850        if let Some(autoscroll) = autoscroll {
15851            self.request_autoscroll(autoscroll, cx);
15852        }
15853        cx.notify();
15854    }
15855
15856    pub fn remove_blocks(
15857        &mut self,
15858        block_ids: HashSet<CustomBlockId>,
15859        autoscroll: Option<Autoscroll>,
15860        cx: &mut Context<Self>,
15861    ) {
15862        self.display_map.update(cx, |display_map, cx| {
15863            display_map.remove_blocks(block_ids, cx)
15864        });
15865        if let Some(autoscroll) = autoscroll {
15866            self.request_autoscroll(autoscroll, cx);
15867        }
15868        cx.notify();
15869    }
15870
15871    pub fn row_for_block(
15872        &self,
15873        block_id: CustomBlockId,
15874        cx: &mut Context<Self>,
15875    ) -> Option<DisplayRow> {
15876        self.display_map
15877            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15878    }
15879
15880    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15881        self.focused_block = Some(focused_block);
15882    }
15883
15884    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15885        self.focused_block.take()
15886    }
15887
15888    pub fn insert_creases(
15889        &mut self,
15890        creases: impl IntoIterator<Item = Crease<Anchor>>,
15891        cx: &mut Context<Self>,
15892    ) -> Vec<CreaseId> {
15893        self.display_map
15894            .update(cx, |map, cx| map.insert_creases(creases, cx))
15895    }
15896
15897    pub fn remove_creases(
15898        &mut self,
15899        ids: impl IntoIterator<Item = CreaseId>,
15900        cx: &mut Context<Self>,
15901    ) {
15902        self.display_map
15903            .update(cx, |map, cx| map.remove_creases(ids, cx));
15904    }
15905
15906    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15907        self.display_map
15908            .update(cx, |map, cx| map.snapshot(cx))
15909            .longest_row()
15910    }
15911
15912    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15913        self.display_map
15914            .update(cx, |map, cx| map.snapshot(cx))
15915            .max_point()
15916    }
15917
15918    pub fn text(&self, cx: &App) -> String {
15919        self.buffer.read(cx).read(cx).text()
15920    }
15921
15922    pub fn is_empty(&self, cx: &App) -> bool {
15923        self.buffer.read(cx).read(cx).is_empty()
15924    }
15925
15926    pub fn text_option(&self, cx: &App) -> Option<String> {
15927        let text = self.text(cx);
15928        let text = text.trim();
15929
15930        if text.is_empty() {
15931            return None;
15932        }
15933
15934        Some(text.to_string())
15935    }
15936
15937    pub fn set_text(
15938        &mut self,
15939        text: impl Into<Arc<str>>,
15940        window: &mut Window,
15941        cx: &mut Context<Self>,
15942    ) {
15943        self.transact(window, cx, |this, _, cx| {
15944            this.buffer
15945                .read(cx)
15946                .as_singleton()
15947                .expect("you can only call set_text on editors for singleton buffers")
15948                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15949        });
15950    }
15951
15952    pub fn display_text(&self, cx: &mut App) -> String {
15953        self.display_map
15954            .update(cx, |map, cx| map.snapshot(cx))
15955            .text()
15956    }
15957
15958    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15959        let mut wrap_guides = smallvec::smallvec![];
15960
15961        if self.show_wrap_guides == Some(false) {
15962            return wrap_guides;
15963        }
15964
15965        let settings = self.buffer.read(cx).language_settings(cx);
15966        if settings.show_wrap_guides {
15967            match self.soft_wrap_mode(cx) {
15968                SoftWrap::Column(soft_wrap) => {
15969                    wrap_guides.push((soft_wrap as usize, true));
15970                }
15971                SoftWrap::Bounded(soft_wrap) => {
15972                    wrap_guides.push((soft_wrap as usize, true));
15973                }
15974                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15975            }
15976            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15977        }
15978
15979        wrap_guides
15980    }
15981
15982    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15983        let settings = self.buffer.read(cx).language_settings(cx);
15984        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15985        match mode {
15986            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15987                SoftWrap::None
15988            }
15989            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15990            language_settings::SoftWrap::PreferredLineLength => {
15991                SoftWrap::Column(settings.preferred_line_length)
15992            }
15993            language_settings::SoftWrap::Bounded => {
15994                SoftWrap::Bounded(settings.preferred_line_length)
15995            }
15996        }
15997    }
15998
15999    pub fn set_soft_wrap_mode(
16000        &mut self,
16001        mode: language_settings::SoftWrap,
16002
16003        cx: &mut Context<Self>,
16004    ) {
16005        self.soft_wrap_mode_override = Some(mode);
16006        cx.notify();
16007    }
16008
16009    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16010        self.hard_wrap = hard_wrap;
16011        cx.notify();
16012    }
16013
16014    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16015        self.text_style_refinement = Some(style);
16016    }
16017
16018    /// called by the Element so we know what style we were most recently rendered with.
16019    pub(crate) fn set_style(
16020        &mut self,
16021        style: EditorStyle,
16022        window: &mut Window,
16023        cx: &mut Context<Self>,
16024    ) {
16025        let rem_size = window.rem_size();
16026        self.display_map.update(cx, |map, cx| {
16027            map.set_font(
16028                style.text.font(),
16029                style.text.font_size.to_pixels(rem_size),
16030                cx,
16031            )
16032        });
16033        self.style = Some(style);
16034    }
16035
16036    pub fn style(&self) -> Option<&EditorStyle> {
16037        self.style.as_ref()
16038    }
16039
16040    // Called by the element. This method is not designed to be called outside of the editor
16041    // element's layout code because it does not notify when rewrapping is computed synchronously.
16042    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16043        self.display_map
16044            .update(cx, |map, cx| map.set_wrap_width(width, cx))
16045    }
16046
16047    pub fn set_soft_wrap(&mut self) {
16048        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16049    }
16050
16051    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16052        if self.soft_wrap_mode_override.is_some() {
16053            self.soft_wrap_mode_override.take();
16054        } else {
16055            let soft_wrap = match self.soft_wrap_mode(cx) {
16056                SoftWrap::GitDiff => return,
16057                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16058                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16059                    language_settings::SoftWrap::None
16060                }
16061            };
16062            self.soft_wrap_mode_override = Some(soft_wrap);
16063        }
16064        cx.notify();
16065    }
16066
16067    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16068        let Some(workspace) = self.workspace() else {
16069            return;
16070        };
16071        let fs = workspace.read(cx).app_state().fs.clone();
16072        let current_show = TabBarSettings::get_global(cx).show;
16073        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16074            setting.show = Some(!current_show);
16075        });
16076    }
16077
16078    pub fn toggle_indent_guides(
16079        &mut self,
16080        _: &ToggleIndentGuides,
16081        _: &mut Window,
16082        cx: &mut Context<Self>,
16083    ) {
16084        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16085            self.buffer
16086                .read(cx)
16087                .language_settings(cx)
16088                .indent_guides
16089                .enabled
16090        });
16091        self.show_indent_guides = Some(!currently_enabled);
16092        cx.notify();
16093    }
16094
16095    fn should_show_indent_guides(&self) -> Option<bool> {
16096        self.show_indent_guides
16097    }
16098
16099    pub fn toggle_line_numbers(
16100        &mut self,
16101        _: &ToggleLineNumbers,
16102        _: &mut Window,
16103        cx: &mut Context<Self>,
16104    ) {
16105        let mut editor_settings = EditorSettings::get_global(cx).clone();
16106        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16107        EditorSettings::override_global(editor_settings, cx);
16108    }
16109
16110    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16111        if let Some(show_line_numbers) = self.show_line_numbers {
16112            return show_line_numbers;
16113        }
16114        EditorSettings::get_global(cx).gutter.line_numbers
16115    }
16116
16117    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16118        self.use_relative_line_numbers
16119            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16120    }
16121
16122    pub fn toggle_relative_line_numbers(
16123        &mut self,
16124        _: &ToggleRelativeLineNumbers,
16125        _: &mut Window,
16126        cx: &mut Context<Self>,
16127    ) {
16128        let is_relative = self.should_use_relative_line_numbers(cx);
16129        self.set_relative_line_number(Some(!is_relative), cx)
16130    }
16131
16132    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16133        self.use_relative_line_numbers = is_relative;
16134        cx.notify();
16135    }
16136
16137    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16138        self.show_gutter = show_gutter;
16139        cx.notify();
16140    }
16141
16142    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16143        self.show_scrollbars = show_scrollbars;
16144        cx.notify();
16145    }
16146
16147    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16148        self.show_line_numbers = Some(show_line_numbers);
16149        cx.notify();
16150    }
16151
16152    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16153        self.show_git_diff_gutter = Some(show_git_diff_gutter);
16154        cx.notify();
16155    }
16156
16157    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16158        self.show_code_actions = Some(show_code_actions);
16159        cx.notify();
16160    }
16161
16162    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16163        self.show_runnables = Some(show_runnables);
16164        cx.notify();
16165    }
16166
16167    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16168        self.show_breakpoints = Some(show_breakpoints);
16169        cx.notify();
16170    }
16171
16172    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16173        if self.display_map.read(cx).masked != masked {
16174            self.display_map.update(cx, |map, _| map.masked = masked);
16175        }
16176        cx.notify()
16177    }
16178
16179    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16180        self.show_wrap_guides = Some(show_wrap_guides);
16181        cx.notify();
16182    }
16183
16184    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16185        self.show_indent_guides = Some(show_indent_guides);
16186        cx.notify();
16187    }
16188
16189    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16190        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16191            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16192                if let Some(dir) = file.abs_path(cx).parent() {
16193                    return Some(dir.to_owned());
16194                }
16195            }
16196
16197            if let Some(project_path) = buffer.read(cx).project_path(cx) {
16198                return Some(project_path.path.to_path_buf());
16199            }
16200        }
16201
16202        None
16203    }
16204
16205    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16206        self.active_excerpt(cx)?
16207            .1
16208            .read(cx)
16209            .file()
16210            .and_then(|f| f.as_local())
16211    }
16212
16213    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16214        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16215            let buffer = buffer.read(cx);
16216            if let Some(project_path) = buffer.project_path(cx) {
16217                let project = self.project.as_ref()?.read(cx);
16218                project.absolute_path(&project_path, cx)
16219            } else {
16220                buffer
16221                    .file()
16222                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16223            }
16224        })
16225    }
16226
16227    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16228        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16229            let project_path = buffer.read(cx).project_path(cx)?;
16230            let project = self.project.as_ref()?.read(cx);
16231            let entry = project.entry_for_path(&project_path, cx)?;
16232            let path = entry.path.to_path_buf();
16233            Some(path)
16234        })
16235    }
16236
16237    pub fn reveal_in_finder(
16238        &mut self,
16239        _: &RevealInFileManager,
16240        _window: &mut Window,
16241        cx: &mut Context<Self>,
16242    ) {
16243        if let Some(target) = self.target_file(cx) {
16244            cx.reveal_path(&target.abs_path(cx));
16245        }
16246    }
16247
16248    pub fn copy_path(
16249        &mut self,
16250        _: &zed_actions::workspace::CopyPath,
16251        _window: &mut Window,
16252        cx: &mut Context<Self>,
16253    ) {
16254        if let Some(path) = self.target_file_abs_path(cx) {
16255            if let Some(path) = path.to_str() {
16256                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16257            }
16258        }
16259    }
16260
16261    pub fn copy_relative_path(
16262        &mut self,
16263        _: &zed_actions::workspace::CopyRelativePath,
16264        _window: &mut Window,
16265        cx: &mut Context<Self>,
16266    ) {
16267        if let Some(path) = self.target_file_path(cx) {
16268            if let Some(path) = path.to_str() {
16269                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16270            }
16271        }
16272    }
16273
16274    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16275        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16276            buffer.read(cx).project_path(cx)
16277        } else {
16278            None
16279        }
16280    }
16281
16282    // Returns true if the editor handled a go-to-line request
16283    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16284        maybe!({
16285            let breakpoint_store = self.breakpoint_store.as_ref()?;
16286
16287            let Some((_, _, active_position)) =
16288                breakpoint_store.read(cx).active_position().cloned()
16289            else {
16290                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16291                return None;
16292            };
16293
16294            let snapshot = self
16295                .project
16296                .as_ref()?
16297                .read(cx)
16298                .buffer_for_id(active_position.buffer_id?, cx)?
16299                .read(cx)
16300                .snapshot();
16301
16302            let mut handled = false;
16303            for (id, ExcerptRange { context, .. }) in self
16304                .buffer
16305                .read(cx)
16306                .excerpts_for_buffer(active_position.buffer_id?, cx)
16307            {
16308                if context.start.cmp(&active_position, &snapshot).is_ge()
16309                    || context.end.cmp(&active_position, &snapshot).is_lt()
16310                {
16311                    continue;
16312                }
16313                let snapshot = self.buffer.read(cx).snapshot(cx);
16314                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16315
16316                handled = true;
16317                self.clear_row_highlights::<DebugCurrentRowHighlight>();
16318                self.go_to_line::<DebugCurrentRowHighlight>(
16319                    multibuffer_anchor,
16320                    Some(cx.theme().colors().editor_debugger_active_line_background),
16321                    window,
16322                    cx,
16323                );
16324
16325                cx.notify();
16326            }
16327            handled.then_some(())
16328        })
16329        .is_some()
16330    }
16331
16332    pub fn copy_file_name_without_extension(
16333        &mut self,
16334        _: &CopyFileNameWithoutExtension,
16335        _: &mut Window,
16336        cx: &mut Context<Self>,
16337    ) {
16338        if let Some(file) = self.target_file(cx) {
16339            if let Some(file_stem) = file.path().file_stem() {
16340                if let Some(name) = file_stem.to_str() {
16341                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16342                }
16343            }
16344        }
16345    }
16346
16347    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16348        if let Some(file) = self.target_file(cx) {
16349            if let Some(file_name) = file.path().file_name() {
16350                if let Some(name) = file_name.to_str() {
16351                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16352                }
16353            }
16354        }
16355    }
16356
16357    pub fn toggle_git_blame(
16358        &mut self,
16359        _: &::git::Blame,
16360        window: &mut Window,
16361        cx: &mut Context<Self>,
16362    ) {
16363        self.show_git_blame_gutter = !self.show_git_blame_gutter;
16364
16365        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16366            self.start_git_blame(true, window, cx);
16367        }
16368
16369        cx.notify();
16370    }
16371
16372    pub fn toggle_git_blame_inline(
16373        &mut self,
16374        _: &ToggleGitBlameInline,
16375        window: &mut Window,
16376        cx: &mut Context<Self>,
16377    ) {
16378        self.toggle_git_blame_inline_internal(true, window, cx);
16379        cx.notify();
16380    }
16381
16382    pub fn open_git_blame_commit(
16383        &mut self,
16384        _: &OpenGitBlameCommit,
16385        window: &mut Window,
16386        cx: &mut Context<Self>,
16387    ) {
16388        self.open_git_blame_commit_internal(window, cx);
16389    }
16390
16391    fn open_git_blame_commit_internal(
16392        &mut self,
16393        window: &mut Window,
16394        cx: &mut Context<Self>,
16395    ) -> Option<()> {
16396        let blame = self.blame.as_ref()?;
16397        let snapshot = self.snapshot(window, cx);
16398        let cursor = self.selections.newest::<Point>(cx).head();
16399        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16400        let blame_entry = blame
16401            .update(cx, |blame, cx| {
16402                blame
16403                    .blame_for_rows(
16404                        &[RowInfo {
16405                            buffer_id: Some(buffer.remote_id()),
16406                            buffer_row: Some(point.row),
16407                            ..Default::default()
16408                        }],
16409                        cx,
16410                    )
16411                    .next()
16412            })
16413            .flatten()?;
16414        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16415        let repo = blame.read(cx).repository(cx)?;
16416        let workspace = self.workspace()?.downgrade();
16417        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16418        None
16419    }
16420
16421    pub fn git_blame_inline_enabled(&self) -> bool {
16422        self.git_blame_inline_enabled
16423    }
16424
16425    pub fn toggle_selection_menu(
16426        &mut self,
16427        _: &ToggleSelectionMenu,
16428        _: &mut Window,
16429        cx: &mut Context<Self>,
16430    ) {
16431        self.show_selection_menu = self
16432            .show_selection_menu
16433            .map(|show_selections_menu| !show_selections_menu)
16434            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16435
16436        cx.notify();
16437    }
16438
16439    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16440        self.show_selection_menu
16441            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16442    }
16443
16444    fn start_git_blame(
16445        &mut self,
16446        user_triggered: bool,
16447        window: &mut Window,
16448        cx: &mut Context<Self>,
16449    ) {
16450        if let Some(project) = self.project.as_ref() {
16451            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16452                return;
16453            };
16454
16455            if buffer.read(cx).file().is_none() {
16456                return;
16457            }
16458
16459            let focused = self.focus_handle(cx).contains_focused(window, cx);
16460
16461            let project = project.clone();
16462            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16463            self.blame_subscription =
16464                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16465            self.blame = Some(blame);
16466        }
16467    }
16468
16469    fn toggle_git_blame_inline_internal(
16470        &mut self,
16471        user_triggered: bool,
16472        window: &mut Window,
16473        cx: &mut Context<Self>,
16474    ) {
16475        if self.git_blame_inline_enabled {
16476            self.git_blame_inline_enabled = false;
16477            self.show_git_blame_inline = false;
16478            self.show_git_blame_inline_delay_task.take();
16479        } else {
16480            self.git_blame_inline_enabled = true;
16481            self.start_git_blame_inline(user_triggered, window, cx);
16482        }
16483
16484        cx.notify();
16485    }
16486
16487    fn start_git_blame_inline(
16488        &mut self,
16489        user_triggered: bool,
16490        window: &mut Window,
16491        cx: &mut Context<Self>,
16492    ) {
16493        self.start_git_blame(user_triggered, window, cx);
16494
16495        if ProjectSettings::get_global(cx)
16496            .git
16497            .inline_blame_delay()
16498            .is_some()
16499        {
16500            self.start_inline_blame_timer(window, cx);
16501        } else {
16502            self.show_git_blame_inline = true
16503        }
16504    }
16505
16506    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16507        self.blame.as_ref()
16508    }
16509
16510    pub fn show_git_blame_gutter(&self) -> bool {
16511        self.show_git_blame_gutter
16512    }
16513
16514    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16515        self.show_git_blame_gutter && self.has_blame_entries(cx)
16516    }
16517
16518    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16519        self.show_git_blame_inline
16520            && (self.focus_handle.is_focused(window)
16521                || self
16522                    .git_blame_inline_tooltip
16523                    .as_ref()
16524                    .and_then(|t| t.upgrade())
16525                    .is_some())
16526            && !self.newest_selection_head_on_empty_line(cx)
16527            && self.has_blame_entries(cx)
16528    }
16529
16530    fn has_blame_entries(&self, cx: &App) -> bool {
16531        self.blame()
16532            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16533    }
16534
16535    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16536        let cursor_anchor = self.selections.newest_anchor().head();
16537
16538        let snapshot = self.buffer.read(cx).snapshot(cx);
16539        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16540
16541        snapshot.line_len(buffer_row) == 0
16542    }
16543
16544    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16545        let buffer_and_selection = maybe!({
16546            let selection = self.selections.newest::<Point>(cx);
16547            let selection_range = selection.range();
16548
16549            let multi_buffer = self.buffer().read(cx);
16550            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16551            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16552
16553            let (buffer, range, _) = if selection.reversed {
16554                buffer_ranges.first()
16555            } else {
16556                buffer_ranges.last()
16557            }?;
16558
16559            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16560                ..text::ToPoint::to_point(&range.end, &buffer).row;
16561            Some((
16562                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16563                selection,
16564            ))
16565        });
16566
16567        let Some((buffer, selection)) = buffer_and_selection else {
16568            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16569        };
16570
16571        let Some(project) = self.project.as_ref() else {
16572            return Task::ready(Err(anyhow!("editor does not have project")));
16573        };
16574
16575        project.update(cx, |project, cx| {
16576            project.get_permalink_to_line(&buffer, selection, cx)
16577        })
16578    }
16579
16580    pub fn copy_permalink_to_line(
16581        &mut self,
16582        _: &CopyPermalinkToLine,
16583        window: &mut Window,
16584        cx: &mut Context<Self>,
16585    ) {
16586        let permalink_task = self.get_permalink_to_line(cx);
16587        let workspace = self.workspace();
16588
16589        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16590            Ok(permalink) => {
16591                cx.update(|_, cx| {
16592                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16593                })
16594                .ok();
16595            }
16596            Err(err) => {
16597                let message = format!("Failed to copy permalink: {err}");
16598
16599                Err::<(), anyhow::Error>(err).log_err();
16600
16601                if let Some(workspace) = workspace {
16602                    workspace
16603                        .update_in(cx, |workspace, _, cx| {
16604                            struct CopyPermalinkToLine;
16605
16606                            workspace.show_toast(
16607                                Toast::new(
16608                                    NotificationId::unique::<CopyPermalinkToLine>(),
16609                                    message,
16610                                ),
16611                                cx,
16612                            )
16613                        })
16614                        .ok();
16615                }
16616            }
16617        })
16618        .detach();
16619    }
16620
16621    pub fn copy_file_location(
16622        &mut self,
16623        _: &CopyFileLocation,
16624        _: &mut Window,
16625        cx: &mut Context<Self>,
16626    ) {
16627        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16628        if let Some(file) = self.target_file(cx) {
16629            if let Some(path) = file.path().to_str() {
16630                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16631            }
16632        }
16633    }
16634
16635    pub fn open_permalink_to_line(
16636        &mut self,
16637        _: &OpenPermalinkToLine,
16638        window: &mut Window,
16639        cx: &mut Context<Self>,
16640    ) {
16641        let permalink_task = self.get_permalink_to_line(cx);
16642        let workspace = self.workspace();
16643
16644        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16645            Ok(permalink) => {
16646                cx.update(|_, cx| {
16647                    cx.open_url(permalink.as_ref());
16648                })
16649                .ok();
16650            }
16651            Err(err) => {
16652                let message = format!("Failed to open permalink: {err}");
16653
16654                Err::<(), anyhow::Error>(err).log_err();
16655
16656                if let Some(workspace) = workspace {
16657                    workspace
16658                        .update(cx, |workspace, cx| {
16659                            struct OpenPermalinkToLine;
16660
16661                            workspace.show_toast(
16662                                Toast::new(
16663                                    NotificationId::unique::<OpenPermalinkToLine>(),
16664                                    message,
16665                                ),
16666                                cx,
16667                            )
16668                        })
16669                        .ok();
16670                }
16671            }
16672        })
16673        .detach();
16674    }
16675
16676    pub fn insert_uuid_v4(
16677        &mut self,
16678        _: &InsertUuidV4,
16679        window: &mut Window,
16680        cx: &mut Context<Self>,
16681    ) {
16682        self.insert_uuid(UuidVersion::V4, window, cx);
16683    }
16684
16685    pub fn insert_uuid_v7(
16686        &mut self,
16687        _: &InsertUuidV7,
16688        window: &mut Window,
16689        cx: &mut Context<Self>,
16690    ) {
16691        self.insert_uuid(UuidVersion::V7, window, cx);
16692    }
16693
16694    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16695        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16696        self.transact(window, cx, |this, window, cx| {
16697            let edits = this
16698                .selections
16699                .all::<Point>(cx)
16700                .into_iter()
16701                .map(|selection| {
16702                    let uuid = match version {
16703                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16704                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16705                    };
16706
16707                    (selection.range(), uuid.to_string())
16708                });
16709            this.edit(edits, cx);
16710            this.refresh_inline_completion(true, false, window, cx);
16711        });
16712    }
16713
16714    pub fn open_selections_in_multibuffer(
16715        &mut self,
16716        _: &OpenSelectionsInMultibuffer,
16717        window: &mut Window,
16718        cx: &mut Context<Self>,
16719    ) {
16720        let multibuffer = self.buffer.read(cx);
16721
16722        let Some(buffer) = multibuffer.as_singleton() else {
16723            return;
16724        };
16725
16726        let Some(workspace) = self.workspace() else {
16727            return;
16728        };
16729
16730        let locations = self
16731            .selections
16732            .disjoint_anchors()
16733            .iter()
16734            .map(|range| Location {
16735                buffer: buffer.clone(),
16736                range: range.start.text_anchor..range.end.text_anchor,
16737            })
16738            .collect::<Vec<_>>();
16739
16740        let title = multibuffer.title(cx).to_string();
16741
16742        cx.spawn_in(window, async move |_, cx| {
16743            workspace.update_in(cx, |workspace, window, cx| {
16744                Self::open_locations_in_multibuffer(
16745                    workspace,
16746                    locations,
16747                    format!("Selections for '{title}'"),
16748                    false,
16749                    MultibufferSelectionMode::All,
16750                    window,
16751                    cx,
16752                );
16753            })
16754        })
16755        .detach();
16756    }
16757
16758    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16759    /// last highlight added will be used.
16760    ///
16761    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16762    pub fn highlight_rows<T: 'static>(
16763        &mut self,
16764        range: Range<Anchor>,
16765        color: Hsla,
16766        should_autoscroll: bool,
16767        cx: &mut Context<Self>,
16768    ) {
16769        let snapshot = self.buffer().read(cx).snapshot(cx);
16770        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16771        let ix = row_highlights.binary_search_by(|highlight| {
16772            Ordering::Equal
16773                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16774                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16775        });
16776
16777        if let Err(mut ix) = ix {
16778            let index = post_inc(&mut self.highlight_order);
16779
16780            // If this range intersects with the preceding highlight, then merge it with
16781            // the preceding highlight. Otherwise insert a new highlight.
16782            let mut merged = false;
16783            if ix > 0 {
16784                let prev_highlight = &mut row_highlights[ix - 1];
16785                if prev_highlight
16786                    .range
16787                    .end
16788                    .cmp(&range.start, &snapshot)
16789                    .is_ge()
16790                {
16791                    ix -= 1;
16792                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16793                        prev_highlight.range.end = range.end;
16794                    }
16795                    merged = true;
16796                    prev_highlight.index = index;
16797                    prev_highlight.color = color;
16798                    prev_highlight.should_autoscroll = should_autoscroll;
16799                }
16800            }
16801
16802            if !merged {
16803                row_highlights.insert(
16804                    ix,
16805                    RowHighlight {
16806                        range: range.clone(),
16807                        index,
16808                        color,
16809                        should_autoscroll,
16810                    },
16811                );
16812            }
16813
16814            // If any of the following highlights intersect with this one, merge them.
16815            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16816                let highlight = &row_highlights[ix];
16817                if next_highlight
16818                    .range
16819                    .start
16820                    .cmp(&highlight.range.end, &snapshot)
16821                    .is_le()
16822                {
16823                    if next_highlight
16824                        .range
16825                        .end
16826                        .cmp(&highlight.range.end, &snapshot)
16827                        .is_gt()
16828                    {
16829                        row_highlights[ix].range.end = next_highlight.range.end;
16830                    }
16831                    row_highlights.remove(ix + 1);
16832                } else {
16833                    break;
16834                }
16835            }
16836        }
16837    }
16838
16839    /// Remove any highlighted row ranges of the given type that intersect the
16840    /// given ranges.
16841    pub fn remove_highlighted_rows<T: 'static>(
16842        &mut self,
16843        ranges_to_remove: Vec<Range<Anchor>>,
16844        cx: &mut Context<Self>,
16845    ) {
16846        let snapshot = self.buffer().read(cx).snapshot(cx);
16847        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16848        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16849        row_highlights.retain(|highlight| {
16850            while let Some(range_to_remove) = ranges_to_remove.peek() {
16851                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16852                    Ordering::Less | Ordering::Equal => {
16853                        ranges_to_remove.next();
16854                    }
16855                    Ordering::Greater => {
16856                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16857                            Ordering::Less | Ordering::Equal => {
16858                                return false;
16859                            }
16860                            Ordering::Greater => break,
16861                        }
16862                    }
16863                }
16864            }
16865
16866            true
16867        })
16868    }
16869
16870    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16871    pub fn clear_row_highlights<T: 'static>(&mut self) {
16872        self.highlighted_rows.remove(&TypeId::of::<T>());
16873    }
16874
16875    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16876    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16877        self.highlighted_rows
16878            .get(&TypeId::of::<T>())
16879            .map_or(&[] as &[_], |vec| vec.as_slice())
16880            .iter()
16881            .map(|highlight| (highlight.range.clone(), highlight.color))
16882    }
16883
16884    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16885    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16886    /// Allows to ignore certain kinds of highlights.
16887    pub fn highlighted_display_rows(
16888        &self,
16889        window: &mut Window,
16890        cx: &mut App,
16891    ) -> BTreeMap<DisplayRow, LineHighlight> {
16892        let snapshot = self.snapshot(window, cx);
16893        let mut used_highlight_orders = HashMap::default();
16894        self.highlighted_rows
16895            .iter()
16896            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16897            .fold(
16898                BTreeMap::<DisplayRow, LineHighlight>::new(),
16899                |mut unique_rows, highlight| {
16900                    let start = highlight.range.start.to_display_point(&snapshot);
16901                    let end = highlight.range.end.to_display_point(&snapshot);
16902                    let start_row = start.row().0;
16903                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16904                        && end.column() == 0
16905                    {
16906                        end.row().0.saturating_sub(1)
16907                    } else {
16908                        end.row().0
16909                    };
16910                    for row in start_row..=end_row {
16911                        let used_index =
16912                            used_highlight_orders.entry(row).or_insert(highlight.index);
16913                        if highlight.index >= *used_index {
16914                            *used_index = highlight.index;
16915                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16916                        }
16917                    }
16918                    unique_rows
16919                },
16920            )
16921    }
16922
16923    pub fn highlighted_display_row_for_autoscroll(
16924        &self,
16925        snapshot: &DisplaySnapshot,
16926    ) -> Option<DisplayRow> {
16927        self.highlighted_rows
16928            .values()
16929            .flat_map(|highlighted_rows| highlighted_rows.iter())
16930            .filter_map(|highlight| {
16931                if highlight.should_autoscroll {
16932                    Some(highlight.range.start.to_display_point(snapshot).row())
16933                } else {
16934                    None
16935                }
16936            })
16937            .min()
16938    }
16939
16940    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16941        self.highlight_background::<SearchWithinRange>(
16942            ranges,
16943            |colors| colors.editor_document_highlight_read_background,
16944            cx,
16945        )
16946    }
16947
16948    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16949        self.breadcrumb_header = Some(new_header);
16950    }
16951
16952    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16953        self.clear_background_highlights::<SearchWithinRange>(cx);
16954    }
16955
16956    pub fn highlight_background<T: 'static>(
16957        &mut self,
16958        ranges: &[Range<Anchor>],
16959        color_fetcher: fn(&ThemeColors) -> Hsla,
16960        cx: &mut Context<Self>,
16961    ) {
16962        self.background_highlights
16963            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16964        self.scrollbar_marker_state.dirty = true;
16965        cx.notify();
16966    }
16967
16968    pub fn clear_background_highlights<T: 'static>(
16969        &mut self,
16970        cx: &mut Context<Self>,
16971    ) -> Option<BackgroundHighlight> {
16972        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16973        if !text_highlights.1.is_empty() {
16974            self.scrollbar_marker_state.dirty = true;
16975            cx.notify();
16976        }
16977        Some(text_highlights)
16978    }
16979
16980    pub fn highlight_gutter<T: 'static>(
16981        &mut self,
16982        ranges: &[Range<Anchor>],
16983        color_fetcher: fn(&App) -> Hsla,
16984        cx: &mut Context<Self>,
16985    ) {
16986        self.gutter_highlights
16987            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16988        cx.notify();
16989    }
16990
16991    pub fn clear_gutter_highlights<T: 'static>(
16992        &mut self,
16993        cx: &mut Context<Self>,
16994    ) -> Option<GutterHighlight> {
16995        cx.notify();
16996        self.gutter_highlights.remove(&TypeId::of::<T>())
16997    }
16998
16999    #[cfg(feature = "test-support")]
17000    pub fn all_text_background_highlights(
17001        &self,
17002        window: &mut Window,
17003        cx: &mut Context<Self>,
17004    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17005        let snapshot = self.snapshot(window, cx);
17006        let buffer = &snapshot.buffer_snapshot;
17007        let start = buffer.anchor_before(0);
17008        let end = buffer.anchor_after(buffer.len());
17009        let theme = cx.theme().colors();
17010        self.background_highlights_in_range(start..end, &snapshot, theme)
17011    }
17012
17013    #[cfg(feature = "test-support")]
17014    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17015        let snapshot = self.buffer().read(cx).snapshot(cx);
17016
17017        let highlights = self
17018            .background_highlights
17019            .get(&TypeId::of::<items::BufferSearchHighlights>());
17020
17021        if let Some((_color, ranges)) = highlights {
17022            ranges
17023                .iter()
17024                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17025                .collect_vec()
17026        } else {
17027            vec![]
17028        }
17029    }
17030
17031    fn document_highlights_for_position<'a>(
17032        &'a self,
17033        position: Anchor,
17034        buffer: &'a MultiBufferSnapshot,
17035    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17036        let read_highlights = self
17037            .background_highlights
17038            .get(&TypeId::of::<DocumentHighlightRead>())
17039            .map(|h| &h.1);
17040        let write_highlights = self
17041            .background_highlights
17042            .get(&TypeId::of::<DocumentHighlightWrite>())
17043            .map(|h| &h.1);
17044        let left_position = position.bias_left(buffer);
17045        let right_position = position.bias_right(buffer);
17046        read_highlights
17047            .into_iter()
17048            .chain(write_highlights)
17049            .flat_map(move |ranges| {
17050                let start_ix = match ranges.binary_search_by(|probe| {
17051                    let cmp = probe.end.cmp(&left_position, buffer);
17052                    if cmp.is_ge() {
17053                        Ordering::Greater
17054                    } else {
17055                        Ordering::Less
17056                    }
17057                }) {
17058                    Ok(i) | Err(i) => i,
17059                };
17060
17061                ranges[start_ix..]
17062                    .iter()
17063                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17064            })
17065    }
17066
17067    pub fn has_background_highlights<T: 'static>(&self) -> bool {
17068        self.background_highlights
17069            .get(&TypeId::of::<T>())
17070            .map_or(false, |(_, highlights)| !highlights.is_empty())
17071    }
17072
17073    pub fn background_highlights_in_range(
17074        &self,
17075        search_range: Range<Anchor>,
17076        display_snapshot: &DisplaySnapshot,
17077        theme: &ThemeColors,
17078    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17079        let mut results = Vec::new();
17080        for (color_fetcher, ranges) in self.background_highlights.values() {
17081            let color = color_fetcher(theme);
17082            let start_ix = match ranges.binary_search_by(|probe| {
17083                let cmp = probe
17084                    .end
17085                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17086                if cmp.is_gt() {
17087                    Ordering::Greater
17088                } else {
17089                    Ordering::Less
17090                }
17091            }) {
17092                Ok(i) | Err(i) => i,
17093            };
17094            for range in &ranges[start_ix..] {
17095                if range
17096                    .start
17097                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17098                    .is_ge()
17099                {
17100                    break;
17101                }
17102
17103                let start = range.start.to_display_point(display_snapshot);
17104                let end = range.end.to_display_point(display_snapshot);
17105                results.push((start..end, color))
17106            }
17107        }
17108        results
17109    }
17110
17111    pub fn background_highlight_row_ranges<T: 'static>(
17112        &self,
17113        search_range: Range<Anchor>,
17114        display_snapshot: &DisplaySnapshot,
17115        count: usize,
17116    ) -> Vec<RangeInclusive<DisplayPoint>> {
17117        let mut results = Vec::new();
17118        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17119            return vec![];
17120        };
17121
17122        let start_ix = match ranges.binary_search_by(|probe| {
17123            let cmp = probe
17124                .end
17125                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17126            if cmp.is_gt() {
17127                Ordering::Greater
17128            } else {
17129                Ordering::Less
17130            }
17131        }) {
17132            Ok(i) | Err(i) => i,
17133        };
17134        let mut push_region = |start: Option<Point>, end: Option<Point>| {
17135            if let (Some(start_display), Some(end_display)) = (start, end) {
17136                results.push(
17137                    start_display.to_display_point(display_snapshot)
17138                        ..=end_display.to_display_point(display_snapshot),
17139                );
17140            }
17141        };
17142        let mut start_row: Option<Point> = None;
17143        let mut end_row: Option<Point> = None;
17144        if ranges.len() > count {
17145            return Vec::new();
17146        }
17147        for range in &ranges[start_ix..] {
17148            if range
17149                .start
17150                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17151                .is_ge()
17152            {
17153                break;
17154            }
17155            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17156            if let Some(current_row) = &end_row {
17157                if end.row == current_row.row {
17158                    continue;
17159                }
17160            }
17161            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17162            if start_row.is_none() {
17163                assert_eq!(end_row, None);
17164                start_row = Some(start);
17165                end_row = Some(end);
17166                continue;
17167            }
17168            if let Some(current_end) = end_row.as_mut() {
17169                if start.row > current_end.row + 1 {
17170                    push_region(start_row, end_row);
17171                    start_row = Some(start);
17172                    end_row = Some(end);
17173                } else {
17174                    // Merge two hunks.
17175                    *current_end = end;
17176                }
17177            } else {
17178                unreachable!();
17179            }
17180        }
17181        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17182        push_region(start_row, end_row);
17183        results
17184    }
17185
17186    pub fn gutter_highlights_in_range(
17187        &self,
17188        search_range: Range<Anchor>,
17189        display_snapshot: &DisplaySnapshot,
17190        cx: &App,
17191    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17192        let mut results = Vec::new();
17193        for (color_fetcher, ranges) in self.gutter_highlights.values() {
17194            let color = color_fetcher(cx);
17195            let start_ix = match ranges.binary_search_by(|probe| {
17196                let cmp = probe
17197                    .end
17198                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17199                if cmp.is_gt() {
17200                    Ordering::Greater
17201                } else {
17202                    Ordering::Less
17203                }
17204            }) {
17205                Ok(i) | Err(i) => i,
17206            };
17207            for range in &ranges[start_ix..] {
17208                if range
17209                    .start
17210                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17211                    .is_ge()
17212                {
17213                    break;
17214                }
17215
17216                let start = range.start.to_display_point(display_snapshot);
17217                let end = range.end.to_display_point(display_snapshot);
17218                results.push((start..end, color))
17219            }
17220        }
17221        results
17222    }
17223
17224    /// Get the text ranges corresponding to the redaction query
17225    pub fn redacted_ranges(
17226        &self,
17227        search_range: Range<Anchor>,
17228        display_snapshot: &DisplaySnapshot,
17229        cx: &App,
17230    ) -> Vec<Range<DisplayPoint>> {
17231        display_snapshot
17232            .buffer_snapshot
17233            .redacted_ranges(search_range, |file| {
17234                if let Some(file) = file {
17235                    file.is_private()
17236                        && EditorSettings::get(
17237                            Some(SettingsLocation {
17238                                worktree_id: file.worktree_id(cx),
17239                                path: file.path().as_ref(),
17240                            }),
17241                            cx,
17242                        )
17243                        .redact_private_values
17244                } else {
17245                    false
17246                }
17247            })
17248            .map(|range| {
17249                range.start.to_display_point(display_snapshot)
17250                    ..range.end.to_display_point(display_snapshot)
17251            })
17252            .collect()
17253    }
17254
17255    pub fn highlight_text<T: 'static>(
17256        &mut self,
17257        ranges: Vec<Range<Anchor>>,
17258        style: HighlightStyle,
17259        cx: &mut Context<Self>,
17260    ) {
17261        self.display_map.update(cx, |map, _| {
17262            map.highlight_text(TypeId::of::<T>(), ranges, style)
17263        });
17264        cx.notify();
17265    }
17266
17267    pub(crate) fn highlight_inlays<T: 'static>(
17268        &mut self,
17269        highlights: Vec<InlayHighlight>,
17270        style: HighlightStyle,
17271        cx: &mut Context<Self>,
17272    ) {
17273        self.display_map.update(cx, |map, _| {
17274            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17275        });
17276        cx.notify();
17277    }
17278
17279    pub fn text_highlights<'a, T: 'static>(
17280        &'a self,
17281        cx: &'a App,
17282    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17283        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17284    }
17285
17286    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17287        let cleared = self
17288            .display_map
17289            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17290        if cleared {
17291            cx.notify();
17292        }
17293    }
17294
17295    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17296        (self.read_only(cx) || self.blink_manager.read(cx).visible())
17297            && self.focus_handle.is_focused(window)
17298    }
17299
17300    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17301        self.show_cursor_when_unfocused = is_enabled;
17302        cx.notify();
17303    }
17304
17305    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17306        cx.notify();
17307    }
17308
17309    fn on_buffer_event(
17310        &mut self,
17311        multibuffer: &Entity<MultiBuffer>,
17312        event: &multi_buffer::Event,
17313        window: &mut Window,
17314        cx: &mut Context<Self>,
17315    ) {
17316        match event {
17317            multi_buffer::Event::Edited {
17318                singleton_buffer_edited,
17319                edited_buffer: buffer_edited,
17320            } => {
17321                self.scrollbar_marker_state.dirty = true;
17322                self.active_indent_guides_state.dirty = true;
17323                self.refresh_active_diagnostics(cx);
17324                self.refresh_code_actions(window, cx);
17325                if self.has_active_inline_completion() {
17326                    self.update_visible_inline_completion(window, cx);
17327                }
17328                if let Some(buffer) = buffer_edited {
17329                    let buffer_id = buffer.read(cx).remote_id();
17330                    if !self.registered_buffers.contains_key(&buffer_id) {
17331                        if let Some(project) = self.project.as_ref() {
17332                            project.update(cx, |project, cx| {
17333                                self.registered_buffers.insert(
17334                                    buffer_id,
17335                                    project.register_buffer_with_language_servers(&buffer, cx),
17336                                );
17337                            })
17338                        }
17339                    }
17340                }
17341                cx.emit(EditorEvent::BufferEdited);
17342                cx.emit(SearchEvent::MatchesInvalidated);
17343                if *singleton_buffer_edited {
17344                    if let Some(project) = &self.project {
17345                        #[allow(clippy::mutable_key_type)]
17346                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17347                            multibuffer
17348                                .all_buffers()
17349                                .into_iter()
17350                                .filter_map(|buffer| {
17351                                    buffer.update(cx, |buffer, cx| {
17352                                        let language = buffer.language()?;
17353                                        let should_discard = project.update(cx, |project, cx| {
17354                                            project.is_local()
17355                                                && !project.has_language_servers_for(buffer, cx)
17356                                        });
17357                                        should_discard.not().then_some(language.clone())
17358                                    })
17359                                })
17360                                .collect::<HashSet<_>>()
17361                        });
17362                        if !languages_affected.is_empty() {
17363                            self.refresh_inlay_hints(
17364                                InlayHintRefreshReason::BufferEdited(languages_affected),
17365                                cx,
17366                            );
17367                        }
17368                    }
17369                }
17370
17371                let Some(project) = &self.project else { return };
17372                let (telemetry, is_via_ssh) = {
17373                    let project = project.read(cx);
17374                    let telemetry = project.client().telemetry().clone();
17375                    let is_via_ssh = project.is_via_ssh();
17376                    (telemetry, is_via_ssh)
17377                };
17378                refresh_linked_ranges(self, window, cx);
17379                telemetry.log_edit_event("editor", is_via_ssh);
17380            }
17381            multi_buffer::Event::ExcerptsAdded {
17382                buffer,
17383                predecessor,
17384                excerpts,
17385            } => {
17386                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17387                let buffer_id = buffer.read(cx).remote_id();
17388                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17389                    if let Some(project) = &self.project {
17390                        get_uncommitted_diff_for_buffer(
17391                            project,
17392                            [buffer.clone()],
17393                            self.buffer.clone(),
17394                            cx,
17395                        )
17396                        .detach();
17397                    }
17398                }
17399                cx.emit(EditorEvent::ExcerptsAdded {
17400                    buffer: buffer.clone(),
17401                    predecessor: *predecessor,
17402                    excerpts: excerpts.clone(),
17403                });
17404                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17405            }
17406            multi_buffer::Event::ExcerptsRemoved { ids } => {
17407                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17408                let buffer = self.buffer.read(cx);
17409                self.registered_buffers
17410                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17411                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17412                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17413            }
17414            multi_buffer::Event::ExcerptsEdited {
17415                excerpt_ids,
17416                buffer_ids,
17417            } => {
17418                self.display_map.update(cx, |map, cx| {
17419                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
17420                });
17421                cx.emit(EditorEvent::ExcerptsEdited {
17422                    ids: excerpt_ids.clone(),
17423                })
17424            }
17425            multi_buffer::Event::ExcerptsExpanded { ids } => {
17426                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17427                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17428            }
17429            multi_buffer::Event::Reparsed(buffer_id) => {
17430                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17431                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17432
17433                cx.emit(EditorEvent::Reparsed(*buffer_id));
17434            }
17435            multi_buffer::Event::DiffHunksToggled => {
17436                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17437            }
17438            multi_buffer::Event::LanguageChanged(buffer_id) => {
17439                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17440                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17441                cx.emit(EditorEvent::Reparsed(*buffer_id));
17442                cx.notify();
17443            }
17444            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17445            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17446            multi_buffer::Event::FileHandleChanged
17447            | multi_buffer::Event::Reloaded
17448            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17449            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17450            multi_buffer::Event::DiagnosticsUpdated => {
17451                self.refresh_active_diagnostics(cx);
17452                self.refresh_inline_diagnostics(true, window, cx);
17453                self.scrollbar_marker_state.dirty = true;
17454                cx.notify();
17455            }
17456            _ => {}
17457        };
17458    }
17459
17460    fn on_display_map_changed(
17461        &mut self,
17462        _: Entity<DisplayMap>,
17463        _: &mut Window,
17464        cx: &mut Context<Self>,
17465    ) {
17466        cx.notify();
17467    }
17468
17469    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17470        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17471        self.update_edit_prediction_settings(cx);
17472        self.refresh_inline_completion(true, false, window, cx);
17473        self.refresh_inlay_hints(
17474            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17475                self.selections.newest_anchor().head(),
17476                &self.buffer.read(cx).snapshot(cx),
17477                cx,
17478            )),
17479            cx,
17480        );
17481
17482        let old_cursor_shape = self.cursor_shape;
17483
17484        {
17485            let editor_settings = EditorSettings::get_global(cx);
17486            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17487            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17488            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17489            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17490        }
17491
17492        if old_cursor_shape != self.cursor_shape {
17493            cx.emit(EditorEvent::CursorShapeChanged);
17494        }
17495
17496        let project_settings = ProjectSettings::get_global(cx);
17497        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17498
17499        if self.mode.is_full() {
17500            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17501            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17502            if self.show_inline_diagnostics != show_inline_diagnostics {
17503                self.show_inline_diagnostics = show_inline_diagnostics;
17504                self.refresh_inline_diagnostics(false, window, cx);
17505            }
17506
17507            if self.git_blame_inline_enabled != inline_blame_enabled {
17508                self.toggle_git_blame_inline_internal(false, window, cx);
17509            }
17510        }
17511
17512        cx.notify();
17513    }
17514
17515    pub fn set_searchable(&mut self, searchable: bool) {
17516        self.searchable = searchable;
17517    }
17518
17519    pub fn searchable(&self) -> bool {
17520        self.searchable
17521    }
17522
17523    fn open_proposed_changes_editor(
17524        &mut self,
17525        _: &OpenProposedChangesEditor,
17526        window: &mut Window,
17527        cx: &mut Context<Self>,
17528    ) {
17529        let Some(workspace) = self.workspace() else {
17530            cx.propagate();
17531            return;
17532        };
17533
17534        let selections = self.selections.all::<usize>(cx);
17535        let multi_buffer = self.buffer.read(cx);
17536        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17537        let mut new_selections_by_buffer = HashMap::default();
17538        for selection in selections {
17539            for (buffer, range, _) in
17540                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17541            {
17542                let mut range = range.to_point(buffer);
17543                range.start.column = 0;
17544                range.end.column = buffer.line_len(range.end.row);
17545                new_selections_by_buffer
17546                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17547                    .or_insert(Vec::new())
17548                    .push(range)
17549            }
17550        }
17551
17552        let proposed_changes_buffers = new_selections_by_buffer
17553            .into_iter()
17554            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17555            .collect::<Vec<_>>();
17556        let proposed_changes_editor = cx.new(|cx| {
17557            ProposedChangesEditor::new(
17558                "Proposed changes",
17559                proposed_changes_buffers,
17560                self.project.clone(),
17561                window,
17562                cx,
17563            )
17564        });
17565
17566        window.defer(cx, move |window, cx| {
17567            workspace.update(cx, |workspace, cx| {
17568                workspace.active_pane().update(cx, |pane, cx| {
17569                    pane.add_item(
17570                        Box::new(proposed_changes_editor),
17571                        true,
17572                        true,
17573                        None,
17574                        window,
17575                        cx,
17576                    );
17577                });
17578            });
17579        });
17580    }
17581
17582    pub fn open_excerpts_in_split(
17583        &mut self,
17584        _: &OpenExcerptsSplit,
17585        window: &mut Window,
17586        cx: &mut Context<Self>,
17587    ) {
17588        self.open_excerpts_common(None, true, window, cx)
17589    }
17590
17591    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17592        self.open_excerpts_common(None, false, window, cx)
17593    }
17594
17595    fn open_excerpts_common(
17596        &mut self,
17597        jump_data: Option<JumpData>,
17598        split: bool,
17599        window: &mut Window,
17600        cx: &mut Context<Self>,
17601    ) {
17602        let Some(workspace) = self.workspace() else {
17603            cx.propagate();
17604            return;
17605        };
17606
17607        if self.buffer.read(cx).is_singleton() {
17608            cx.propagate();
17609            return;
17610        }
17611
17612        let mut new_selections_by_buffer = HashMap::default();
17613        match &jump_data {
17614            Some(JumpData::MultiBufferPoint {
17615                excerpt_id,
17616                position,
17617                anchor,
17618                line_offset_from_top,
17619            }) => {
17620                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17621                if let Some(buffer) = multi_buffer_snapshot
17622                    .buffer_id_for_excerpt(*excerpt_id)
17623                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17624                {
17625                    let buffer_snapshot = buffer.read(cx).snapshot();
17626                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17627                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17628                    } else {
17629                        buffer_snapshot.clip_point(*position, Bias::Left)
17630                    };
17631                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17632                    new_selections_by_buffer.insert(
17633                        buffer,
17634                        (
17635                            vec![jump_to_offset..jump_to_offset],
17636                            Some(*line_offset_from_top),
17637                        ),
17638                    );
17639                }
17640            }
17641            Some(JumpData::MultiBufferRow {
17642                row,
17643                line_offset_from_top,
17644            }) => {
17645                let point = MultiBufferPoint::new(row.0, 0);
17646                if let Some((buffer, buffer_point, _)) =
17647                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17648                {
17649                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17650                    new_selections_by_buffer
17651                        .entry(buffer)
17652                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17653                        .0
17654                        .push(buffer_offset..buffer_offset)
17655                }
17656            }
17657            None => {
17658                let selections = self.selections.all::<usize>(cx);
17659                let multi_buffer = self.buffer.read(cx);
17660                for selection in selections {
17661                    for (snapshot, range, _, anchor) in multi_buffer
17662                        .snapshot(cx)
17663                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17664                    {
17665                        if let Some(anchor) = anchor {
17666                            // selection is in a deleted hunk
17667                            let Some(buffer_id) = anchor.buffer_id else {
17668                                continue;
17669                            };
17670                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17671                                continue;
17672                            };
17673                            let offset = text::ToOffset::to_offset(
17674                                &anchor.text_anchor,
17675                                &buffer_handle.read(cx).snapshot(),
17676                            );
17677                            let range = offset..offset;
17678                            new_selections_by_buffer
17679                                .entry(buffer_handle)
17680                                .or_insert((Vec::new(), None))
17681                                .0
17682                                .push(range)
17683                        } else {
17684                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17685                            else {
17686                                continue;
17687                            };
17688                            new_selections_by_buffer
17689                                .entry(buffer_handle)
17690                                .or_insert((Vec::new(), None))
17691                                .0
17692                                .push(range)
17693                        }
17694                    }
17695                }
17696            }
17697        }
17698
17699        new_selections_by_buffer
17700            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17701
17702        if new_selections_by_buffer.is_empty() {
17703            return;
17704        }
17705
17706        // We defer the pane interaction because we ourselves are a workspace item
17707        // and activating a new item causes the pane to call a method on us reentrantly,
17708        // which panics if we're on the stack.
17709        window.defer(cx, move |window, cx| {
17710            workspace.update(cx, |workspace, cx| {
17711                let pane = if split {
17712                    workspace.adjacent_pane(window, cx)
17713                } else {
17714                    workspace.active_pane().clone()
17715                };
17716
17717                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17718                    let editor = buffer
17719                        .read(cx)
17720                        .file()
17721                        .is_none()
17722                        .then(|| {
17723                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17724                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17725                            // Instead, we try to activate the existing editor in the pane first.
17726                            let (editor, pane_item_index) =
17727                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17728                                    let editor = item.downcast::<Editor>()?;
17729                                    let singleton_buffer =
17730                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17731                                    if singleton_buffer == buffer {
17732                                        Some((editor, i))
17733                                    } else {
17734                                        None
17735                                    }
17736                                })?;
17737                            pane.update(cx, |pane, cx| {
17738                                pane.activate_item(pane_item_index, true, true, window, cx)
17739                            });
17740                            Some(editor)
17741                        })
17742                        .flatten()
17743                        .unwrap_or_else(|| {
17744                            workspace.open_project_item::<Self>(
17745                                pane.clone(),
17746                                buffer,
17747                                true,
17748                                true,
17749                                window,
17750                                cx,
17751                            )
17752                        });
17753
17754                    editor.update(cx, |editor, cx| {
17755                        let autoscroll = match scroll_offset {
17756                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17757                            None => Autoscroll::newest(),
17758                        };
17759                        let nav_history = editor.nav_history.take();
17760                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17761                            s.select_ranges(ranges);
17762                        });
17763                        editor.nav_history = nav_history;
17764                    });
17765                }
17766            })
17767        });
17768    }
17769
17770    // For now, don't allow opening excerpts in buffers that aren't backed by
17771    // regular project files.
17772    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17773        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17774    }
17775
17776    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17777        let snapshot = self.buffer.read(cx).read(cx);
17778        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17779        Some(
17780            ranges
17781                .iter()
17782                .map(move |range| {
17783                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17784                })
17785                .collect(),
17786        )
17787    }
17788
17789    fn selection_replacement_ranges(
17790        &self,
17791        range: Range<OffsetUtf16>,
17792        cx: &mut App,
17793    ) -> Vec<Range<OffsetUtf16>> {
17794        let selections = self.selections.all::<OffsetUtf16>(cx);
17795        let newest_selection = selections
17796            .iter()
17797            .max_by_key(|selection| selection.id)
17798            .unwrap();
17799        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17800        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17801        let snapshot = self.buffer.read(cx).read(cx);
17802        selections
17803            .into_iter()
17804            .map(|mut selection| {
17805                selection.start.0 =
17806                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17807                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17808                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17809                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17810            })
17811            .collect()
17812    }
17813
17814    fn report_editor_event(
17815        &self,
17816        event_type: &'static str,
17817        file_extension: Option<String>,
17818        cx: &App,
17819    ) {
17820        if cfg!(any(test, feature = "test-support")) {
17821            return;
17822        }
17823
17824        let Some(project) = &self.project else { return };
17825
17826        // If None, we are in a file without an extension
17827        let file = self
17828            .buffer
17829            .read(cx)
17830            .as_singleton()
17831            .and_then(|b| b.read(cx).file());
17832        let file_extension = file_extension.or(file
17833            .as_ref()
17834            .and_then(|file| Path::new(file.file_name(cx)).extension())
17835            .and_then(|e| e.to_str())
17836            .map(|a| a.to_string()));
17837
17838        let vim_mode = vim_enabled(cx);
17839
17840        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17841        let copilot_enabled = edit_predictions_provider
17842            == language::language_settings::EditPredictionProvider::Copilot;
17843        let copilot_enabled_for_language = self
17844            .buffer
17845            .read(cx)
17846            .language_settings(cx)
17847            .show_edit_predictions;
17848
17849        let project = project.read(cx);
17850        telemetry::event!(
17851            event_type,
17852            file_extension,
17853            vim_mode,
17854            copilot_enabled,
17855            copilot_enabled_for_language,
17856            edit_predictions_provider,
17857            is_via_ssh = project.is_via_ssh(),
17858        );
17859    }
17860
17861    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17862    /// with each line being an array of {text, highlight} objects.
17863    fn copy_highlight_json(
17864        &mut self,
17865        _: &CopyHighlightJson,
17866        window: &mut Window,
17867        cx: &mut Context<Self>,
17868    ) {
17869        #[derive(Serialize)]
17870        struct Chunk<'a> {
17871            text: String,
17872            highlight: Option<&'a str>,
17873        }
17874
17875        let snapshot = self.buffer.read(cx).snapshot(cx);
17876        let range = self
17877            .selected_text_range(false, window, cx)
17878            .and_then(|selection| {
17879                if selection.range.is_empty() {
17880                    None
17881                } else {
17882                    Some(selection.range)
17883                }
17884            })
17885            .unwrap_or_else(|| 0..snapshot.len());
17886
17887        let chunks = snapshot.chunks(range, true);
17888        let mut lines = Vec::new();
17889        let mut line: VecDeque<Chunk> = VecDeque::new();
17890
17891        let Some(style) = self.style.as_ref() else {
17892            return;
17893        };
17894
17895        for chunk in chunks {
17896            let highlight = chunk
17897                .syntax_highlight_id
17898                .and_then(|id| id.name(&style.syntax));
17899            let mut chunk_lines = chunk.text.split('\n').peekable();
17900            while let Some(text) = chunk_lines.next() {
17901                let mut merged_with_last_token = false;
17902                if let Some(last_token) = line.back_mut() {
17903                    if last_token.highlight == highlight {
17904                        last_token.text.push_str(text);
17905                        merged_with_last_token = true;
17906                    }
17907                }
17908
17909                if !merged_with_last_token {
17910                    line.push_back(Chunk {
17911                        text: text.into(),
17912                        highlight,
17913                    });
17914                }
17915
17916                if chunk_lines.peek().is_some() {
17917                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17918                        line.pop_front();
17919                    }
17920                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17921                        line.pop_back();
17922                    }
17923
17924                    lines.push(mem::take(&mut line));
17925                }
17926            }
17927        }
17928
17929        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17930            return;
17931        };
17932        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17933    }
17934
17935    pub fn open_context_menu(
17936        &mut self,
17937        _: &OpenContextMenu,
17938        window: &mut Window,
17939        cx: &mut Context<Self>,
17940    ) {
17941        self.request_autoscroll(Autoscroll::newest(), cx);
17942        let position = self.selections.newest_display(cx).start;
17943        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17944    }
17945
17946    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17947        &self.inlay_hint_cache
17948    }
17949
17950    pub fn replay_insert_event(
17951        &mut self,
17952        text: &str,
17953        relative_utf16_range: Option<Range<isize>>,
17954        window: &mut Window,
17955        cx: &mut Context<Self>,
17956    ) {
17957        if !self.input_enabled {
17958            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17959            return;
17960        }
17961        if let Some(relative_utf16_range) = relative_utf16_range {
17962            let selections = self.selections.all::<OffsetUtf16>(cx);
17963            self.change_selections(None, window, cx, |s| {
17964                let new_ranges = selections.into_iter().map(|range| {
17965                    let start = OffsetUtf16(
17966                        range
17967                            .head()
17968                            .0
17969                            .saturating_add_signed(relative_utf16_range.start),
17970                    );
17971                    let end = OffsetUtf16(
17972                        range
17973                            .head()
17974                            .0
17975                            .saturating_add_signed(relative_utf16_range.end),
17976                    );
17977                    start..end
17978                });
17979                s.select_ranges(new_ranges);
17980            });
17981        }
17982
17983        self.handle_input(text, window, cx);
17984    }
17985
17986    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17987        let Some(provider) = self.semantics_provider.as_ref() else {
17988            return false;
17989        };
17990
17991        let mut supports = false;
17992        self.buffer().update(cx, |this, cx| {
17993            this.for_each_buffer(|buffer| {
17994                supports |= provider.supports_inlay_hints(buffer, cx);
17995            });
17996        });
17997
17998        supports
17999    }
18000
18001    pub fn is_focused(&self, window: &Window) -> bool {
18002        self.focus_handle.is_focused(window)
18003    }
18004
18005    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18006        cx.emit(EditorEvent::Focused);
18007
18008        if let Some(descendant) = self
18009            .last_focused_descendant
18010            .take()
18011            .and_then(|descendant| descendant.upgrade())
18012        {
18013            window.focus(&descendant);
18014        } else {
18015            if let Some(blame) = self.blame.as_ref() {
18016                blame.update(cx, GitBlame::focus)
18017            }
18018
18019            self.blink_manager.update(cx, BlinkManager::enable);
18020            self.show_cursor_names(window, cx);
18021            self.buffer.update(cx, |buffer, cx| {
18022                buffer.finalize_last_transaction(cx);
18023                if self.leader_peer_id.is_none() {
18024                    buffer.set_active_selections(
18025                        &self.selections.disjoint_anchors(),
18026                        self.selections.line_mode,
18027                        self.cursor_shape,
18028                        cx,
18029                    );
18030                }
18031            });
18032        }
18033    }
18034
18035    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18036        cx.emit(EditorEvent::FocusedIn)
18037    }
18038
18039    fn handle_focus_out(
18040        &mut self,
18041        event: FocusOutEvent,
18042        _window: &mut Window,
18043        cx: &mut Context<Self>,
18044    ) {
18045        if event.blurred != self.focus_handle {
18046            self.last_focused_descendant = Some(event.blurred);
18047        }
18048        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18049    }
18050
18051    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18052        self.blink_manager.update(cx, BlinkManager::disable);
18053        self.buffer
18054            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18055
18056        if let Some(blame) = self.blame.as_ref() {
18057            blame.update(cx, GitBlame::blur)
18058        }
18059        if !self.hover_state.focused(window, cx) {
18060            hide_hover(self, cx);
18061        }
18062        if !self
18063            .context_menu
18064            .borrow()
18065            .as_ref()
18066            .is_some_and(|context_menu| context_menu.focused(window, cx))
18067        {
18068            self.hide_context_menu(window, cx);
18069        }
18070        self.discard_inline_completion(false, cx);
18071        cx.emit(EditorEvent::Blurred);
18072        cx.notify();
18073    }
18074
18075    pub fn register_action<A: Action>(
18076        &mut self,
18077        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18078    ) -> Subscription {
18079        let id = self.next_editor_action_id.post_inc();
18080        let listener = Arc::new(listener);
18081        self.editor_actions.borrow_mut().insert(
18082            id,
18083            Box::new(move |window, _| {
18084                let listener = listener.clone();
18085                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18086                    let action = action.downcast_ref().unwrap();
18087                    if phase == DispatchPhase::Bubble {
18088                        listener(action, window, cx)
18089                    }
18090                })
18091            }),
18092        );
18093
18094        let editor_actions = self.editor_actions.clone();
18095        Subscription::new(move || {
18096            editor_actions.borrow_mut().remove(&id);
18097        })
18098    }
18099
18100    pub fn file_header_size(&self) -> u32 {
18101        FILE_HEADER_HEIGHT
18102    }
18103
18104    pub fn restore(
18105        &mut self,
18106        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18107        window: &mut Window,
18108        cx: &mut Context<Self>,
18109    ) {
18110        let workspace = self.workspace();
18111        let project = self.project.as_ref();
18112        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18113            let mut tasks = Vec::new();
18114            for (buffer_id, changes) in revert_changes {
18115                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18116                    buffer.update(cx, |buffer, cx| {
18117                        buffer.edit(
18118                            changes
18119                                .into_iter()
18120                                .map(|(range, text)| (range, text.to_string())),
18121                            None,
18122                            cx,
18123                        );
18124                    });
18125
18126                    if let Some(project) =
18127                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18128                    {
18129                        project.update(cx, |project, cx| {
18130                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18131                        })
18132                    }
18133                }
18134            }
18135            tasks
18136        });
18137        cx.spawn_in(window, async move |_, cx| {
18138            for (buffer, task) in save_tasks {
18139                let result = task.await;
18140                if result.is_err() {
18141                    let Some(path) = buffer
18142                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
18143                        .ok()
18144                    else {
18145                        continue;
18146                    };
18147                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18148                        let Some(task) = cx
18149                            .update_window_entity(&workspace, |workspace, window, cx| {
18150                                workspace
18151                                    .open_path_preview(path, None, false, false, false, window, cx)
18152                            })
18153                            .ok()
18154                        else {
18155                            continue;
18156                        };
18157                        task.await.log_err();
18158                    }
18159                }
18160            }
18161        })
18162        .detach();
18163        self.change_selections(None, window, cx, |selections| selections.refresh());
18164    }
18165
18166    pub fn to_pixel_point(
18167        &self,
18168        source: multi_buffer::Anchor,
18169        editor_snapshot: &EditorSnapshot,
18170        window: &mut Window,
18171    ) -> Option<gpui::Point<Pixels>> {
18172        let source_point = source.to_display_point(editor_snapshot);
18173        self.display_to_pixel_point(source_point, editor_snapshot, window)
18174    }
18175
18176    pub fn display_to_pixel_point(
18177        &self,
18178        source: DisplayPoint,
18179        editor_snapshot: &EditorSnapshot,
18180        window: &mut Window,
18181    ) -> Option<gpui::Point<Pixels>> {
18182        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18183        let text_layout_details = self.text_layout_details(window);
18184        let scroll_top = text_layout_details
18185            .scroll_anchor
18186            .scroll_position(editor_snapshot)
18187            .y;
18188
18189        if source.row().as_f32() < scroll_top.floor() {
18190            return None;
18191        }
18192        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18193        let source_y = line_height * (source.row().as_f32() - scroll_top);
18194        Some(gpui::Point::new(source_x, source_y))
18195    }
18196
18197    pub fn has_visible_completions_menu(&self) -> bool {
18198        !self.edit_prediction_preview_is_active()
18199            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18200                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18201            })
18202    }
18203
18204    pub fn register_addon<T: Addon>(&mut self, instance: T) {
18205        self.addons
18206            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18207    }
18208
18209    pub fn unregister_addon<T: Addon>(&mut self) {
18210        self.addons.remove(&std::any::TypeId::of::<T>());
18211    }
18212
18213    pub fn addon<T: Addon>(&self) -> Option<&T> {
18214        let type_id = std::any::TypeId::of::<T>();
18215        self.addons
18216            .get(&type_id)
18217            .and_then(|item| item.to_any().downcast_ref::<T>())
18218    }
18219
18220    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18221        let text_layout_details = self.text_layout_details(window);
18222        let style = &text_layout_details.editor_style;
18223        let font_id = window.text_system().resolve_font(&style.text.font());
18224        let font_size = style.text.font_size.to_pixels(window.rem_size());
18225        let line_height = style.text.line_height_in_pixels(window.rem_size());
18226        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18227
18228        gpui::Size::new(em_width, line_height)
18229    }
18230
18231    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18232        self.load_diff_task.clone()
18233    }
18234
18235    fn read_metadata_from_db(
18236        &mut self,
18237        item_id: u64,
18238        workspace_id: WorkspaceId,
18239        window: &mut Window,
18240        cx: &mut Context<Editor>,
18241    ) {
18242        if self.is_singleton(cx)
18243            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18244        {
18245            let buffer_snapshot = OnceCell::new();
18246
18247            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18248                if !folds.is_empty() {
18249                    let snapshot =
18250                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18251                    self.fold_ranges(
18252                        folds
18253                            .into_iter()
18254                            .map(|(start, end)| {
18255                                snapshot.clip_offset(start, Bias::Left)
18256                                    ..snapshot.clip_offset(end, Bias::Right)
18257                            })
18258                            .collect(),
18259                        false,
18260                        window,
18261                        cx,
18262                    );
18263                }
18264            }
18265
18266            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18267                if !selections.is_empty() {
18268                    let snapshot =
18269                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18270                    self.change_selections(None, window, cx, |s| {
18271                        s.select_ranges(selections.into_iter().map(|(start, end)| {
18272                            snapshot.clip_offset(start, Bias::Left)
18273                                ..snapshot.clip_offset(end, Bias::Right)
18274                        }));
18275                    });
18276                }
18277            };
18278        }
18279
18280        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18281    }
18282}
18283
18284fn vim_enabled(cx: &App) -> bool {
18285    cx.global::<SettingsStore>()
18286        .raw_user_settings()
18287        .get("vim_mode")
18288        == Some(&serde_json::Value::Bool(true))
18289}
18290
18291// Consider user intent and default settings
18292fn choose_completion_range(
18293    completion: &Completion,
18294    intent: CompletionIntent,
18295    buffer: &Entity<Buffer>,
18296    cx: &mut Context<Editor>,
18297) -> Range<usize> {
18298    fn should_replace(
18299        completion: &Completion,
18300        insert_range: &Range<text::Anchor>,
18301        intent: CompletionIntent,
18302        completion_mode_setting: LspInsertMode,
18303        buffer: &Buffer,
18304    ) -> bool {
18305        // specific actions take precedence over settings
18306        match intent {
18307            CompletionIntent::CompleteWithInsert => return false,
18308            CompletionIntent::CompleteWithReplace => return true,
18309            CompletionIntent::Complete | CompletionIntent::Compose => {}
18310        }
18311
18312        match completion_mode_setting {
18313            LspInsertMode::Insert => false,
18314            LspInsertMode::Replace => true,
18315            LspInsertMode::ReplaceSubsequence => {
18316                let mut text_to_replace = buffer.chars_for_range(
18317                    buffer.anchor_before(completion.replace_range.start)
18318                        ..buffer.anchor_after(completion.replace_range.end),
18319                );
18320                let mut completion_text = completion.new_text.chars();
18321
18322                // is `text_to_replace` a subsequence of `completion_text`
18323                text_to_replace
18324                    .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18325            }
18326            LspInsertMode::ReplaceSuffix => {
18327                let range_after_cursor = insert_range.end..completion.replace_range.end;
18328
18329                let text_after_cursor = buffer
18330                    .text_for_range(
18331                        buffer.anchor_before(range_after_cursor.start)
18332                            ..buffer.anchor_after(range_after_cursor.end),
18333                    )
18334                    .collect::<String>();
18335                completion.new_text.ends_with(&text_after_cursor)
18336            }
18337        }
18338    }
18339
18340    let buffer = buffer.read(cx);
18341
18342    if let CompletionSource::Lsp {
18343        insert_range: Some(insert_range),
18344        ..
18345    } = &completion.source
18346    {
18347        let completion_mode_setting =
18348            language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18349                .completions
18350                .lsp_insert_mode;
18351
18352        if !should_replace(
18353            completion,
18354            &insert_range,
18355            intent,
18356            completion_mode_setting,
18357            buffer,
18358        ) {
18359            return insert_range.to_offset(buffer);
18360        }
18361    }
18362
18363    completion.replace_range.to_offset(buffer)
18364}
18365
18366fn insert_extra_newline_brackets(
18367    buffer: &MultiBufferSnapshot,
18368    range: Range<usize>,
18369    language: &language::LanguageScope,
18370) -> bool {
18371    let leading_whitespace_len = buffer
18372        .reversed_chars_at(range.start)
18373        .take_while(|c| c.is_whitespace() && *c != '\n')
18374        .map(|c| c.len_utf8())
18375        .sum::<usize>();
18376    let trailing_whitespace_len = buffer
18377        .chars_at(range.end)
18378        .take_while(|c| c.is_whitespace() && *c != '\n')
18379        .map(|c| c.len_utf8())
18380        .sum::<usize>();
18381    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18382
18383    language.brackets().any(|(pair, enabled)| {
18384        let pair_start = pair.start.trim_end();
18385        let pair_end = pair.end.trim_start();
18386
18387        enabled
18388            && pair.newline
18389            && buffer.contains_str_at(range.end, pair_end)
18390            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18391    })
18392}
18393
18394fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18395    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18396        [(buffer, range, _)] => (*buffer, range.clone()),
18397        _ => return false,
18398    };
18399    let pair = {
18400        let mut result: Option<BracketMatch> = None;
18401
18402        for pair in buffer
18403            .all_bracket_ranges(range.clone())
18404            .filter(move |pair| {
18405                pair.open_range.start <= range.start && pair.close_range.end >= range.end
18406            })
18407        {
18408            let len = pair.close_range.end - pair.open_range.start;
18409
18410            if let Some(existing) = &result {
18411                let existing_len = existing.close_range.end - existing.open_range.start;
18412                if len > existing_len {
18413                    continue;
18414                }
18415            }
18416
18417            result = Some(pair);
18418        }
18419
18420        result
18421    };
18422    let Some(pair) = pair else {
18423        return false;
18424    };
18425    pair.newline_only
18426        && buffer
18427            .chars_for_range(pair.open_range.end..range.start)
18428            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18429            .all(|c| c.is_whitespace() && c != '\n')
18430}
18431
18432fn get_uncommitted_diff_for_buffer(
18433    project: &Entity<Project>,
18434    buffers: impl IntoIterator<Item = Entity<Buffer>>,
18435    buffer: Entity<MultiBuffer>,
18436    cx: &mut App,
18437) -> Task<()> {
18438    let mut tasks = Vec::new();
18439    project.update(cx, |project, cx| {
18440        for buffer in buffers {
18441            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18442                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18443            }
18444        }
18445    });
18446    cx.spawn(async move |cx| {
18447        let diffs = future::join_all(tasks).await;
18448        buffer
18449            .update(cx, |buffer, cx| {
18450                for diff in diffs.into_iter().flatten() {
18451                    buffer.add_diff(diff, cx);
18452                }
18453            })
18454            .ok();
18455    })
18456}
18457
18458fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18459    let tab_size = tab_size.get() as usize;
18460    let mut width = offset;
18461
18462    for ch in text.chars() {
18463        width += if ch == '\t' {
18464            tab_size - (width % tab_size)
18465        } else {
18466            1
18467        };
18468    }
18469
18470    width - offset
18471}
18472
18473#[cfg(test)]
18474mod tests {
18475    use super::*;
18476
18477    #[test]
18478    fn test_string_size_with_expanded_tabs() {
18479        let nz = |val| NonZeroU32::new(val).unwrap();
18480        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18481        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18482        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18483        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18484        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18485        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18486        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18487        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18488    }
18489}
18490
18491/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18492struct WordBreakingTokenizer<'a> {
18493    input: &'a str,
18494}
18495
18496impl<'a> WordBreakingTokenizer<'a> {
18497    fn new(input: &'a str) -> Self {
18498        Self { input }
18499    }
18500}
18501
18502fn is_char_ideographic(ch: char) -> bool {
18503    use unicode_script::Script::*;
18504    use unicode_script::UnicodeScript;
18505    matches!(ch.script(), Han | Tangut | Yi)
18506}
18507
18508fn is_grapheme_ideographic(text: &str) -> bool {
18509    text.chars().any(is_char_ideographic)
18510}
18511
18512fn is_grapheme_whitespace(text: &str) -> bool {
18513    text.chars().any(|x| x.is_whitespace())
18514}
18515
18516fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18517    text.chars().next().map_or(false, |ch| {
18518        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18519    })
18520}
18521
18522#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18523enum WordBreakToken<'a> {
18524    Word { token: &'a str, grapheme_len: usize },
18525    InlineWhitespace { token: &'a str, grapheme_len: usize },
18526    Newline,
18527}
18528
18529impl<'a> Iterator for WordBreakingTokenizer<'a> {
18530    /// Yields a span, the count of graphemes in the token, and whether it was
18531    /// whitespace. Note that it also breaks at word boundaries.
18532    type Item = WordBreakToken<'a>;
18533
18534    fn next(&mut self) -> Option<Self::Item> {
18535        use unicode_segmentation::UnicodeSegmentation;
18536        if self.input.is_empty() {
18537            return None;
18538        }
18539
18540        let mut iter = self.input.graphemes(true).peekable();
18541        let mut offset = 0;
18542        let mut grapheme_len = 0;
18543        if let Some(first_grapheme) = iter.next() {
18544            let is_newline = first_grapheme == "\n";
18545            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18546            offset += first_grapheme.len();
18547            grapheme_len += 1;
18548            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18549                if let Some(grapheme) = iter.peek().copied() {
18550                    if should_stay_with_preceding_ideograph(grapheme) {
18551                        offset += grapheme.len();
18552                        grapheme_len += 1;
18553                    }
18554                }
18555            } else {
18556                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18557                let mut next_word_bound = words.peek().copied();
18558                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18559                    next_word_bound = words.next();
18560                }
18561                while let Some(grapheme) = iter.peek().copied() {
18562                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18563                        break;
18564                    };
18565                    if is_grapheme_whitespace(grapheme) != is_whitespace
18566                        || (grapheme == "\n") != is_newline
18567                    {
18568                        break;
18569                    };
18570                    offset += grapheme.len();
18571                    grapheme_len += 1;
18572                    iter.next();
18573                }
18574            }
18575            let token = &self.input[..offset];
18576            self.input = &self.input[offset..];
18577            if token == "\n" {
18578                Some(WordBreakToken::Newline)
18579            } else if is_whitespace {
18580                Some(WordBreakToken::InlineWhitespace {
18581                    token,
18582                    grapheme_len,
18583                })
18584            } else {
18585                Some(WordBreakToken::Word {
18586                    token,
18587                    grapheme_len,
18588                })
18589            }
18590        } else {
18591            None
18592        }
18593    }
18594}
18595
18596#[test]
18597fn test_word_breaking_tokenizer() {
18598    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18599        ("", &[]),
18600        ("  ", &[whitespace("  ", 2)]),
18601        ("Ʒ", &[word("Ʒ", 1)]),
18602        ("Ǽ", &[word("Ǽ", 1)]),
18603        ("", &[word("", 1)]),
18604        ("⋑⋑", &[word("⋑⋑", 2)]),
18605        (
18606            "原理,进而",
18607            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18608        ),
18609        (
18610            "hello world",
18611            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18612        ),
18613        (
18614            "hello, world",
18615            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18616        ),
18617        (
18618            "  hello world",
18619            &[
18620                whitespace("  ", 2),
18621                word("hello", 5),
18622                whitespace(" ", 1),
18623                word("world", 5),
18624            ],
18625        ),
18626        (
18627            "这是什么 \n 钢笔",
18628            &[
18629                word("", 1),
18630                word("", 1),
18631                word("", 1),
18632                word("", 1),
18633                whitespace(" ", 1),
18634                newline(),
18635                whitespace(" ", 1),
18636                word("", 1),
18637                word("", 1),
18638            ],
18639        ),
18640        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18641    ];
18642
18643    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18644        WordBreakToken::Word {
18645            token,
18646            grapheme_len,
18647        }
18648    }
18649
18650    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18651        WordBreakToken::InlineWhitespace {
18652            token,
18653            grapheme_len,
18654        }
18655    }
18656
18657    fn newline() -> WordBreakToken<'static> {
18658        WordBreakToken::Newline
18659    }
18660
18661    for (input, result) in tests {
18662        assert_eq!(
18663            WordBreakingTokenizer::new(input)
18664                .collect::<Vec<_>>()
18665                .as_slice(),
18666            *result,
18667        );
18668    }
18669}
18670
18671fn wrap_with_prefix(
18672    line_prefix: String,
18673    unwrapped_text: String,
18674    wrap_column: usize,
18675    tab_size: NonZeroU32,
18676    preserve_existing_whitespace: bool,
18677) -> String {
18678    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18679    let mut wrapped_text = String::new();
18680    let mut current_line = line_prefix.clone();
18681
18682    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18683    let mut current_line_len = line_prefix_len;
18684    let mut in_whitespace = false;
18685    for token in tokenizer {
18686        let have_preceding_whitespace = in_whitespace;
18687        match token {
18688            WordBreakToken::Word {
18689                token,
18690                grapheme_len,
18691            } => {
18692                in_whitespace = false;
18693                if current_line_len + grapheme_len > wrap_column
18694                    && current_line_len != line_prefix_len
18695                {
18696                    wrapped_text.push_str(current_line.trim_end());
18697                    wrapped_text.push('\n');
18698                    current_line.truncate(line_prefix.len());
18699                    current_line_len = line_prefix_len;
18700                }
18701                current_line.push_str(token);
18702                current_line_len += grapheme_len;
18703            }
18704            WordBreakToken::InlineWhitespace {
18705                mut token,
18706                mut grapheme_len,
18707            } => {
18708                in_whitespace = true;
18709                if have_preceding_whitespace && !preserve_existing_whitespace {
18710                    continue;
18711                }
18712                if !preserve_existing_whitespace {
18713                    token = " ";
18714                    grapheme_len = 1;
18715                }
18716                if current_line_len + grapheme_len > wrap_column {
18717                    wrapped_text.push_str(current_line.trim_end());
18718                    wrapped_text.push('\n');
18719                    current_line.truncate(line_prefix.len());
18720                    current_line_len = line_prefix_len;
18721                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18722                    current_line.push_str(token);
18723                    current_line_len += grapheme_len;
18724                }
18725            }
18726            WordBreakToken::Newline => {
18727                in_whitespace = true;
18728                if preserve_existing_whitespace {
18729                    wrapped_text.push_str(current_line.trim_end());
18730                    wrapped_text.push('\n');
18731                    current_line.truncate(line_prefix.len());
18732                    current_line_len = line_prefix_len;
18733                } else if have_preceding_whitespace {
18734                    continue;
18735                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18736                {
18737                    wrapped_text.push_str(current_line.trim_end());
18738                    wrapped_text.push('\n');
18739                    current_line.truncate(line_prefix.len());
18740                    current_line_len = line_prefix_len;
18741                } else if current_line_len != line_prefix_len {
18742                    current_line.push(' ');
18743                    current_line_len += 1;
18744                }
18745            }
18746        }
18747    }
18748
18749    if !current_line.is_empty() {
18750        wrapped_text.push_str(&current_line);
18751    }
18752    wrapped_text
18753}
18754
18755#[test]
18756fn test_wrap_with_prefix() {
18757    assert_eq!(
18758        wrap_with_prefix(
18759            "# ".to_string(),
18760            "abcdefg".to_string(),
18761            4,
18762            NonZeroU32::new(4).unwrap(),
18763            false,
18764        ),
18765        "# abcdefg"
18766    );
18767    assert_eq!(
18768        wrap_with_prefix(
18769            "".to_string(),
18770            "\thello world".to_string(),
18771            8,
18772            NonZeroU32::new(4).unwrap(),
18773            false,
18774        ),
18775        "hello\nworld"
18776    );
18777    assert_eq!(
18778        wrap_with_prefix(
18779            "// ".to_string(),
18780            "xx \nyy zz aa bb cc".to_string(),
18781            12,
18782            NonZeroU32::new(4).unwrap(),
18783            false,
18784        ),
18785        "// xx yy zz\n// aa bb cc"
18786    );
18787    assert_eq!(
18788        wrap_with_prefix(
18789            String::new(),
18790            "这是什么 \n 钢笔".to_string(),
18791            3,
18792            NonZeroU32::new(4).unwrap(),
18793            false,
18794        ),
18795        "这是什\n么 钢\n"
18796    );
18797}
18798
18799pub trait CollaborationHub {
18800    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18801    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18802    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18803}
18804
18805impl CollaborationHub for Entity<Project> {
18806    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18807        self.read(cx).collaborators()
18808    }
18809
18810    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18811        self.read(cx).user_store().read(cx).participant_indices()
18812    }
18813
18814    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18815        let this = self.read(cx);
18816        let user_ids = this.collaborators().values().map(|c| c.user_id);
18817        this.user_store().read_with(cx, |user_store, cx| {
18818            user_store.participant_names(user_ids, cx)
18819        })
18820    }
18821}
18822
18823pub trait SemanticsProvider {
18824    fn hover(
18825        &self,
18826        buffer: &Entity<Buffer>,
18827        position: text::Anchor,
18828        cx: &mut App,
18829    ) -> Option<Task<Vec<project::Hover>>>;
18830
18831    fn inlay_hints(
18832        &self,
18833        buffer_handle: Entity<Buffer>,
18834        range: Range<text::Anchor>,
18835        cx: &mut App,
18836    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18837
18838    fn resolve_inlay_hint(
18839        &self,
18840        hint: InlayHint,
18841        buffer_handle: Entity<Buffer>,
18842        server_id: LanguageServerId,
18843        cx: &mut App,
18844    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18845
18846    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18847
18848    fn document_highlights(
18849        &self,
18850        buffer: &Entity<Buffer>,
18851        position: text::Anchor,
18852        cx: &mut App,
18853    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18854
18855    fn definitions(
18856        &self,
18857        buffer: &Entity<Buffer>,
18858        position: text::Anchor,
18859        kind: GotoDefinitionKind,
18860        cx: &mut App,
18861    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18862
18863    fn range_for_rename(
18864        &self,
18865        buffer: &Entity<Buffer>,
18866        position: text::Anchor,
18867        cx: &mut App,
18868    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18869
18870    fn perform_rename(
18871        &self,
18872        buffer: &Entity<Buffer>,
18873        position: text::Anchor,
18874        new_name: String,
18875        cx: &mut App,
18876    ) -> Option<Task<Result<ProjectTransaction>>>;
18877}
18878
18879pub trait CompletionProvider {
18880    fn completions(
18881        &self,
18882        excerpt_id: ExcerptId,
18883        buffer: &Entity<Buffer>,
18884        buffer_position: text::Anchor,
18885        trigger: CompletionContext,
18886        window: &mut Window,
18887        cx: &mut Context<Editor>,
18888    ) -> Task<Result<Option<Vec<Completion>>>>;
18889
18890    fn resolve_completions(
18891        &self,
18892        buffer: Entity<Buffer>,
18893        completion_indices: Vec<usize>,
18894        completions: Rc<RefCell<Box<[Completion]>>>,
18895        cx: &mut Context<Editor>,
18896    ) -> Task<Result<bool>>;
18897
18898    fn apply_additional_edits_for_completion(
18899        &self,
18900        _buffer: Entity<Buffer>,
18901        _completions: Rc<RefCell<Box<[Completion]>>>,
18902        _completion_index: usize,
18903        _push_to_history: bool,
18904        _cx: &mut Context<Editor>,
18905    ) -> Task<Result<Option<language::Transaction>>> {
18906        Task::ready(Ok(None))
18907    }
18908
18909    fn is_completion_trigger(
18910        &self,
18911        buffer: &Entity<Buffer>,
18912        position: language::Anchor,
18913        text: &str,
18914        trigger_in_words: bool,
18915        cx: &mut Context<Editor>,
18916    ) -> bool;
18917
18918    fn sort_completions(&self) -> bool {
18919        true
18920    }
18921
18922    fn filter_completions(&self) -> bool {
18923        true
18924    }
18925}
18926
18927pub trait CodeActionProvider {
18928    fn id(&self) -> Arc<str>;
18929
18930    fn code_actions(
18931        &self,
18932        buffer: &Entity<Buffer>,
18933        range: Range<text::Anchor>,
18934        window: &mut Window,
18935        cx: &mut App,
18936    ) -> Task<Result<Vec<CodeAction>>>;
18937
18938    fn apply_code_action(
18939        &self,
18940        buffer_handle: Entity<Buffer>,
18941        action: CodeAction,
18942        excerpt_id: ExcerptId,
18943        push_to_history: bool,
18944        window: &mut Window,
18945        cx: &mut App,
18946    ) -> Task<Result<ProjectTransaction>>;
18947}
18948
18949impl CodeActionProvider for Entity<Project> {
18950    fn id(&self) -> Arc<str> {
18951        "project".into()
18952    }
18953
18954    fn code_actions(
18955        &self,
18956        buffer: &Entity<Buffer>,
18957        range: Range<text::Anchor>,
18958        _window: &mut Window,
18959        cx: &mut App,
18960    ) -> Task<Result<Vec<CodeAction>>> {
18961        self.update(cx, |project, cx| {
18962            let code_lens = project.code_lens(buffer, range.clone(), cx);
18963            let code_actions = project.code_actions(buffer, range, None, cx);
18964            cx.background_spawn(async move {
18965                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18966                Ok(code_lens
18967                    .context("code lens fetch")?
18968                    .into_iter()
18969                    .chain(code_actions.context("code action fetch")?)
18970                    .collect())
18971            })
18972        })
18973    }
18974
18975    fn apply_code_action(
18976        &self,
18977        buffer_handle: Entity<Buffer>,
18978        action: CodeAction,
18979        _excerpt_id: ExcerptId,
18980        push_to_history: bool,
18981        _window: &mut Window,
18982        cx: &mut App,
18983    ) -> Task<Result<ProjectTransaction>> {
18984        self.update(cx, |project, cx| {
18985            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18986        })
18987    }
18988}
18989
18990fn snippet_completions(
18991    project: &Project,
18992    buffer: &Entity<Buffer>,
18993    buffer_position: text::Anchor,
18994    cx: &mut App,
18995) -> Task<Result<Vec<Completion>>> {
18996    let languages = buffer.read(cx).languages_at(buffer_position);
18997    let snippet_store = project.snippets().read(cx);
18998
18999    let scopes: Vec<_> = languages
19000        .iter()
19001        .filter_map(|language| {
19002            let language_name = language.lsp_id();
19003            let snippets = snippet_store.snippets_for(Some(language_name), cx);
19004
19005            if snippets.is_empty() {
19006                None
19007            } else {
19008                Some((language.default_scope(), snippets))
19009            }
19010        })
19011        .collect();
19012
19013    if scopes.is_empty() {
19014        return Task::ready(Ok(vec![]));
19015    }
19016
19017    let snapshot = buffer.read(cx).text_snapshot();
19018    let chars: String = snapshot
19019        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19020        .collect();
19021    let executor = cx.background_executor().clone();
19022
19023    cx.background_spawn(async move {
19024        let mut all_results: Vec<Completion> = Vec::new();
19025        for (scope, snippets) in scopes.into_iter() {
19026            let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19027            let mut last_word = chars
19028                .chars()
19029                .take_while(|c| classifier.is_word(*c))
19030                .collect::<String>();
19031            last_word = last_word.chars().rev().collect();
19032
19033            if last_word.is_empty() {
19034                return Ok(vec![]);
19035            }
19036
19037            let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19038            let to_lsp = |point: &text::Anchor| {
19039                let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19040                point_to_lsp(end)
19041            };
19042            let lsp_end = to_lsp(&buffer_position);
19043
19044            let candidates = snippets
19045                .iter()
19046                .enumerate()
19047                .flat_map(|(ix, snippet)| {
19048                    snippet
19049                        .prefix
19050                        .iter()
19051                        .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19052                })
19053                .collect::<Vec<StringMatchCandidate>>();
19054
19055            let mut matches = fuzzy::match_strings(
19056                &candidates,
19057                &last_word,
19058                last_word.chars().any(|c| c.is_uppercase()),
19059                100,
19060                &Default::default(),
19061                executor.clone(),
19062            )
19063            .await;
19064
19065            // Remove all candidates where the query's start does not match the start of any word in the candidate
19066            if let Some(query_start) = last_word.chars().next() {
19067                matches.retain(|string_match| {
19068                    split_words(&string_match.string).any(|word| {
19069                        // Check that the first codepoint of the word as lowercase matches the first
19070                        // codepoint of the query as lowercase
19071                        word.chars()
19072                            .flat_map(|codepoint| codepoint.to_lowercase())
19073                            .zip(query_start.to_lowercase())
19074                            .all(|(word_cp, query_cp)| word_cp == query_cp)
19075                    })
19076                });
19077            }
19078
19079            let matched_strings = matches
19080                .into_iter()
19081                .map(|m| m.string)
19082                .collect::<HashSet<_>>();
19083
19084            let mut result: Vec<Completion> = snippets
19085                .iter()
19086                .filter_map(|snippet| {
19087                    let matching_prefix = snippet
19088                        .prefix
19089                        .iter()
19090                        .find(|prefix| matched_strings.contains(*prefix))?;
19091                    let start = as_offset - last_word.len();
19092                    let start = snapshot.anchor_before(start);
19093                    let range = start..buffer_position;
19094                    let lsp_start = to_lsp(&start);
19095                    let lsp_range = lsp::Range {
19096                        start: lsp_start,
19097                        end: lsp_end,
19098                    };
19099                    Some(Completion {
19100                        replace_range: range,
19101                        new_text: snippet.body.clone(),
19102                        source: CompletionSource::Lsp {
19103                            insert_range: None,
19104                            server_id: LanguageServerId(usize::MAX),
19105                            resolved: true,
19106                            lsp_completion: Box::new(lsp::CompletionItem {
19107                                label: snippet.prefix.first().unwrap().clone(),
19108                                kind: Some(CompletionItemKind::SNIPPET),
19109                                label_details: snippet.description.as_ref().map(|description| {
19110                                    lsp::CompletionItemLabelDetails {
19111                                        detail: Some(description.clone()),
19112                                        description: None,
19113                                    }
19114                                }),
19115                                insert_text_format: Some(InsertTextFormat::SNIPPET),
19116                                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19117                                    lsp::InsertReplaceEdit {
19118                                        new_text: snippet.body.clone(),
19119                                        insert: lsp_range,
19120                                        replace: lsp_range,
19121                                    },
19122                                )),
19123                                filter_text: Some(snippet.body.clone()),
19124                                sort_text: Some(char::MAX.to_string()),
19125                                ..lsp::CompletionItem::default()
19126                            }),
19127                            lsp_defaults: None,
19128                        },
19129                        label: CodeLabel {
19130                            text: matching_prefix.clone(),
19131                            runs: Vec::new(),
19132                            filter_range: 0..matching_prefix.len(),
19133                        },
19134                        icon_path: None,
19135                        documentation: snippet.description.clone().map(|description| {
19136                            CompletionDocumentation::SingleLine(description.into())
19137                        }),
19138                        insert_text_mode: None,
19139                        confirm: None,
19140                    })
19141                })
19142                .collect();
19143
19144            all_results.append(&mut result);
19145        }
19146
19147        Ok(all_results)
19148    })
19149}
19150
19151impl CompletionProvider for Entity<Project> {
19152    fn completions(
19153        &self,
19154        _excerpt_id: ExcerptId,
19155        buffer: &Entity<Buffer>,
19156        buffer_position: text::Anchor,
19157        options: CompletionContext,
19158        _window: &mut Window,
19159        cx: &mut Context<Editor>,
19160    ) -> Task<Result<Option<Vec<Completion>>>> {
19161        self.update(cx, |project, cx| {
19162            let snippets = snippet_completions(project, buffer, buffer_position, cx);
19163            let project_completions = project.completions(buffer, buffer_position, options, cx);
19164            cx.background_spawn(async move {
19165                let snippets_completions = snippets.await?;
19166                match project_completions.await? {
19167                    Some(mut completions) => {
19168                        completions.extend(snippets_completions);
19169                        Ok(Some(completions))
19170                    }
19171                    None => {
19172                        if snippets_completions.is_empty() {
19173                            Ok(None)
19174                        } else {
19175                            Ok(Some(snippets_completions))
19176                        }
19177                    }
19178                }
19179            })
19180        })
19181    }
19182
19183    fn resolve_completions(
19184        &self,
19185        buffer: Entity<Buffer>,
19186        completion_indices: Vec<usize>,
19187        completions: Rc<RefCell<Box<[Completion]>>>,
19188        cx: &mut Context<Editor>,
19189    ) -> Task<Result<bool>> {
19190        self.update(cx, |project, cx| {
19191            project.lsp_store().update(cx, |lsp_store, cx| {
19192                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19193            })
19194        })
19195    }
19196
19197    fn apply_additional_edits_for_completion(
19198        &self,
19199        buffer: Entity<Buffer>,
19200        completions: Rc<RefCell<Box<[Completion]>>>,
19201        completion_index: usize,
19202        push_to_history: bool,
19203        cx: &mut Context<Editor>,
19204    ) -> Task<Result<Option<language::Transaction>>> {
19205        self.update(cx, |project, cx| {
19206            project.lsp_store().update(cx, |lsp_store, cx| {
19207                lsp_store.apply_additional_edits_for_completion(
19208                    buffer,
19209                    completions,
19210                    completion_index,
19211                    push_to_history,
19212                    cx,
19213                )
19214            })
19215        })
19216    }
19217
19218    fn is_completion_trigger(
19219        &self,
19220        buffer: &Entity<Buffer>,
19221        position: language::Anchor,
19222        text: &str,
19223        trigger_in_words: bool,
19224        cx: &mut Context<Editor>,
19225    ) -> bool {
19226        let mut chars = text.chars();
19227        let char = if let Some(char) = chars.next() {
19228            char
19229        } else {
19230            return false;
19231        };
19232        if chars.next().is_some() {
19233            return false;
19234        }
19235
19236        let buffer = buffer.read(cx);
19237        let snapshot = buffer.snapshot();
19238        if !snapshot.settings_at(position, cx).show_completions_on_input {
19239            return false;
19240        }
19241        let classifier = snapshot.char_classifier_at(position).for_completion(true);
19242        if trigger_in_words && classifier.is_word(char) {
19243            return true;
19244        }
19245
19246        buffer.completion_triggers().contains(text)
19247    }
19248}
19249
19250impl SemanticsProvider for Entity<Project> {
19251    fn hover(
19252        &self,
19253        buffer: &Entity<Buffer>,
19254        position: text::Anchor,
19255        cx: &mut App,
19256    ) -> Option<Task<Vec<project::Hover>>> {
19257        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19258    }
19259
19260    fn document_highlights(
19261        &self,
19262        buffer: &Entity<Buffer>,
19263        position: text::Anchor,
19264        cx: &mut App,
19265    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19266        Some(self.update(cx, |project, cx| {
19267            project.document_highlights(buffer, position, cx)
19268        }))
19269    }
19270
19271    fn definitions(
19272        &self,
19273        buffer: &Entity<Buffer>,
19274        position: text::Anchor,
19275        kind: GotoDefinitionKind,
19276        cx: &mut App,
19277    ) -> Option<Task<Result<Vec<LocationLink>>>> {
19278        Some(self.update(cx, |project, cx| match kind {
19279            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19280            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19281            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19282            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19283        }))
19284    }
19285
19286    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19287        // TODO: make this work for remote projects
19288        self.update(cx, |this, cx| {
19289            buffer.update(cx, |buffer, cx| {
19290                this.any_language_server_supports_inlay_hints(buffer, cx)
19291            })
19292        })
19293    }
19294
19295    fn inlay_hints(
19296        &self,
19297        buffer_handle: Entity<Buffer>,
19298        range: Range<text::Anchor>,
19299        cx: &mut App,
19300    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19301        Some(self.update(cx, |project, cx| {
19302            project.inlay_hints(buffer_handle, range, cx)
19303        }))
19304    }
19305
19306    fn resolve_inlay_hint(
19307        &self,
19308        hint: InlayHint,
19309        buffer_handle: Entity<Buffer>,
19310        server_id: LanguageServerId,
19311        cx: &mut App,
19312    ) -> Option<Task<anyhow::Result<InlayHint>>> {
19313        Some(self.update(cx, |project, cx| {
19314            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19315        }))
19316    }
19317
19318    fn range_for_rename(
19319        &self,
19320        buffer: &Entity<Buffer>,
19321        position: text::Anchor,
19322        cx: &mut App,
19323    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19324        Some(self.update(cx, |project, cx| {
19325            let buffer = buffer.clone();
19326            let task = project.prepare_rename(buffer.clone(), position, cx);
19327            cx.spawn(async move |_, cx| {
19328                Ok(match task.await? {
19329                    PrepareRenameResponse::Success(range) => Some(range),
19330                    PrepareRenameResponse::InvalidPosition => None,
19331                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19332                        // Fallback on using TreeSitter info to determine identifier range
19333                        buffer.update(cx, |buffer, _| {
19334                            let snapshot = buffer.snapshot();
19335                            let (range, kind) = snapshot.surrounding_word(position);
19336                            if kind != Some(CharKind::Word) {
19337                                return None;
19338                            }
19339                            Some(
19340                                snapshot.anchor_before(range.start)
19341                                    ..snapshot.anchor_after(range.end),
19342                            )
19343                        })?
19344                    }
19345                })
19346            })
19347        }))
19348    }
19349
19350    fn perform_rename(
19351        &self,
19352        buffer: &Entity<Buffer>,
19353        position: text::Anchor,
19354        new_name: String,
19355        cx: &mut App,
19356    ) -> Option<Task<Result<ProjectTransaction>>> {
19357        Some(self.update(cx, |project, cx| {
19358            project.perform_rename(buffer.clone(), position, new_name, cx)
19359        }))
19360    }
19361}
19362
19363fn inlay_hint_settings(
19364    location: Anchor,
19365    snapshot: &MultiBufferSnapshot,
19366    cx: &mut Context<Editor>,
19367) -> InlayHintSettings {
19368    let file = snapshot.file_at(location);
19369    let language = snapshot.language_at(location).map(|l| l.name());
19370    language_settings(language, file, cx).inlay_hints
19371}
19372
19373fn consume_contiguous_rows(
19374    contiguous_row_selections: &mut Vec<Selection<Point>>,
19375    selection: &Selection<Point>,
19376    display_map: &DisplaySnapshot,
19377    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19378) -> (MultiBufferRow, MultiBufferRow) {
19379    contiguous_row_selections.push(selection.clone());
19380    let start_row = MultiBufferRow(selection.start.row);
19381    let mut end_row = ending_row(selection, display_map);
19382
19383    while let Some(next_selection) = selections.peek() {
19384        if next_selection.start.row <= end_row.0 {
19385            end_row = ending_row(next_selection, display_map);
19386            contiguous_row_selections.push(selections.next().unwrap().clone());
19387        } else {
19388            break;
19389        }
19390    }
19391    (start_row, end_row)
19392}
19393
19394fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19395    if next_selection.end.column > 0 || next_selection.is_empty() {
19396        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19397    } else {
19398        MultiBufferRow(next_selection.end.row)
19399    }
19400}
19401
19402impl EditorSnapshot {
19403    pub fn remote_selections_in_range<'a>(
19404        &'a self,
19405        range: &'a Range<Anchor>,
19406        collaboration_hub: &dyn CollaborationHub,
19407        cx: &'a App,
19408    ) -> impl 'a + Iterator<Item = RemoteSelection> {
19409        let participant_names = collaboration_hub.user_names(cx);
19410        let participant_indices = collaboration_hub.user_participant_indices(cx);
19411        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19412        let collaborators_by_replica_id = collaborators_by_peer_id
19413            .iter()
19414            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19415            .collect::<HashMap<_, _>>();
19416        self.buffer_snapshot
19417            .selections_in_range(range, false)
19418            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19419                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19420                let participant_index = participant_indices.get(&collaborator.user_id).copied();
19421                let user_name = participant_names.get(&collaborator.user_id).cloned();
19422                Some(RemoteSelection {
19423                    replica_id,
19424                    selection,
19425                    cursor_shape,
19426                    line_mode,
19427                    participant_index,
19428                    peer_id: collaborator.peer_id,
19429                    user_name,
19430                })
19431            })
19432    }
19433
19434    pub fn hunks_for_ranges(
19435        &self,
19436        ranges: impl IntoIterator<Item = Range<Point>>,
19437    ) -> Vec<MultiBufferDiffHunk> {
19438        let mut hunks = Vec::new();
19439        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19440            HashMap::default();
19441        for query_range in ranges {
19442            let query_rows =
19443                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19444            for hunk in self.buffer_snapshot.diff_hunks_in_range(
19445                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19446            ) {
19447                // Include deleted hunks that are adjacent to the query range, because
19448                // otherwise they would be missed.
19449                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19450                if hunk.status().is_deleted() {
19451                    intersects_range |= hunk.row_range.start == query_rows.end;
19452                    intersects_range |= hunk.row_range.end == query_rows.start;
19453                }
19454                if intersects_range {
19455                    if !processed_buffer_rows
19456                        .entry(hunk.buffer_id)
19457                        .or_default()
19458                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19459                    {
19460                        continue;
19461                    }
19462                    hunks.push(hunk);
19463                }
19464            }
19465        }
19466
19467        hunks
19468    }
19469
19470    fn display_diff_hunks_for_rows<'a>(
19471        &'a self,
19472        display_rows: Range<DisplayRow>,
19473        folded_buffers: &'a HashSet<BufferId>,
19474    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19475        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19476        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19477
19478        self.buffer_snapshot
19479            .diff_hunks_in_range(buffer_start..buffer_end)
19480            .filter_map(|hunk| {
19481                if folded_buffers.contains(&hunk.buffer_id) {
19482                    return None;
19483                }
19484
19485                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19486                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19487
19488                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19489                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19490
19491                let display_hunk = if hunk_display_start.column() != 0 {
19492                    DisplayDiffHunk::Folded {
19493                        display_row: hunk_display_start.row(),
19494                    }
19495                } else {
19496                    let mut end_row = hunk_display_end.row();
19497                    if hunk_display_end.column() > 0 {
19498                        end_row.0 += 1;
19499                    }
19500                    let is_created_file = hunk.is_created_file();
19501                    DisplayDiffHunk::Unfolded {
19502                        status: hunk.status(),
19503                        diff_base_byte_range: hunk.diff_base_byte_range,
19504                        display_row_range: hunk_display_start.row()..end_row,
19505                        multi_buffer_range: Anchor::range_in_buffer(
19506                            hunk.excerpt_id,
19507                            hunk.buffer_id,
19508                            hunk.buffer_range,
19509                        ),
19510                        is_created_file,
19511                    }
19512                };
19513
19514                Some(display_hunk)
19515            })
19516    }
19517
19518    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19519        self.display_snapshot.buffer_snapshot.language_at(position)
19520    }
19521
19522    pub fn is_focused(&self) -> bool {
19523        self.is_focused
19524    }
19525
19526    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19527        self.placeholder_text.as_ref()
19528    }
19529
19530    pub fn scroll_position(&self) -> gpui::Point<f32> {
19531        self.scroll_anchor.scroll_position(&self.display_snapshot)
19532    }
19533
19534    fn gutter_dimensions(
19535        &self,
19536        font_id: FontId,
19537        font_size: Pixels,
19538        max_line_number_width: Pixels,
19539        cx: &App,
19540    ) -> Option<GutterDimensions> {
19541        if !self.show_gutter {
19542            return None;
19543        }
19544
19545        let descent = cx.text_system().descent(font_id, font_size);
19546        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19547        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19548
19549        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19550            matches!(
19551                ProjectSettings::get_global(cx).git.git_gutter,
19552                Some(GitGutterSetting::TrackedFiles)
19553            )
19554        });
19555        let gutter_settings = EditorSettings::get_global(cx).gutter;
19556        let show_line_numbers = self
19557            .show_line_numbers
19558            .unwrap_or(gutter_settings.line_numbers);
19559        let line_gutter_width = if show_line_numbers {
19560            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19561            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19562            max_line_number_width.max(min_width_for_number_on_gutter)
19563        } else {
19564            0.0.into()
19565        };
19566
19567        let show_code_actions = self
19568            .show_code_actions
19569            .unwrap_or(gutter_settings.code_actions);
19570
19571        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19572        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19573
19574        let git_blame_entries_width =
19575            self.git_blame_gutter_max_author_length
19576                .map(|max_author_length| {
19577                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19578                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19579
19580                    /// The number of characters to dedicate to gaps and margins.
19581                    const SPACING_WIDTH: usize = 4;
19582
19583                    let max_char_count = max_author_length.min(renderer.max_author_length())
19584                        + ::git::SHORT_SHA_LENGTH
19585                        + MAX_RELATIVE_TIMESTAMP.len()
19586                        + SPACING_WIDTH;
19587
19588                    em_advance * max_char_count
19589                });
19590
19591        let is_singleton = self.buffer_snapshot.is_singleton();
19592
19593        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19594        left_padding += if !is_singleton {
19595            em_width * 4.0
19596        } else if show_code_actions || show_runnables || show_breakpoints {
19597            em_width * 3.0
19598        } else if show_git_gutter && show_line_numbers {
19599            em_width * 2.0
19600        } else if show_git_gutter || show_line_numbers {
19601            em_width
19602        } else {
19603            px(0.)
19604        };
19605
19606        let shows_folds = is_singleton && gutter_settings.folds;
19607
19608        let right_padding = if shows_folds && show_line_numbers {
19609            em_width * 4.0
19610        } else if shows_folds || (!is_singleton && show_line_numbers) {
19611            em_width * 3.0
19612        } else if show_line_numbers {
19613            em_width
19614        } else {
19615            px(0.)
19616        };
19617
19618        Some(GutterDimensions {
19619            left_padding,
19620            right_padding,
19621            width: line_gutter_width + left_padding + right_padding,
19622            margin: -descent,
19623            git_blame_entries_width,
19624        })
19625    }
19626
19627    pub fn render_crease_toggle(
19628        &self,
19629        buffer_row: MultiBufferRow,
19630        row_contains_cursor: bool,
19631        editor: Entity<Editor>,
19632        window: &mut Window,
19633        cx: &mut App,
19634    ) -> Option<AnyElement> {
19635        let folded = self.is_line_folded(buffer_row);
19636        let mut is_foldable = false;
19637
19638        if let Some(crease) = self
19639            .crease_snapshot
19640            .query_row(buffer_row, &self.buffer_snapshot)
19641        {
19642            is_foldable = true;
19643            match crease {
19644                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19645                    if let Some(render_toggle) = render_toggle {
19646                        let toggle_callback =
19647                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19648                                if folded {
19649                                    editor.update(cx, |editor, cx| {
19650                                        editor.fold_at(buffer_row, window, cx)
19651                                    });
19652                                } else {
19653                                    editor.update(cx, |editor, cx| {
19654                                        editor.unfold_at(buffer_row, window, cx)
19655                                    });
19656                                }
19657                            });
19658                        return Some((render_toggle)(
19659                            buffer_row,
19660                            folded,
19661                            toggle_callback,
19662                            window,
19663                            cx,
19664                        ));
19665                    }
19666                }
19667            }
19668        }
19669
19670        is_foldable |= self.starts_indent(buffer_row);
19671
19672        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19673            Some(
19674                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19675                    .toggle_state(folded)
19676                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19677                        if folded {
19678                            this.unfold_at(buffer_row, window, cx);
19679                        } else {
19680                            this.fold_at(buffer_row, window, cx);
19681                        }
19682                    }))
19683                    .into_any_element(),
19684            )
19685        } else {
19686            None
19687        }
19688    }
19689
19690    pub fn render_crease_trailer(
19691        &self,
19692        buffer_row: MultiBufferRow,
19693        window: &mut Window,
19694        cx: &mut App,
19695    ) -> Option<AnyElement> {
19696        let folded = self.is_line_folded(buffer_row);
19697        if let Crease::Inline { render_trailer, .. } = self
19698            .crease_snapshot
19699            .query_row(buffer_row, &self.buffer_snapshot)?
19700        {
19701            let render_trailer = render_trailer.as_ref()?;
19702            Some(render_trailer(buffer_row, folded, window, cx))
19703        } else {
19704            None
19705        }
19706    }
19707}
19708
19709impl Deref for EditorSnapshot {
19710    type Target = DisplaySnapshot;
19711
19712    fn deref(&self) -> &Self::Target {
19713        &self.display_snapshot
19714    }
19715}
19716
19717#[derive(Clone, Debug, PartialEq, Eq)]
19718pub enum EditorEvent {
19719    InputIgnored {
19720        text: Arc<str>,
19721    },
19722    InputHandled {
19723        utf16_range_to_replace: Option<Range<isize>>,
19724        text: Arc<str>,
19725    },
19726    ExcerptsAdded {
19727        buffer: Entity<Buffer>,
19728        predecessor: ExcerptId,
19729        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19730    },
19731    ExcerptsRemoved {
19732        ids: Vec<ExcerptId>,
19733    },
19734    BufferFoldToggled {
19735        ids: Vec<ExcerptId>,
19736        folded: bool,
19737    },
19738    ExcerptsEdited {
19739        ids: Vec<ExcerptId>,
19740    },
19741    ExcerptsExpanded {
19742        ids: Vec<ExcerptId>,
19743    },
19744    BufferEdited,
19745    Edited {
19746        transaction_id: clock::Lamport,
19747    },
19748    Reparsed(BufferId),
19749    Focused,
19750    FocusedIn,
19751    Blurred,
19752    DirtyChanged,
19753    Saved,
19754    TitleChanged,
19755    DiffBaseChanged,
19756    SelectionsChanged {
19757        local: bool,
19758    },
19759    ScrollPositionChanged {
19760        local: bool,
19761        autoscroll: bool,
19762    },
19763    Closed,
19764    TransactionUndone {
19765        transaction_id: clock::Lamport,
19766    },
19767    TransactionBegun {
19768        transaction_id: clock::Lamport,
19769    },
19770    Reloaded,
19771    CursorShapeChanged,
19772    PushedToNavHistory {
19773        anchor: Anchor,
19774        is_deactivate: bool,
19775    },
19776}
19777
19778impl EventEmitter<EditorEvent> for Editor {}
19779
19780impl Focusable for Editor {
19781    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19782        self.focus_handle.clone()
19783    }
19784}
19785
19786impl Render for Editor {
19787    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19788        let settings = ThemeSettings::get_global(cx);
19789
19790        let mut text_style = match self.mode {
19791            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19792                color: cx.theme().colors().editor_foreground,
19793                font_family: settings.ui_font.family.clone(),
19794                font_features: settings.ui_font.features.clone(),
19795                font_fallbacks: settings.ui_font.fallbacks.clone(),
19796                font_size: rems(0.875).into(),
19797                font_weight: settings.ui_font.weight,
19798                line_height: relative(settings.buffer_line_height.value()),
19799                ..Default::default()
19800            },
19801            EditorMode::Full { .. } => TextStyle {
19802                color: cx.theme().colors().editor_foreground,
19803                font_family: settings.buffer_font.family.clone(),
19804                font_features: settings.buffer_font.features.clone(),
19805                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19806                font_size: settings.buffer_font_size(cx).into(),
19807                font_weight: settings.buffer_font.weight,
19808                line_height: relative(settings.buffer_line_height.value()),
19809                ..Default::default()
19810            },
19811        };
19812        if let Some(text_style_refinement) = &self.text_style_refinement {
19813            text_style.refine(text_style_refinement)
19814        }
19815
19816        let background = match self.mode {
19817            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19818            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19819            EditorMode::Full { .. } => cx.theme().colors().editor_background,
19820        };
19821
19822        EditorElement::new(
19823            &cx.entity(),
19824            EditorStyle {
19825                background,
19826                local_player: cx.theme().players().local(),
19827                text: text_style,
19828                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19829                syntax: cx.theme().syntax().clone(),
19830                status: cx.theme().status().clone(),
19831                inlay_hints_style: make_inlay_hints_style(cx),
19832                inline_completion_styles: make_suggestion_styles(cx),
19833                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19834            },
19835        )
19836    }
19837}
19838
19839impl EntityInputHandler for Editor {
19840    fn text_for_range(
19841        &mut self,
19842        range_utf16: Range<usize>,
19843        adjusted_range: &mut Option<Range<usize>>,
19844        _: &mut Window,
19845        cx: &mut Context<Self>,
19846    ) -> Option<String> {
19847        let snapshot = self.buffer.read(cx).read(cx);
19848        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19849        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19850        if (start.0..end.0) != range_utf16 {
19851            adjusted_range.replace(start.0..end.0);
19852        }
19853        Some(snapshot.text_for_range(start..end).collect())
19854    }
19855
19856    fn selected_text_range(
19857        &mut self,
19858        ignore_disabled_input: bool,
19859        _: &mut Window,
19860        cx: &mut Context<Self>,
19861    ) -> Option<UTF16Selection> {
19862        // Prevent the IME menu from appearing when holding down an alphabetic key
19863        // while input is disabled.
19864        if !ignore_disabled_input && !self.input_enabled {
19865            return None;
19866        }
19867
19868        let selection = self.selections.newest::<OffsetUtf16>(cx);
19869        let range = selection.range();
19870
19871        Some(UTF16Selection {
19872            range: range.start.0..range.end.0,
19873            reversed: selection.reversed,
19874        })
19875    }
19876
19877    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19878        let snapshot = self.buffer.read(cx).read(cx);
19879        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19880        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19881    }
19882
19883    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19884        self.clear_highlights::<InputComposition>(cx);
19885        self.ime_transaction.take();
19886    }
19887
19888    fn replace_text_in_range(
19889        &mut self,
19890        range_utf16: Option<Range<usize>>,
19891        text: &str,
19892        window: &mut Window,
19893        cx: &mut Context<Self>,
19894    ) {
19895        if !self.input_enabled {
19896            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19897            return;
19898        }
19899
19900        self.transact(window, cx, |this, window, cx| {
19901            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19902                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19903                Some(this.selection_replacement_ranges(range_utf16, cx))
19904            } else {
19905                this.marked_text_ranges(cx)
19906            };
19907
19908            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19909                let newest_selection_id = this.selections.newest_anchor().id;
19910                this.selections
19911                    .all::<OffsetUtf16>(cx)
19912                    .iter()
19913                    .zip(ranges_to_replace.iter())
19914                    .find_map(|(selection, range)| {
19915                        if selection.id == newest_selection_id {
19916                            Some(
19917                                (range.start.0 as isize - selection.head().0 as isize)
19918                                    ..(range.end.0 as isize - selection.head().0 as isize),
19919                            )
19920                        } else {
19921                            None
19922                        }
19923                    })
19924            });
19925
19926            cx.emit(EditorEvent::InputHandled {
19927                utf16_range_to_replace: range_to_replace,
19928                text: text.into(),
19929            });
19930
19931            if let Some(new_selected_ranges) = new_selected_ranges {
19932                this.change_selections(None, window, cx, |selections| {
19933                    selections.select_ranges(new_selected_ranges)
19934                });
19935                this.backspace(&Default::default(), window, cx);
19936            }
19937
19938            this.handle_input(text, window, cx);
19939        });
19940
19941        if let Some(transaction) = self.ime_transaction {
19942            self.buffer.update(cx, |buffer, cx| {
19943                buffer.group_until_transaction(transaction, cx);
19944            });
19945        }
19946
19947        self.unmark_text(window, cx);
19948    }
19949
19950    fn replace_and_mark_text_in_range(
19951        &mut self,
19952        range_utf16: Option<Range<usize>>,
19953        text: &str,
19954        new_selected_range_utf16: Option<Range<usize>>,
19955        window: &mut Window,
19956        cx: &mut Context<Self>,
19957    ) {
19958        if !self.input_enabled {
19959            return;
19960        }
19961
19962        let transaction = self.transact(window, cx, |this, window, cx| {
19963            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19964                let snapshot = this.buffer.read(cx).read(cx);
19965                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19966                    for marked_range in &mut marked_ranges {
19967                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19968                        marked_range.start.0 += relative_range_utf16.start;
19969                        marked_range.start =
19970                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19971                        marked_range.end =
19972                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19973                    }
19974                }
19975                Some(marked_ranges)
19976            } else if let Some(range_utf16) = range_utf16 {
19977                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19978                Some(this.selection_replacement_ranges(range_utf16, cx))
19979            } else {
19980                None
19981            };
19982
19983            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19984                let newest_selection_id = this.selections.newest_anchor().id;
19985                this.selections
19986                    .all::<OffsetUtf16>(cx)
19987                    .iter()
19988                    .zip(ranges_to_replace.iter())
19989                    .find_map(|(selection, range)| {
19990                        if selection.id == newest_selection_id {
19991                            Some(
19992                                (range.start.0 as isize - selection.head().0 as isize)
19993                                    ..(range.end.0 as isize - selection.head().0 as isize),
19994                            )
19995                        } else {
19996                            None
19997                        }
19998                    })
19999            });
20000
20001            cx.emit(EditorEvent::InputHandled {
20002                utf16_range_to_replace: range_to_replace,
20003                text: text.into(),
20004            });
20005
20006            if let Some(ranges) = ranges_to_replace {
20007                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20008            }
20009
20010            let marked_ranges = {
20011                let snapshot = this.buffer.read(cx).read(cx);
20012                this.selections
20013                    .disjoint_anchors()
20014                    .iter()
20015                    .map(|selection| {
20016                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20017                    })
20018                    .collect::<Vec<_>>()
20019            };
20020
20021            if text.is_empty() {
20022                this.unmark_text(window, cx);
20023            } else {
20024                this.highlight_text::<InputComposition>(
20025                    marked_ranges.clone(),
20026                    HighlightStyle {
20027                        underline: Some(UnderlineStyle {
20028                            thickness: px(1.),
20029                            color: None,
20030                            wavy: false,
20031                        }),
20032                        ..Default::default()
20033                    },
20034                    cx,
20035                );
20036            }
20037
20038            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20039            let use_autoclose = this.use_autoclose;
20040            let use_auto_surround = this.use_auto_surround;
20041            this.set_use_autoclose(false);
20042            this.set_use_auto_surround(false);
20043            this.handle_input(text, window, cx);
20044            this.set_use_autoclose(use_autoclose);
20045            this.set_use_auto_surround(use_auto_surround);
20046
20047            if let Some(new_selected_range) = new_selected_range_utf16 {
20048                let snapshot = this.buffer.read(cx).read(cx);
20049                let new_selected_ranges = marked_ranges
20050                    .into_iter()
20051                    .map(|marked_range| {
20052                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20053                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20054                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20055                        snapshot.clip_offset_utf16(new_start, Bias::Left)
20056                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20057                    })
20058                    .collect::<Vec<_>>();
20059
20060                drop(snapshot);
20061                this.change_selections(None, window, cx, |selections| {
20062                    selections.select_ranges(new_selected_ranges)
20063                });
20064            }
20065        });
20066
20067        self.ime_transaction = self.ime_transaction.or(transaction);
20068        if let Some(transaction) = self.ime_transaction {
20069            self.buffer.update(cx, |buffer, cx| {
20070                buffer.group_until_transaction(transaction, cx);
20071            });
20072        }
20073
20074        if self.text_highlights::<InputComposition>(cx).is_none() {
20075            self.ime_transaction.take();
20076        }
20077    }
20078
20079    fn bounds_for_range(
20080        &mut self,
20081        range_utf16: Range<usize>,
20082        element_bounds: gpui::Bounds<Pixels>,
20083        window: &mut Window,
20084        cx: &mut Context<Self>,
20085    ) -> Option<gpui::Bounds<Pixels>> {
20086        let text_layout_details = self.text_layout_details(window);
20087        let gpui::Size {
20088            width: em_width,
20089            height: line_height,
20090        } = self.character_size(window);
20091
20092        let snapshot = self.snapshot(window, cx);
20093        let scroll_position = snapshot.scroll_position();
20094        let scroll_left = scroll_position.x * em_width;
20095
20096        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20097        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20098            + self.gutter_dimensions.width
20099            + self.gutter_dimensions.margin;
20100        let y = line_height * (start.row().as_f32() - scroll_position.y);
20101
20102        Some(Bounds {
20103            origin: element_bounds.origin + point(x, y),
20104            size: size(em_width, line_height),
20105        })
20106    }
20107
20108    fn character_index_for_point(
20109        &mut self,
20110        point: gpui::Point<Pixels>,
20111        _window: &mut Window,
20112        _cx: &mut Context<Self>,
20113    ) -> Option<usize> {
20114        let position_map = self.last_position_map.as_ref()?;
20115        if !position_map.text_hitbox.contains(&point) {
20116            return None;
20117        }
20118        let display_point = position_map.point_for_position(point).previous_valid;
20119        let anchor = position_map
20120            .snapshot
20121            .display_point_to_anchor(display_point, Bias::Left);
20122        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20123        Some(utf16_offset.0)
20124    }
20125}
20126
20127trait SelectionExt {
20128    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20129    fn spanned_rows(
20130        &self,
20131        include_end_if_at_line_start: bool,
20132        map: &DisplaySnapshot,
20133    ) -> Range<MultiBufferRow>;
20134}
20135
20136impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20137    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20138        let start = self
20139            .start
20140            .to_point(&map.buffer_snapshot)
20141            .to_display_point(map);
20142        let end = self
20143            .end
20144            .to_point(&map.buffer_snapshot)
20145            .to_display_point(map);
20146        if self.reversed {
20147            end..start
20148        } else {
20149            start..end
20150        }
20151    }
20152
20153    fn spanned_rows(
20154        &self,
20155        include_end_if_at_line_start: bool,
20156        map: &DisplaySnapshot,
20157    ) -> Range<MultiBufferRow> {
20158        let start = self.start.to_point(&map.buffer_snapshot);
20159        let mut end = self.end.to_point(&map.buffer_snapshot);
20160        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20161            end.row -= 1;
20162        }
20163
20164        let buffer_start = map.prev_line_boundary(start).0;
20165        let buffer_end = map.next_line_boundary(end).0;
20166        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20167    }
20168}
20169
20170impl<T: InvalidationRegion> InvalidationStack<T> {
20171    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20172    where
20173        S: Clone + ToOffset,
20174    {
20175        while let Some(region) = self.last() {
20176            let all_selections_inside_invalidation_ranges =
20177                if selections.len() == region.ranges().len() {
20178                    selections
20179                        .iter()
20180                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20181                        .all(|(selection, invalidation_range)| {
20182                            let head = selection.head().to_offset(buffer);
20183                            invalidation_range.start <= head && invalidation_range.end >= head
20184                        })
20185                } else {
20186                    false
20187                };
20188
20189            if all_selections_inside_invalidation_ranges {
20190                break;
20191            } else {
20192                self.pop();
20193            }
20194        }
20195    }
20196}
20197
20198impl<T> Default for InvalidationStack<T> {
20199    fn default() -> Self {
20200        Self(Default::default())
20201    }
20202}
20203
20204impl<T> Deref for InvalidationStack<T> {
20205    type Target = Vec<T>;
20206
20207    fn deref(&self) -> &Self::Target {
20208        &self.0
20209    }
20210}
20211
20212impl<T> DerefMut for InvalidationStack<T> {
20213    fn deref_mut(&mut self) -> &mut Self::Target {
20214        &mut self.0
20215    }
20216}
20217
20218impl InvalidationRegion for SnippetState {
20219    fn ranges(&self) -> &[Range<Anchor>] {
20220        &self.ranges[self.active_index]
20221    }
20222}
20223
20224fn inline_completion_edit_text(
20225    current_snapshot: &BufferSnapshot,
20226    edits: &[(Range<Anchor>, String)],
20227    edit_preview: &EditPreview,
20228    include_deletions: bool,
20229    cx: &App,
20230) -> HighlightedText {
20231    let edits = edits
20232        .iter()
20233        .map(|(anchor, text)| {
20234            (
20235                anchor.start.text_anchor..anchor.end.text_anchor,
20236                text.clone(),
20237            )
20238        })
20239        .collect::<Vec<_>>();
20240
20241    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20242}
20243
20244pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20245    match severity {
20246        DiagnosticSeverity::ERROR => colors.error,
20247        DiagnosticSeverity::WARNING => colors.warning,
20248        DiagnosticSeverity::INFORMATION => colors.info,
20249        DiagnosticSeverity::HINT => colors.info,
20250        _ => colors.ignored,
20251    }
20252}
20253
20254pub fn styled_runs_for_code_label<'a>(
20255    label: &'a CodeLabel,
20256    syntax_theme: &'a theme::SyntaxTheme,
20257) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20258    let fade_out = HighlightStyle {
20259        fade_out: Some(0.35),
20260        ..Default::default()
20261    };
20262
20263    let mut prev_end = label.filter_range.end;
20264    label
20265        .runs
20266        .iter()
20267        .enumerate()
20268        .flat_map(move |(ix, (range, highlight_id))| {
20269            let style = if let Some(style) = highlight_id.style(syntax_theme) {
20270                style
20271            } else {
20272                return Default::default();
20273            };
20274            let mut muted_style = style;
20275            muted_style.highlight(fade_out);
20276
20277            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20278            if range.start >= label.filter_range.end {
20279                if range.start > prev_end {
20280                    runs.push((prev_end..range.start, fade_out));
20281                }
20282                runs.push((range.clone(), muted_style));
20283            } else if range.end <= label.filter_range.end {
20284                runs.push((range.clone(), style));
20285            } else {
20286                runs.push((range.start..label.filter_range.end, style));
20287                runs.push((label.filter_range.end..range.end, muted_style));
20288            }
20289            prev_end = cmp::max(prev_end, range.end);
20290
20291            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20292                runs.push((prev_end..label.text.len(), fade_out));
20293            }
20294
20295            runs
20296        })
20297}
20298
20299pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20300    let mut prev_index = 0;
20301    let mut prev_codepoint: Option<char> = None;
20302    text.char_indices()
20303        .chain([(text.len(), '\0')])
20304        .filter_map(move |(index, codepoint)| {
20305            let prev_codepoint = prev_codepoint.replace(codepoint)?;
20306            let is_boundary = index == text.len()
20307                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20308                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20309            if is_boundary {
20310                let chunk = &text[prev_index..index];
20311                prev_index = index;
20312                Some(chunk)
20313            } else {
20314                None
20315            }
20316        })
20317}
20318
20319pub trait RangeToAnchorExt: Sized {
20320    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20321
20322    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20323        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20324        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20325    }
20326}
20327
20328impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20329    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20330        let start_offset = self.start.to_offset(snapshot);
20331        let end_offset = self.end.to_offset(snapshot);
20332        if start_offset == end_offset {
20333            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20334        } else {
20335            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20336        }
20337    }
20338}
20339
20340pub trait RowExt {
20341    fn as_f32(&self) -> f32;
20342
20343    fn next_row(&self) -> Self;
20344
20345    fn previous_row(&self) -> Self;
20346
20347    fn minus(&self, other: Self) -> u32;
20348}
20349
20350impl RowExt for DisplayRow {
20351    fn as_f32(&self) -> f32 {
20352        self.0 as f32
20353    }
20354
20355    fn next_row(&self) -> Self {
20356        Self(self.0 + 1)
20357    }
20358
20359    fn previous_row(&self) -> Self {
20360        Self(self.0.saturating_sub(1))
20361    }
20362
20363    fn minus(&self, other: Self) -> u32 {
20364        self.0 - other.0
20365    }
20366}
20367
20368impl RowExt for MultiBufferRow {
20369    fn as_f32(&self) -> f32 {
20370        self.0 as f32
20371    }
20372
20373    fn next_row(&self) -> Self {
20374        Self(self.0 + 1)
20375    }
20376
20377    fn previous_row(&self) -> Self {
20378        Self(self.0.saturating_sub(1))
20379    }
20380
20381    fn minus(&self, other: Self) -> u32 {
20382        self.0 - other.0
20383    }
20384}
20385
20386trait RowRangeExt {
20387    type Row;
20388
20389    fn len(&self) -> usize;
20390
20391    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20392}
20393
20394impl RowRangeExt for Range<MultiBufferRow> {
20395    type Row = MultiBufferRow;
20396
20397    fn len(&self) -> usize {
20398        (self.end.0 - self.start.0) as usize
20399    }
20400
20401    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20402        (self.start.0..self.end.0).map(MultiBufferRow)
20403    }
20404}
20405
20406impl RowRangeExt for Range<DisplayRow> {
20407    type Row = DisplayRow;
20408
20409    fn len(&self) -> usize {
20410        (self.end.0 - self.start.0) as usize
20411    }
20412
20413    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20414        (self.start.0..self.end.0).map(DisplayRow)
20415    }
20416}
20417
20418/// If select range has more than one line, we
20419/// just point the cursor to range.start.
20420fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20421    if range.start.row == range.end.row {
20422        range
20423    } else {
20424        range.start..range.start
20425    }
20426}
20427pub struct KillRing(ClipboardItem);
20428impl Global for KillRing {}
20429
20430const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20431
20432enum BreakpointPromptEditAction {
20433    Log,
20434    Condition,
20435    HitCondition,
20436}
20437
20438struct BreakpointPromptEditor {
20439    pub(crate) prompt: Entity<Editor>,
20440    editor: WeakEntity<Editor>,
20441    breakpoint_anchor: Anchor,
20442    breakpoint: Breakpoint,
20443    edit_action: BreakpointPromptEditAction,
20444    block_ids: HashSet<CustomBlockId>,
20445    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20446    _subscriptions: Vec<Subscription>,
20447}
20448
20449impl BreakpointPromptEditor {
20450    const MAX_LINES: u8 = 4;
20451
20452    fn new(
20453        editor: WeakEntity<Editor>,
20454        breakpoint_anchor: Anchor,
20455        breakpoint: Breakpoint,
20456        edit_action: BreakpointPromptEditAction,
20457        window: &mut Window,
20458        cx: &mut Context<Self>,
20459    ) -> Self {
20460        let base_text = match edit_action {
20461            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20462            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20463            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20464        }
20465        .map(|msg| msg.to_string())
20466        .unwrap_or_default();
20467
20468        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20469        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20470
20471        let prompt = cx.new(|cx| {
20472            let mut prompt = Editor::new(
20473                EditorMode::AutoHeight {
20474                    max_lines: Self::MAX_LINES as usize,
20475                },
20476                buffer,
20477                None,
20478                window,
20479                cx,
20480            );
20481            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20482            prompt.set_show_cursor_when_unfocused(false, cx);
20483            prompt.set_placeholder_text(
20484                match edit_action {
20485                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20486                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20487                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20488                },
20489                cx,
20490            );
20491
20492            prompt
20493        });
20494
20495        Self {
20496            prompt,
20497            editor,
20498            breakpoint_anchor,
20499            breakpoint,
20500            edit_action,
20501            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20502            block_ids: Default::default(),
20503            _subscriptions: vec![],
20504        }
20505    }
20506
20507    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20508        self.block_ids.extend(block_ids)
20509    }
20510
20511    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20512        if let Some(editor) = self.editor.upgrade() {
20513            let message = self
20514                .prompt
20515                .read(cx)
20516                .buffer
20517                .read(cx)
20518                .as_singleton()
20519                .expect("A multi buffer in breakpoint prompt isn't possible")
20520                .read(cx)
20521                .as_rope()
20522                .to_string();
20523
20524            editor.update(cx, |editor, cx| {
20525                editor.edit_breakpoint_at_anchor(
20526                    self.breakpoint_anchor,
20527                    self.breakpoint.clone(),
20528                    match self.edit_action {
20529                        BreakpointPromptEditAction::Log => {
20530                            BreakpointEditAction::EditLogMessage(message.into())
20531                        }
20532                        BreakpointPromptEditAction::Condition => {
20533                            BreakpointEditAction::EditCondition(message.into())
20534                        }
20535                        BreakpointPromptEditAction::HitCondition => {
20536                            BreakpointEditAction::EditHitCondition(message.into())
20537                        }
20538                    },
20539                    cx,
20540                );
20541
20542                editor.remove_blocks(self.block_ids.clone(), None, cx);
20543                cx.focus_self(window);
20544            });
20545        }
20546    }
20547
20548    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20549        self.editor
20550            .update(cx, |editor, cx| {
20551                editor.remove_blocks(self.block_ids.clone(), None, cx);
20552                window.focus(&editor.focus_handle);
20553            })
20554            .log_err();
20555    }
20556
20557    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20558        let settings = ThemeSettings::get_global(cx);
20559        let text_style = TextStyle {
20560            color: if self.prompt.read(cx).read_only(cx) {
20561                cx.theme().colors().text_disabled
20562            } else {
20563                cx.theme().colors().text
20564            },
20565            font_family: settings.buffer_font.family.clone(),
20566            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20567            font_size: settings.buffer_font_size(cx).into(),
20568            font_weight: settings.buffer_font.weight,
20569            line_height: relative(settings.buffer_line_height.value()),
20570            ..Default::default()
20571        };
20572        EditorElement::new(
20573            &self.prompt,
20574            EditorStyle {
20575                background: cx.theme().colors().editor_background,
20576                local_player: cx.theme().players().local(),
20577                text: text_style,
20578                ..Default::default()
20579            },
20580        )
20581    }
20582}
20583
20584impl Render for BreakpointPromptEditor {
20585    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20586        let gutter_dimensions = *self.gutter_dimensions.lock();
20587        h_flex()
20588            .key_context("Editor")
20589            .bg(cx.theme().colors().editor_background)
20590            .border_y_1()
20591            .border_color(cx.theme().status().info_border)
20592            .size_full()
20593            .py(window.line_height() / 2.5)
20594            .on_action(cx.listener(Self::confirm))
20595            .on_action(cx.listener(Self::cancel))
20596            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20597            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20598    }
20599}
20600
20601impl Focusable for BreakpointPromptEditor {
20602    fn focus_handle(&self, cx: &App) -> FocusHandle {
20603        self.prompt.focus_handle(cx)
20604    }
20605}
20606
20607fn all_edits_insertions_or_deletions(
20608    edits: &Vec<(Range<Anchor>, String)>,
20609    snapshot: &MultiBufferSnapshot,
20610) -> bool {
20611    let mut all_insertions = true;
20612    let mut all_deletions = true;
20613
20614    for (range, new_text) in edits.iter() {
20615        let range_is_empty = range.to_offset(&snapshot).is_empty();
20616        let text_is_empty = new_text.is_empty();
20617
20618        if range_is_empty != text_is_empty {
20619            if range_is_empty {
20620                all_deletions = false;
20621            } else {
20622                all_insertions = false;
20623            }
20624        } else {
20625            return false;
20626        }
20627
20628        if !all_insertions && !all_deletions {
20629            return false;
20630        }
20631    }
20632    all_insertions || all_deletions
20633}
20634
20635struct MissingEditPredictionKeybindingTooltip;
20636
20637impl Render for MissingEditPredictionKeybindingTooltip {
20638    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20639        ui::tooltip_container(window, cx, |container, _, cx| {
20640            container
20641                .flex_shrink_0()
20642                .max_w_80()
20643                .min_h(rems_from_px(124.))
20644                .justify_between()
20645                .child(
20646                    v_flex()
20647                        .flex_1()
20648                        .text_ui_sm(cx)
20649                        .child(Label::new("Conflict with Accept Keybinding"))
20650                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20651                )
20652                .child(
20653                    h_flex()
20654                        .pb_1()
20655                        .gap_1()
20656                        .items_end()
20657                        .w_full()
20658                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20659                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20660                        }))
20661                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20662                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20663                        })),
20664                )
20665        })
20666    }
20667}
20668
20669#[derive(Debug, Clone, Copy, PartialEq)]
20670pub struct LineHighlight {
20671    pub background: Background,
20672    pub border: Option<gpui::Hsla>,
20673}
20674
20675impl From<Hsla> for LineHighlight {
20676    fn from(hsla: Hsla) -> Self {
20677        Self {
20678            background: hsla.into(),
20679            border: None,
20680        }
20681    }
20682}
20683
20684impl From<Background> for LineHighlight {
20685    fn from(background: Background) -> Self {
20686        Self {
20687            background,
20688            border: None,
20689        }
20690    }
20691}
20692
20693fn render_diff_hunk_controls(
20694    row: u32,
20695    status: &DiffHunkStatus,
20696    hunk_range: Range<Anchor>,
20697    is_created_file: bool,
20698    line_height: Pixels,
20699    editor: &Entity<Editor>,
20700    _window: &mut Window,
20701    cx: &mut App,
20702) -> AnyElement {
20703    h_flex()
20704        .h(line_height)
20705        .mr_1()
20706        .gap_1()
20707        .px_0p5()
20708        .pb_1()
20709        .border_x_1()
20710        .border_b_1()
20711        .border_color(cx.theme().colors().border_variant)
20712        .rounded_b_lg()
20713        .bg(cx.theme().colors().editor_background)
20714        .gap_1()
20715        .occlude()
20716        .shadow_md()
20717        .child(if status.has_secondary_hunk() {
20718            Button::new(("stage", row as u64), "Stage")
20719                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20720                .tooltip({
20721                    let focus_handle = editor.focus_handle(cx);
20722                    move |window, cx| {
20723                        Tooltip::for_action_in(
20724                            "Stage Hunk",
20725                            &::git::ToggleStaged,
20726                            &focus_handle,
20727                            window,
20728                            cx,
20729                        )
20730                    }
20731                })
20732                .on_click({
20733                    let editor = editor.clone();
20734                    move |_event, _window, cx| {
20735                        editor.update(cx, |editor, cx| {
20736                            editor.stage_or_unstage_diff_hunks(
20737                                true,
20738                                vec![hunk_range.start..hunk_range.start],
20739                                cx,
20740                            );
20741                        });
20742                    }
20743                })
20744        } else {
20745            Button::new(("unstage", row as u64), "Unstage")
20746                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20747                .tooltip({
20748                    let focus_handle = editor.focus_handle(cx);
20749                    move |window, cx| {
20750                        Tooltip::for_action_in(
20751                            "Unstage Hunk",
20752                            &::git::ToggleStaged,
20753                            &focus_handle,
20754                            window,
20755                            cx,
20756                        )
20757                    }
20758                })
20759                .on_click({
20760                    let editor = editor.clone();
20761                    move |_event, _window, cx| {
20762                        editor.update(cx, |editor, cx| {
20763                            editor.stage_or_unstage_diff_hunks(
20764                                false,
20765                                vec![hunk_range.start..hunk_range.start],
20766                                cx,
20767                            );
20768                        });
20769                    }
20770                })
20771        })
20772        .child(
20773            Button::new(("restore", row as u64), "Restore")
20774                .tooltip({
20775                    let focus_handle = editor.focus_handle(cx);
20776                    move |window, cx| {
20777                        Tooltip::for_action_in(
20778                            "Restore Hunk",
20779                            &::git::Restore,
20780                            &focus_handle,
20781                            window,
20782                            cx,
20783                        )
20784                    }
20785                })
20786                .on_click({
20787                    let editor = editor.clone();
20788                    move |_event, window, cx| {
20789                        editor.update(cx, |editor, cx| {
20790                            let snapshot = editor.snapshot(window, cx);
20791                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20792                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20793                        });
20794                    }
20795                })
20796                .disabled(is_created_file),
20797        )
20798        .when(
20799            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20800            |el| {
20801                el.child(
20802                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20803                        .shape(IconButtonShape::Square)
20804                        .icon_size(IconSize::Small)
20805                        // .disabled(!has_multiple_hunks)
20806                        .tooltip({
20807                            let focus_handle = editor.focus_handle(cx);
20808                            move |window, cx| {
20809                                Tooltip::for_action_in(
20810                                    "Next Hunk",
20811                                    &GoToHunk,
20812                                    &focus_handle,
20813                                    window,
20814                                    cx,
20815                                )
20816                            }
20817                        })
20818                        .on_click({
20819                            let editor = editor.clone();
20820                            move |_event, window, cx| {
20821                                editor.update(cx, |editor, cx| {
20822                                    let snapshot = editor.snapshot(window, cx);
20823                                    let position =
20824                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20825                                    editor.go_to_hunk_before_or_after_position(
20826                                        &snapshot,
20827                                        position,
20828                                        Direction::Next,
20829                                        window,
20830                                        cx,
20831                                    );
20832                                    editor.expand_selected_diff_hunks(cx);
20833                                });
20834                            }
20835                        }),
20836                )
20837                .child(
20838                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20839                        .shape(IconButtonShape::Square)
20840                        .icon_size(IconSize::Small)
20841                        // .disabled(!has_multiple_hunks)
20842                        .tooltip({
20843                            let focus_handle = editor.focus_handle(cx);
20844                            move |window, cx| {
20845                                Tooltip::for_action_in(
20846                                    "Previous Hunk",
20847                                    &GoToPreviousHunk,
20848                                    &focus_handle,
20849                                    window,
20850                                    cx,
20851                                )
20852                            }
20853                        })
20854                        .on_click({
20855                            let editor = editor.clone();
20856                            move |_event, window, cx| {
20857                                editor.update(cx, |editor, cx| {
20858                                    let snapshot = editor.snapshot(window, cx);
20859                                    let point =
20860                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20861                                    editor.go_to_hunk_before_or_after_position(
20862                                        &snapshot,
20863                                        point,
20864                                        Direction::Prev,
20865                                        window,
20866                                        cx,
20867                                    );
20868                                    editor.expand_selected_diff_hunks(cx);
20869                                });
20870                            }
20871                        }),
20872                )
20873            },
20874        )
20875        .into_any_element()
20876}