editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26mod hover_popover;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29pub mod items;
   30mod jsx_tag_auto_close;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{Context as _, Result, anyhow};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62use editor_settings::GoToDefinitionFallback;
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   65    ShowScrollbar,
   66};
   67pub use editor_settings_controls::*;
   68use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   69pub use element::{
   70    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   71};
   72use feature_flags::{Debugger, FeatureFlagAppExt};
   73use futures::{
   74    FutureExt,
   75    future::{self, Shared, join},
   76};
   77use fuzzy::StringMatchCandidate;
   78
   79use ::git::Restore;
   80use code_context_menus::{
   81    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   82    CompletionsMenu, ContextMenuOrigin,
   83};
   84use git::blame::{GitBlame, GlobalBlameRenderer};
   85use gpui::{
   86    Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
   87    AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
   88    ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
   89    FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
   90    KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
   91    SharedString, Size, Stateful, Styled, StyledText, Subscription, Task, TextStyle,
   92    TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
   93    WeakFocusHandle, Window, div, impl_actions, point, prelude::*, pulsating_between, px, relative,
   94    size,
   95};
   96use highlight_matching_bracket::refresh_matching_bracket_highlights;
   97use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
   98pub use hover_popover::hover_markdown_style;
   99use hover_popover::{HoverState, hide_hover};
  100use indent_guides::ActiveIndentGuidesState;
  101use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  102pub use inline_completion::Direction;
  103use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
  104pub use items::MAX_TAB_TITLE_LEN;
  105use itertools::Itertools;
  106use language::{
  107    AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  108    CursorShape, Diagnostic, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
  109    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  110    TransactionId, TreeSitterOptions, WordsQuery,
  111    language_settings::{
  112        self, InlayHintSettings, RewrapBehavior, WordsCompletionMode, all_language_settings,
  113        language_settings,
  114    },
  115    point_from_lsp, text_diff_with_options,
  116};
  117use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
  118use linked_editing_ranges::refresh_linked_ranges;
  119use mouse_context_menu::MouseContextMenu;
  120use persistence::DB;
  121use project::{
  122    ProjectPath,
  123    debugger::breakpoint_store::{
  124        BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
  125    },
  126};
  127
  128pub use git::blame::BlameRenderer;
  129pub use proposed_changes_editor::{
  130    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  131};
  132use smallvec::smallvec;
  133use std::{cell::OnceCell, iter::Peekable};
  134use task::{ResolvedTask, TaskTemplate, TaskVariables};
  135
  136pub use lsp::CompletionContext;
  137use lsp::{
  138    CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
  139    InsertTextFormat, LanguageServerId, LanguageServerName,
  140};
  141
  142use language::BufferSnapshot;
  143use movement::TextLayoutDetails;
  144pub use multi_buffer::{
  145    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  146    ToOffset, ToPoint,
  147};
  148use multi_buffer::{
  149    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  150    MultiOrSingleBufferOffsetRange, 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, OffsetUtf16, Rope};
  187use theme::{
  188    ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
  189    observe_buffer_font_size_adjustment,
  190};
  191use ui::{
  192    ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
  193    IconSize, Key, Tooltip, h_flex, prelude::*,
  194};
  195use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
  196use workspace::{
  197    Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
  198    RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
  199    ViewId, Workspace, WorkspaceId, WorkspaceSettings,
  200    item::{ItemHandle, PreviewTabsSettings},
  201    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  202    searchable::SearchEvent,
  203};
  204
  205use crate::hover_links::{find_url, find_url_from_range};
  206use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  207
  208pub const FILE_HEADER_HEIGHT: u32 = 2;
  209pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  210pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  211const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  212const MAX_LINE_LEN: usize = 1024;
  213const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  214const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  215pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  216#[doc(hidden)]
  217pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  218
  219pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
  220pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  221pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  222
  223pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  224pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  225pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
  226
  227pub type RenderDiffHunkControlsFn = Arc<
  228    dyn Fn(
  229        u32,
  230        &DiffHunkStatus,
  231        Range<Anchor>,
  232        bool,
  233        Pixels,
  234        &Entity<Editor>,
  235        &mut Window,
  236        &mut App,
  237    ) -> AnyElement,
  238>;
  239
  240const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  241    alt: true,
  242    shift: true,
  243    control: false,
  244    platform: false,
  245    function: false,
  246};
  247
  248#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  249pub enum InlayId {
  250    InlineCompletion(usize),
  251    Hint(usize),
  252}
  253
  254impl InlayId {
  255    fn id(&self) -> usize {
  256        match self {
  257            Self::InlineCompletion(id) => *id,
  258            Self::Hint(id) => *id,
  259        }
  260    }
  261}
  262
  263pub enum DebugCurrentRowHighlight {}
  264enum DocumentHighlightRead {}
  265enum DocumentHighlightWrite {}
  266enum InputComposition {}
  267enum SelectedTextHighlight {}
  268
  269#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  270pub enum Navigated {
  271    Yes,
  272    No,
  273}
  274
  275impl Navigated {
  276    pub fn from_bool(yes: bool) -> Navigated {
  277        if yes { Navigated::Yes } else { Navigated::No }
  278    }
  279}
  280
  281#[derive(Debug, Clone, PartialEq, Eq)]
  282enum DisplayDiffHunk {
  283    Folded {
  284        display_row: DisplayRow,
  285    },
  286    Unfolded {
  287        is_created_file: bool,
  288        diff_base_byte_range: Range<usize>,
  289        display_row_range: Range<DisplayRow>,
  290        multi_buffer_range: Range<Anchor>,
  291        status: DiffHunkStatus,
  292    },
  293}
  294
  295pub enum HideMouseCursorOrigin {
  296    TypingAction,
  297    MovementAction,
  298}
  299
  300pub fn init_settings(cx: &mut App) {
  301    EditorSettings::register(cx);
  302}
  303
  304pub fn init(cx: &mut App) {
  305    init_settings(cx);
  306
  307    cx.set_global(GlobalBlameRenderer(Arc::new(())));
  308
  309    workspace::register_project_item::<Editor>(cx);
  310    workspace::FollowableViewRegistry::register::<Editor>(cx);
  311    workspace::register_serializable_item::<Editor>(cx);
  312
  313    cx.observe_new(
  314        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  315            workspace.register_action(Editor::new_file);
  316            workspace.register_action(Editor::new_file_vertical);
  317            workspace.register_action(Editor::new_file_horizontal);
  318            workspace.register_action(Editor::cancel_language_server_work);
  319        },
  320    )
  321    .detach();
  322
  323    cx.on_action(move |_: &workspace::NewFile, cx| {
  324        let app_state = workspace::AppState::global(cx);
  325        if let Some(app_state) = app_state.upgrade() {
  326            workspace::open_new(
  327                Default::default(),
  328                app_state,
  329                cx,
  330                |workspace, window, cx| {
  331                    Editor::new_file(workspace, &Default::default(), window, cx)
  332                },
  333            )
  334            .detach();
  335        }
  336    });
  337    cx.on_action(move |_: &workspace::NewWindow, cx| {
  338        let app_state = workspace::AppState::global(cx);
  339        if let Some(app_state) = app_state.upgrade() {
  340            workspace::open_new(
  341                Default::default(),
  342                app_state,
  343                cx,
  344                |workspace, window, cx| {
  345                    cx.activate(true);
  346                    Editor::new_file(workspace, &Default::default(), window, cx)
  347                },
  348            )
  349            .detach();
  350        }
  351    });
  352}
  353
  354pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
  355    cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
  356}
  357
  358pub struct SearchWithinRange;
  359
  360trait InvalidationRegion {
  361    fn ranges(&self) -> &[Range<Anchor>];
  362}
  363
  364#[derive(Clone, Debug, PartialEq)]
  365pub enum SelectPhase {
  366    Begin {
  367        position: DisplayPoint,
  368        add: bool,
  369        click_count: usize,
  370    },
  371    BeginColumnar {
  372        position: DisplayPoint,
  373        reset: bool,
  374        goal_column: u32,
  375    },
  376    Extend {
  377        position: DisplayPoint,
  378        click_count: usize,
  379    },
  380    Update {
  381        position: DisplayPoint,
  382        goal_column: u32,
  383        scroll_delta: gpui::Point<f32>,
  384    },
  385    End,
  386}
  387
  388#[derive(Clone, Debug)]
  389pub enum SelectMode {
  390    Character,
  391    Word(Range<Anchor>),
  392    Line(Range<Anchor>),
  393    All,
  394}
  395
  396#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  397pub enum EditorMode {
  398    SingleLine { auto_width: bool },
  399    AutoHeight { max_lines: usize },
  400    Full,
  401}
  402
  403#[derive(Copy, Clone, Debug)]
  404pub enum SoftWrap {
  405    /// Prefer not to wrap at all.
  406    ///
  407    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  408    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  409    GitDiff,
  410    /// Prefer a single line generally, unless an overly long line is encountered.
  411    None,
  412    /// Soft wrap lines that exceed the editor width.
  413    EditorWidth,
  414    /// Soft wrap lines at the preferred line length.
  415    Column(u32),
  416    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  417    Bounded(u32),
  418}
  419
  420#[derive(Clone)]
  421pub struct EditorStyle {
  422    pub background: Hsla,
  423    pub local_player: PlayerColor,
  424    pub text: TextStyle,
  425    pub scrollbar_width: Pixels,
  426    pub syntax: Arc<SyntaxTheme>,
  427    pub status: StatusColors,
  428    pub inlay_hints_style: HighlightStyle,
  429    pub inline_completion_styles: InlineCompletionStyles,
  430    pub unnecessary_code_fade: f32,
  431}
  432
  433impl Default for EditorStyle {
  434    fn default() -> Self {
  435        Self {
  436            background: Hsla::default(),
  437            local_player: PlayerColor::default(),
  438            text: TextStyle::default(),
  439            scrollbar_width: Pixels::default(),
  440            syntax: Default::default(),
  441            // HACK: Status colors don't have a real default.
  442            // We should look into removing the status colors from the editor
  443            // style and retrieve them directly from the theme.
  444            status: StatusColors::dark(),
  445            inlay_hints_style: HighlightStyle::default(),
  446            inline_completion_styles: InlineCompletionStyles {
  447                insertion: HighlightStyle::default(),
  448                whitespace: HighlightStyle::default(),
  449            },
  450            unnecessary_code_fade: Default::default(),
  451        }
  452    }
  453}
  454
  455pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  456    let show_background = language_settings::language_settings(None, None, cx)
  457        .inlay_hints
  458        .show_background;
  459
  460    HighlightStyle {
  461        color: Some(cx.theme().status().hint),
  462        background_color: show_background.then(|| cx.theme().status().hint_background),
  463        ..HighlightStyle::default()
  464    }
  465}
  466
  467pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  468    InlineCompletionStyles {
  469        insertion: HighlightStyle {
  470            color: Some(cx.theme().status().predictive),
  471            ..HighlightStyle::default()
  472        },
  473        whitespace: HighlightStyle {
  474            background_color: Some(cx.theme().status().created_background),
  475            ..HighlightStyle::default()
  476        },
  477    }
  478}
  479
  480type CompletionId = usize;
  481
  482pub(crate) enum EditDisplayMode {
  483    TabAccept,
  484    DiffPopover,
  485    Inline,
  486}
  487
  488enum InlineCompletion {
  489    Edit {
  490        edits: Vec<(Range<Anchor>, String)>,
  491        edit_preview: Option<EditPreview>,
  492        display_mode: EditDisplayMode,
  493        snapshot: BufferSnapshot,
  494    },
  495    Move {
  496        target: Anchor,
  497        snapshot: BufferSnapshot,
  498    },
  499}
  500
  501struct InlineCompletionState {
  502    inlay_ids: Vec<InlayId>,
  503    completion: InlineCompletion,
  504    completion_id: Option<SharedString>,
  505    invalidation_range: Range<Anchor>,
  506}
  507
  508enum EditPredictionSettings {
  509    Disabled,
  510    Enabled {
  511        show_in_menu: bool,
  512        preview_requires_modifier: bool,
  513    },
  514}
  515
  516enum InlineCompletionHighlight {}
  517
  518#[derive(Debug, Clone)]
  519struct InlineDiagnostic {
  520    message: SharedString,
  521    group_id: usize,
  522    is_primary: bool,
  523    start: Point,
  524    severity: DiagnosticSeverity,
  525}
  526
  527pub enum MenuInlineCompletionsPolicy {
  528    Never,
  529    ByProvider,
  530}
  531
  532pub enum EditPredictionPreview {
  533    /// Modifier is not pressed
  534    Inactive { released_too_fast: bool },
  535    /// Modifier pressed
  536    Active {
  537        since: Instant,
  538        previous_scroll_position: Option<ScrollAnchor>,
  539    },
  540}
  541
  542impl EditPredictionPreview {
  543    pub fn released_too_fast(&self) -> bool {
  544        match self {
  545            EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
  546            EditPredictionPreview::Active { .. } => false,
  547        }
  548    }
  549
  550    pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
  551        if let EditPredictionPreview::Active {
  552            previous_scroll_position,
  553            ..
  554        } = self
  555        {
  556            *previous_scroll_position = scroll_position;
  557        }
  558    }
  559}
  560
  561pub struct ContextMenuOptions {
  562    pub min_entries_visible: usize,
  563    pub max_entries_visible: usize,
  564    pub placement: Option<ContextMenuPlacement>,
  565}
  566
  567#[derive(Debug, Clone, PartialEq, Eq)]
  568pub enum ContextMenuPlacement {
  569    Above,
  570    Below,
  571}
  572
  573#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  574struct EditorActionId(usize);
  575
  576impl EditorActionId {
  577    pub fn post_inc(&mut self) -> Self {
  578        let answer = self.0;
  579
  580        *self = Self(answer + 1);
  581
  582        Self(answer)
  583    }
  584}
  585
  586// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  587// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  588
  589type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  590type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  591
  592#[derive(Default)]
  593struct ScrollbarMarkerState {
  594    scrollbar_size: Size<Pixels>,
  595    dirty: bool,
  596    markers: Arc<[PaintQuad]>,
  597    pending_refresh: Option<Task<Result<()>>>,
  598}
  599
  600impl ScrollbarMarkerState {
  601    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  602        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  603    }
  604}
  605
  606#[derive(Clone, Debug)]
  607struct RunnableTasks {
  608    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  609    offset: multi_buffer::Anchor,
  610    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  611    column: u32,
  612    // Values of all named captures, including those starting with '_'
  613    extra_variables: HashMap<String, String>,
  614    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  615    context_range: Range<BufferOffset>,
  616}
  617
  618impl RunnableTasks {
  619    fn resolve<'a>(
  620        &'a self,
  621        cx: &'a task::TaskContext,
  622    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  623        self.templates.iter().filter_map(|(kind, template)| {
  624            template
  625                .resolve_task(&kind.to_id_base(), cx)
  626                .map(|task| (kind.clone(), task))
  627        })
  628    }
  629}
  630
  631#[derive(Clone)]
  632struct ResolvedTasks {
  633    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  634    position: Anchor,
  635}
  636
  637#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  638struct BufferOffset(usize);
  639
  640// Addons allow storing per-editor state in other crates (e.g. Vim)
  641pub trait Addon: 'static {
  642    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  643
  644    fn render_buffer_header_controls(
  645        &self,
  646        _: &ExcerptInfo,
  647        _: &Window,
  648        _: &App,
  649    ) -> Option<AnyElement> {
  650        None
  651    }
  652
  653    fn to_any(&self) -> &dyn std::any::Any;
  654}
  655
  656/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  657///
  658/// See the [module level documentation](self) for more information.
  659pub struct Editor {
  660    focus_handle: FocusHandle,
  661    last_focused_descendant: Option<WeakFocusHandle>,
  662    /// The text buffer being edited
  663    buffer: Entity<MultiBuffer>,
  664    /// Map of how text in the buffer should be displayed.
  665    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  666    pub display_map: Entity<DisplayMap>,
  667    pub selections: SelectionsCollection,
  668    pub scroll_manager: ScrollManager,
  669    /// When inline assist editors are linked, they all render cursors because
  670    /// typing enters text into each of them, even the ones that aren't focused.
  671    pub(crate) show_cursor_when_unfocused: bool,
  672    columnar_selection_tail: Option<Anchor>,
  673    add_selections_state: Option<AddSelectionsState>,
  674    select_next_state: Option<SelectNextState>,
  675    select_prev_state: Option<SelectNextState>,
  676    selection_history: SelectionHistory,
  677    autoclose_regions: Vec<AutocloseRegion>,
  678    snippet_stack: InvalidationStack<SnippetState>,
  679    select_syntax_node_history: SelectSyntaxNodeHistory,
  680    ime_transaction: Option<TransactionId>,
  681    active_diagnostics: Option<ActiveDiagnosticGroup>,
  682    show_inline_diagnostics: bool,
  683    inline_diagnostics_update: Task<()>,
  684    inline_diagnostics_enabled: bool,
  685    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  686    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  687    hard_wrap: Option<usize>,
  688
  689    // TODO: make this a access method
  690    pub project: Option<Entity<Project>>,
  691    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  692    completion_provider: Option<Box<dyn CompletionProvider>>,
  693    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  694    blink_manager: Entity<BlinkManager>,
  695    show_cursor_names: bool,
  696    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  697    pub show_local_selections: bool,
  698    mode: EditorMode,
  699    show_breadcrumbs: bool,
  700    show_gutter: bool,
  701    show_scrollbars: bool,
  702    show_line_numbers: Option<bool>,
  703    use_relative_line_numbers: Option<bool>,
  704    show_git_diff_gutter: Option<bool>,
  705    show_code_actions: Option<bool>,
  706    show_runnables: Option<bool>,
  707    show_breakpoints: Option<bool>,
  708    show_wrap_guides: Option<bool>,
  709    show_indent_guides: Option<bool>,
  710    placeholder_text: Option<Arc<str>>,
  711    highlight_order: usize,
  712    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  713    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  714    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  715    scrollbar_marker_state: ScrollbarMarkerState,
  716    active_indent_guides_state: ActiveIndentGuidesState,
  717    nav_history: Option<ItemNavHistory>,
  718    context_menu: RefCell<Option<CodeContextMenu>>,
  719    context_menu_options: Option<ContextMenuOptions>,
  720    mouse_context_menu: Option<MouseContextMenu>,
  721    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  722    signature_help_state: SignatureHelpState,
  723    auto_signature_help: Option<bool>,
  724    find_all_references_task_sources: Vec<Anchor>,
  725    next_completion_id: CompletionId,
  726    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  727    code_actions_task: Option<Task<Result<()>>>,
  728    selection_highlight_task: Option<Task<()>>,
  729    document_highlights_task: Option<Task<()>>,
  730    linked_editing_range_task: Option<Task<Option<()>>>,
  731    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  732    pending_rename: Option<RenameState>,
  733    searchable: bool,
  734    cursor_shape: CursorShape,
  735    current_line_highlight: Option<CurrentLineHighlight>,
  736    collapse_matches: bool,
  737    autoindent_mode: Option<AutoindentMode>,
  738    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  739    input_enabled: bool,
  740    use_modal_editing: bool,
  741    read_only: bool,
  742    leader_peer_id: Option<PeerId>,
  743    remote_id: Option<ViewId>,
  744    hover_state: HoverState,
  745    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  746    gutter_hovered: bool,
  747    hovered_link_state: Option<HoveredLinkState>,
  748    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  749    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  750    active_inline_completion: Option<InlineCompletionState>,
  751    /// Used to prevent flickering as the user types while the menu is open
  752    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  753    edit_prediction_settings: EditPredictionSettings,
  754    inline_completions_hidden_for_vim_mode: bool,
  755    show_inline_completions_override: Option<bool>,
  756    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  757    edit_prediction_preview: EditPredictionPreview,
  758    edit_prediction_indent_conflict: bool,
  759    edit_prediction_requires_modifier_in_indent_conflict: bool,
  760    inlay_hint_cache: InlayHintCache,
  761    next_inlay_id: usize,
  762    _subscriptions: Vec<Subscription>,
  763    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  764    gutter_dimensions: GutterDimensions,
  765    style: Option<EditorStyle>,
  766    text_style_refinement: Option<TextStyleRefinement>,
  767    next_editor_action_id: EditorActionId,
  768    editor_actions:
  769        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  770    use_autoclose: bool,
  771    use_auto_surround: bool,
  772    auto_replace_emoji_shortcode: bool,
  773    jsx_tag_auto_close_enabled_in_any_buffer: bool,
  774    show_git_blame_gutter: bool,
  775    show_git_blame_inline: bool,
  776    show_git_blame_inline_delay_task: Option<Task<()>>,
  777    pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
  778    git_blame_inline_enabled: bool,
  779    render_diff_hunk_controls: RenderDiffHunkControlsFn,
  780    serialize_dirty_buffers: bool,
  781    show_selection_menu: Option<bool>,
  782    blame: Option<Entity<GitBlame>>,
  783    blame_subscription: Option<Subscription>,
  784    custom_context_menu: Option<
  785        Box<
  786            dyn 'static
  787                + Fn(
  788                    &mut Self,
  789                    DisplayPoint,
  790                    &mut Window,
  791                    &mut Context<Self>,
  792                ) -> Option<Entity<ui::ContextMenu>>,
  793        >,
  794    >,
  795    last_bounds: Option<Bounds<Pixels>>,
  796    last_position_map: Option<Rc<PositionMap>>,
  797    expect_bounds_change: Option<Bounds<Pixels>>,
  798    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  799    tasks_update_task: Option<Task<()>>,
  800    breakpoint_store: Option<Entity<BreakpointStore>>,
  801    /// Allow's a user to create a breakpoint by selecting this indicator
  802    /// It should be None while a user is not hovering over the gutter
  803    /// Otherwise it represents the point that the breakpoint will be shown
  804    gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
  805    in_project_search: bool,
  806    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  807    breadcrumb_header: Option<String>,
  808    focused_block: Option<FocusedBlock>,
  809    next_scroll_position: NextScrollCursorCenterTopBottom,
  810    addons: HashMap<TypeId, Box<dyn Addon>>,
  811    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  812    load_diff_task: Option<Shared<Task<()>>>,
  813    selection_mark_mode: bool,
  814    toggle_fold_multiple_buffers: Task<()>,
  815    _scroll_cursor_center_top_bottom_task: Task<()>,
  816    serialize_selections: Task<()>,
  817    serialize_folds: Task<()>,
  818    mouse_cursor_hidden: bool,
  819    hide_mouse_mode: HideMouseMode,
  820}
  821
  822#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  823enum NextScrollCursorCenterTopBottom {
  824    #[default]
  825    Center,
  826    Top,
  827    Bottom,
  828}
  829
  830impl NextScrollCursorCenterTopBottom {
  831    fn next(&self) -> Self {
  832        match self {
  833            Self::Center => Self::Top,
  834            Self::Top => Self::Bottom,
  835            Self::Bottom => Self::Center,
  836        }
  837    }
  838}
  839
  840#[derive(Clone)]
  841pub struct EditorSnapshot {
  842    pub mode: EditorMode,
  843    show_gutter: bool,
  844    show_line_numbers: Option<bool>,
  845    show_git_diff_gutter: Option<bool>,
  846    show_code_actions: Option<bool>,
  847    show_runnables: Option<bool>,
  848    show_breakpoints: Option<bool>,
  849    git_blame_gutter_max_author_length: Option<usize>,
  850    pub display_snapshot: DisplaySnapshot,
  851    pub placeholder_text: Option<Arc<str>>,
  852    is_focused: bool,
  853    scroll_anchor: ScrollAnchor,
  854    ongoing_scroll: OngoingScroll,
  855    current_line_highlight: CurrentLineHighlight,
  856    gutter_hovered: bool,
  857}
  858
  859#[derive(Default, Debug, Clone, Copy)]
  860pub struct GutterDimensions {
  861    pub left_padding: Pixels,
  862    pub right_padding: Pixels,
  863    pub width: Pixels,
  864    pub margin: Pixels,
  865    pub git_blame_entries_width: Option<Pixels>,
  866}
  867
  868impl GutterDimensions {
  869    /// The full width of the space taken up by the gutter.
  870    pub fn full_width(&self) -> Pixels {
  871        self.margin + self.width
  872    }
  873
  874    /// The width of the space reserved for the fold indicators,
  875    /// use alongside 'justify_end' and `gutter_width` to
  876    /// right align content with the line numbers
  877    pub fn fold_area_width(&self) -> Pixels {
  878        self.margin + self.right_padding
  879    }
  880}
  881
  882#[derive(Debug)]
  883pub struct RemoteSelection {
  884    pub replica_id: ReplicaId,
  885    pub selection: Selection<Anchor>,
  886    pub cursor_shape: CursorShape,
  887    pub peer_id: PeerId,
  888    pub line_mode: bool,
  889    pub participant_index: Option<ParticipantIndex>,
  890    pub user_name: Option<SharedString>,
  891}
  892
  893#[derive(Clone, Debug)]
  894struct SelectionHistoryEntry {
  895    selections: Arc<[Selection<Anchor>]>,
  896    select_next_state: Option<SelectNextState>,
  897    select_prev_state: Option<SelectNextState>,
  898    add_selections_state: Option<AddSelectionsState>,
  899}
  900
  901enum SelectionHistoryMode {
  902    Normal,
  903    Undoing,
  904    Redoing,
  905}
  906
  907#[derive(Clone, PartialEq, Eq, Hash)]
  908struct HoveredCursor {
  909    replica_id: u16,
  910    selection_id: usize,
  911}
  912
  913impl Default for SelectionHistoryMode {
  914    fn default() -> Self {
  915        Self::Normal
  916    }
  917}
  918
  919#[derive(Default)]
  920struct SelectionHistory {
  921    #[allow(clippy::type_complexity)]
  922    selections_by_transaction:
  923        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  924    mode: SelectionHistoryMode,
  925    undo_stack: VecDeque<SelectionHistoryEntry>,
  926    redo_stack: VecDeque<SelectionHistoryEntry>,
  927}
  928
  929impl SelectionHistory {
  930    fn insert_transaction(
  931        &mut self,
  932        transaction_id: TransactionId,
  933        selections: Arc<[Selection<Anchor>]>,
  934    ) {
  935        self.selections_by_transaction
  936            .insert(transaction_id, (selections, None));
  937    }
  938
  939    #[allow(clippy::type_complexity)]
  940    fn transaction(
  941        &self,
  942        transaction_id: TransactionId,
  943    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  944        self.selections_by_transaction.get(&transaction_id)
  945    }
  946
  947    #[allow(clippy::type_complexity)]
  948    fn transaction_mut(
  949        &mut self,
  950        transaction_id: TransactionId,
  951    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  952        self.selections_by_transaction.get_mut(&transaction_id)
  953    }
  954
  955    fn push(&mut self, entry: SelectionHistoryEntry) {
  956        if !entry.selections.is_empty() {
  957            match self.mode {
  958                SelectionHistoryMode::Normal => {
  959                    self.push_undo(entry);
  960                    self.redo_stack.clear();
  961                }
  962                SelectionHistoryMode::Undoing => self.push_redo(entry),
  963                SelectionHistoryMode::Redoing => self.push_undo(entry),
  964            }
  965        }
  966    }
  967
  968    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  969        if self
  970            .undo_stack
  971            .back()
  972            .map_or(true, |e| e.selections != entry.selections)
  973        {
  974            self.undo_stack.push_back(entry);
  975            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  976                self.undo_stack.pop_front();
  977            }
  978        }
  979    }
  980
  981    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  982        if self
  983            .redo_stack
  984            .back()
  985            .map_or(true, |e| e.selections != entry.selections)
  986        {
  987            self.redo_stack.push_back(entry);
  988            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  989                self.redo_stack.pop_front();
  990            }
  991        }
  992    }
  993}
  994
  995struct RowHighlight {
  996    index: usize,
  997    range: Range<Anchor>,
  998    color: Hsla,
  999    should_autoscroll: bool,
 1000}
 1001
 1002#[derive(Clone, Debug)]
 1003struct AddSelectionsState {
 1004    above: bool,
 1005    stack: Vec<usize>,
 1006}
 1007
 1008#[derive(Clone)]
 1009struct SelectNextState {
 1010    query: AhoCorasick,
 1011    wordwise: bool,
 1012    done: bool,
 1013}
 1014
 1015impl std::fmt::Debug for SelectNextState {
 1016    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 1017        f.debug_struct(std::any::type_name::<Self>())
 1018            .field("wordwise", &self.wordwise)
 1019            .field("done", &self.done)
 1020            .finish()
 1021    }
 1022}
 1023
 1024#[derive(Debug)]
 1025struct AutocloseRegion {
 1026    selection_id: usize,
 1027    range: Range<Anchor>,
 1028    pair: BracketPair,
 1029}
 1030
 1031#[derive(Debug)]
 1032struct SnippetState {
 1033    ranges: Vec<Vec<Range<Anchor>>>,
 1034    active_index: usize,
 1035    choices: Vec<Option<Vec<String>>>,
 1036}
 1037
 1038#[doc(hidden)]
 1039pub struct RenameState {
 1040    pub range: Range<Anchor>,
 1041    pub old_name: Arc<str>,
 1042    pub editor: Entity<Editor>,
 1043    block_id: CustomBlockId,
 1044}
 1045
 1046struct InvalidationStack<T>(Vec<T>);
 1047
 1048struct RegisteredInlineCompletionProvider {
 1049    provider: Arc<dyn InlineCompletionProviderHandle>,
 1050    _subscription: Subscription,
 1051}
 1052
 1053#[derive(Debug, PartialEq, Eq)]
 1054struct ActiveDiagnosticGroup {
 1055    primary_range: Range<Anchor>,
 1056    primary_message: String,
 1057    group_id: usize,
 1058    blocks: HashMap<CustomBlockId, Diagnostic>,
 1059    is_valid: bool,
 1060}
 1061
 1062#[derive(Serialize, Deserialize, Clone, Debug)]
 1063pub struct ClipboardSelection {
 1064    /// The number of bytes in this selection.
 1065    pub len: usize,
 1066    /// Whether this was a full-line selection.
 1067    pub is_entire_line: bool,
 1068    /// The indentation of the first line when this content was originally copied.
 1069    pub first_line_indent: u32,
 1070}
 1071
 1072// selections, scroll behavior, was newest selection reversed
 1073type SelectSyntaxNodeHistoryState = (
 1074    Box<[Selection<usize>]>,
 1075    SelectSyntaxNodeScrollBehavior,
 1076    bool,
 1077);
 1078
 1079#[derive(Default)]
 1080struct SelectSyntaxNodeHistory {
 1081    stack: Vec<SelectSyntaxNodeHistoryState>,
 1082    // disable temporarily to allow changing selections without losing the stack
 1083    pub disable_clearing: bool,
 1084}
 1085
 1086impl SelectSyntaxNodeHistory {
 1087    pub fn try_clear(&mut self) {
 1088        if !self.disable_clearing {
 1089            self.stack.clear();
 1090        }
 1091    }
 1092
 1093    pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
 1094        self.stack.push(selection);
 1095    }
 1096
 1097    pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
 1098        self.stack.pop()
 1099    }
 1100}
 1101
 1102enum SelectSyntaxNodeScrollBehavior {
 1103    CursorTop,
 1104    CenterSelection,
 1105    CursorBottom,
 1106}
 1107
 1108#[derive(Debug)]
 1109pub(crate) struct NavigationData {
 1110    cursor_anchor: Anchor,
 1111    cursor_position: Point,
 1112    scroll_anchor: ScrollAnchor,
 1113    scroll_top_row: u32,
 1114}
 1115
 1116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1117pub enum GotoDefinitionKind {
 1118    Symbol,
 1119    Declaration,
 1120    Type,
 1121    Implementation,
 1122}
 1123
 1124#[derive(Debug, Clone)]
 1125enum InlayHintRefreshReason {
 1126    ModifiersChanged(bool),
 1127    Toggle(bool),
 1128    SettingsChange(InlayHintSettings),
 1129    NewLinesShown,
 1130    BufferEdited(HashSet<Arc<Language>>),
 1131    RefreshRequested,
 1132    ExcerptsRemoved(Vec<ExcerptId>),
 1133}
 1134
 1135impl InlayHintRefreshReason {
 1136    fn description(&self) -> &'static str {
 1137        match self {
 1138            Self::ModifiersChanged(_) => "modifiers changed",
 1139            Self::Toggle(_) => "toggle",
 1140            Self::SettingsChange(_) => "settings change",
 1141            Self::NewLinesShown => "new lines shown",
 1142            Self::BufferEdited(_) => "buffer edited",
 1143            Self::RefreshRequested => "refresh requested",
 1144            Self::ExcerptsRemoved(_) => "excerpts removed",
 1145        }
 1146    }
 1147}
 1148
 1149pub enum FormatTarget {
 1150    Buffers,
 1151    Ranges(Vec<Range<MultiBufferPoint>>),
 1152}
 1153
 1154pub(crate) struct FocusedBlock {
 1155    id: BlockId,
 1156    focus_handle: WeakFocusHandle,
 1157}
 1158
 1159#[derive(Clone)]
 1160enum JumpData {
 1161    MultiBufferRow {
 1162        row: MultiBufferRow,
 1163        line_offset_from_top: u32,
 1164    },
 1165    MultiBufferPoint {
 1166        excerpt_id: ExcerptId,
 1167        position: Point,
 1168        anchor: text::Anchor,
 1169        line_offset_from_top: u32,
 1170    },
 1171}
 1172
 1173pub enum MultibufferSelectionMode {
 1174    First,
 1175    All,
 1176}
 1177
 1178#[derive(Clone, Copy, Debug, Default)]
 1179pub struct RewrapOptions {
 1180    pub override_language_settings: bool,
 1181    pub preserve_existing_whitespace: bool,
 1182}
 1183
 1184impl Editor {
 1185    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1186        let buffer = cx.new(|cx| Buffer::local("", cx));
 1187        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1188        Self::new(
 1189            EditorMode::SingleLine { auto_width: false },
 1190            buffer,
 1191            None,
 1192            window,
 1193            cx,
 1194        )
 1195    }
 1196
 1197    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1198        let buffer = cx.new(|cx| Buffer::local("", cx));
 1199        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1200        Self::new(EditorMode::Full, buffer, None, window, cx)
 1201    }
 1202
 1203    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1204        let buffer = cx.new(|cx| Buffer::local("", cx));
 1205        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1206        Self::new(
 1207            EditorMode::SingleLine { auto_width: true },
 1208            buffer,
 1209            None,
 1210            window,
 1211            cx,
 1212        )
 1213    }
 1214
 1215    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1216        let buffer = cx.new(|cx| Buffer::local("", cx));
 1217        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1218        Self::new(
 1219            EditorMode::AutoHeight { max_lines },
 1220            buffer,
 1221            None,
 1222            window,
 1223            cx,
 1224        )
 1225    }
 1226
 1227    pub fn for_buffer(
 1228        buffer: Entity<Buffer>,
 1229        project: Option<Entity<Project>>,
 1230        window: &mut Window,
 1231        cx: &mut Context<Self>,
 1232    ) -> Self {
 1233        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1234        Self::new(EditorMode::Full, buffer, project, window, cx)
 1235    }
 1236
 1237    pub fn for_multibuffer(
 1238        buffer: Entity<MultiBuffer>,
 1239        project: Option<Entity<Project>>,
 1240        window: &mut Window,
 1241        cx: &mut Context<Self>,
 1242    ) -> Self {
 1243        Self::new(EditorMode::Full, buffer, project, window, cx)
 1244    }
 1245
 1246    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1247        let mut clone = Self::new(
 1248            self.mode,
 1249            self.buffer.clone(),
 1250            self.project.clone(),
 1251            window,
 1252            cx,
 1253        );
 1254        self.display_map.update(cx, |display_map, cx| {
 1255            let snapshot = display_map.snapshot(cx);
 1256            clone.display_map.update(cx, |display_map, cx| {
 1257                display_map.set_state(&snapshot, cx);
 1258            });
 1259        });
 1260        clone.folds_did_change(cx);
 1261        clone.selections.clone_state(&self.selections);
 1262        clone.scroll_manager.clone_state(&self.scroll_manager);
 1263        clone.searchable = self.searchable;
 1264        clone
 1265    }
 1266
 1267    pub fn new(
 1268        mode: EditorMode,
 1269        buffer: Entity<MultiBuffer>,
 1270        project: Option<Entity<Project>>,
 1271        window: &mut Window,
 1272        cx: &mut Context<Self>,
 1273    ) -> Self {
 1274        let style = window.text_style();
 1275        let font_size = style.font_size.to_pixels(window.rem_size());
 1276        let editor = cx.entity().downgrade();
 1277        let fold_placeholder = FoldPlaceholder {
 1278            constrain_width: true,
 1279            render: Arc::new(move |fold_id, fold_range, cx| {
 1280                let editor = editor.clone();
 1281                div()
 1282                    .id(fold_id)
 1283                    .bg(cx.theme().colors().ghost_element_background)
 1284                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1285                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1286                    .rounded_xs()
 1287                    .size_full()
 1288                    .cursor_pointer()
 1289                    .child("")
 1290                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1291                    .on_click(move |_, _window, cx| {
 1292                        editor
 1293                            .update(cx, |editor, cx| {
 1294                                editor.unfold_ranges(
 1295                                    &[fold_range.start..fold_range.end],
 1296                                    true,
 1297                                    false,
 1298                                    cx,
 1299                                );
 1300                                cx.stop_propagation();
 1301                            })
 1302                            .ok();
 1303                    })
 1304                    .into_any()
 1305            }),
 1306            merge_adjacent: true,
 1307            ..Default::default()
 1308        };
 1309        let display_map = cx.new(|cx| {
 1310            DisplayMap::new(
 1311                buffer.clone(),
 1312                style.font(),
 1313                font_size,
 1314                None,
 1315                FILE_HEADER_HEIGHT,
 1316                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1317                fold_placeholder,
 1318                cx,
 1319            )
 1320        });
 1321
 1322        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1323
 1324        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1325
 1326        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1327            .then(|| language_settings::SoftWrap::None);
 1328
 1329        let mut project_subscriptions = Vec::new();
 1330        if mode == EditorMode::Full {
 1331            if let Some(project) = project.as_ref() {
 1332                project_subscriptions.push(cx.subscribe_in(
 1333                    project,
 1334                    window,
 1335                    |editor, _, event, window, cx| match event {
 1336                        project::Event::RefreshCodeLens => {
 1337                            // we always query lens with actions, without storing them, always refreshing them
 1338                        }
 1339                        project::Event::RefreshInlayHints => {
 1340                            editor
 1341                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1342                        }
 1343                        project::Event::SnippetEdit(id, snippet_edits) => {
 1344                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1345                                let focus_handle = editor.focus_handle(cx);
 1346                                if focus_handle.is_focused(window) {
 1347                                    let snapshot = buffer.read(cx).snapshot();
 1348                                    for (range, snippet) in snippet_edits {
 1349                                        let editor_range =
 1350                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1351                                        editor
 1352                                            .insert_snippet(
 1353                                                &[editor_range],
 1354                                                snippet.clone(),
 1355                                                window,
 1356                                                cx,
 1357                                            )
 1358                                            .ok();
 1359                                    }
 1360                                }
 1361                            }
 1362                        }
 1363                        _ => {}
 1364                    },
 1365                ));
 1366                if let Some(task_inventory) = project
 1367                    .read(cx)
 1368                    .task_store()
 1369                    .read(cx)
 1370                    .task_inventory()
 1371                    .cloned()
 1372                {
 1373                    project_subscriptions.push(cx.observe_in(
 1374                        &task_inventory,
 1375                        window,
 1376                        |editor, _, window, cx| {
 1377                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1378                        },
 1379                    ));
 1380                };
 1381
 1382                project_subscriptions.push(cx.subscribe_in(
 1383                    &project.read(cx).breakpoint_store(),
 1384                    window,
 1385                    |editor, _, event, window, cx| match event {
 1386                        BreakpointStoreEvent::ActiveDebugLineChanged => {
 1387                            editor.go_to_active_debug_line(window, cx);
 1388                        }
 1389                        _ => {}
 1390                    },
 1391                ));
 1392            }
 1393        }
 1394
 1395        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1396
 1397        let inlay_hint_settings =
 1398            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1399        let focus_handle = cx.focus_handle();
 1400        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1401            .detach();
 1402        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1403            .detach();
 1404        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1405            .detach();
 1406        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1407            .detach();
 1408
 1409        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1410            Some(false)
 1411        } else {
 1412            None
 1413        };
 1414
 1415        let breakpoint_store = match (mode, project.as_ref()) {
 1416            (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
 1417            _ => None,
 1418        };
 1419
 1420        let mut code_action_providers = Vec::new();
 1421        let mut load_uncommitted_diff = None;
 1422        if let Some(project) = project.clone() {
 1423            load_uncommitted_diff = Some(
 1424                get_uncommitted_diff_for_buffer(
 1425                    &project,
 1426                    buffer.read(cx).all_buffers(),
 1427                    buffer.clone(),
 1428                    cx,
 1429                )
 1430                .shared(),
 1431            );
 1432            code_action_providers.push(Rc::new(project) as Rc<_>);
 1433        }
 1434
 1435        let mut this = Self {
 1436            focus_handle,
 1437            show_cursor_when_unfocused: false,
 1438            last_focused_descendant: None,
 1439            buffer: buffer.clone(),
 1440            display_map: display_map.clone(),
 1441            selections,
 1442            scroll_manager: ScrollManager::new(cx),
 1443            columnar_selection_tail: None,
 1444            add_selections_state: None,
 1445            select_next_state: None,
 1446            select_prev_state: None,
 1447            selection_history: Default::default(),
 1448            autoclose_regions: Default::default(),
 1449            snippet_stack: Default::default(),
 1450            select_syntax_node_history: SelectSyntaxNodeHistory::default(),
 1451            ime_transaction: Default::default(),
 1452            active_diagnostics: None,
 1453            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1454            inline_diagnostics_update: Task::ready(()),
 1455            inline_diagnostics: Vec::new(),
 1456            soft_wrap_mode_override,
 1457            hard_wrap: None,
 1458            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1459            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1460            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1461            project,
 1462            blink_manager: blink_manager.clone(),
 1463            show_local_selections: true,
 1464            show_scrollbars: true,
 1465            mode,
 1466            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1467            show_gutter: mode == EditorMode::Full,
 1468            show_line_numbers: None,
 1469            use_relative_line_numbers: None,
 1470            show_git_diff_gutter: None,
 1471            show_code_actions: None,
 1472            show_runnables: None,
 1473            show_breakpoints: None,
 1474            show_wrap_guides: None,
 1475            show_indent_guides,
 1476            placeholder_text: None,
 1477            highlight_order: 0,
 1478            highlighted_rows: HashMap::default(),
 1479            background_highlights: Default::default(),
 1480            gutter_highlights: TreeMap::default(),
 1481            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1482            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1483            nav_history: None,
 1484            context_menu: RefCell::new(None),
 1485            context_menu_options: None,
 1486            mouse_context_menu: None,
 1487            completion_tasks: Default::default(),
 1488            signature_help_state: SignatureHelpState::default(),
 1489            auto_signature_help: None,
 1490            find_all_references_task_sources: Vec::new(),
 1491            next_completion_id: 0,
 1492            next_inlay_id: 0,
 1493            code_action_providers,
 1494            available_code_actions: Default::default(),
 1495            code_actions_task: Default::default(),
 1496            selection_highlight_task: Default::default(),
 1497            document_highlights_task: Default::default(),
 1498            linked_editing_range_task: Default::default(),
 1499            pending_rename: Default::default(),
 1500            searchable: true,
 1501            cursor_shape: EditorSettings::get_global(cx)
 1502                .cursor_shape
 1503                .unwrap_or_default(),
 1504            current_line_highlight: None,
 1505            autoindent_mode: Some(AutoindentMode::EachLine),
 1506            collapse_matches: false,
 1507            workspace: None,
 1508            input_enabled: true,
 1509            use_modal_editing: mode == EditorMode::Full,
 1510            read_only: false,
 1511            use_autoclose: true,
 1512            use_auto_surround: true,
 1513            auto_replace_emoji_shortcode: false,
 1514            jsx_tag_auto_close_enabled_in_any_buffer: false,
 1515            leader_peer_id: None,
 1516            remote_id: None,
 1517            hover_state: Default::default(),
 1518            pending_mouse_down: None,
 1519            hovered_link_state: Default::default(),
 1520            edit_prediction_provider: None,
 1521            active_inline_completion: None,
 1522            stale_inline_completion_in_menu: None,
 1523            edit_prediction_preview: EditPredictionPreview::Inactive {
 1524                released_too_fast: false,
 1525            },
 1526            inline_diagnostics_enabled: mode == EditorMode::Full,
 1527            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1528
 1529            gutter_hovered: false,
 1530            pixel_position_of_newest_cursor: None,
 1531            last_bounds: None,
 1532            last_position_map: None,
 1533            expect_bounds_change: None,
 1534            gutter_dimensions: GutterDimensions::default(),
 1535            style: None,
 1536            show_cursor_names: false,
 1537            hovered_cursors: Default::default(),
 1538            next_editor_action_id: EditorActionId::default(),
 1539            editor_actions: Rc::default(),
 1540            inline_completions_hidden_for_vim_mode: false,
 1541            show_inline_completions_override: None,
 1542            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1543            edit_prediction_settings: EditPredictionSettings::Disabled,
 1544            edit_prediction_indent_conflict: false,
 1545            edit_prediction_requires_modifier_in_indent_conflict: true,
 1546            custom_context_menu: None,
 1547            show_git_blame_gutter: false,
 1548            show_git_blame_inline: false,
 1549            show_selection_menu: None,
 1550            show_git_blame_inline_delay_task: None,
 1551            git_blame_inline_tooltip: None,
 1552            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1553            render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
 1554            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1555                .session
 1556                .restore_unsaved_buffers,
 1557            blame: None,
 1558            blame_subscription: None,
 1559            tasks: Default::default(),
 1560
 1561            breakpoint_store,
 1562            gutter_breakpoint_indicator: (None, None),
 1563            _subscriptions: vec![
 1564                cx.observe(&buffer, Self::on_buffer_changed),
 1565                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1566                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1567                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1568                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1569                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1570                cx.observe_window_activation(window, |editor, window, cx| {
 1571                    let active = window.is_window_active();
 1572                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1573                        if active {
 1574                            blink_manager.enable(cx);
 1575                        } else {
 1576                            blink_manager.disable(cx);
 1577                        }
 1578                    });
 1579                }),
 1580            ],
 1581            tasks_update_task: None,
 1582            linked_edit_ranges: Default::default(),
 1583            in_project_search: false,
 1584            previous_search_ranges: None,
 1585            breadcrumb_header: None,
 1586            focused_block: None,
 1587            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1588            addons: HashMap::default(),
 1589            registered_buffers: HashMap::default(),
 1590            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1591            selection_mark_mode: false,
 1592            toggle_fold_multiple_buffers: Task::ready(()),
 1593            serialize_selections: Task::ready(()),
 1594            serialize_folds: Task::ready(()),
 1595            text_style_refinement: None,
 1596            load_diff_task: load_uncommitted_diff,
 1597            mouse_cursor_hidden: false,
 1598            hide_mouse_mode: EditorSettings::get_global(cx)
 1599                .hide_mouse
 1600                .unwrap_or_default(),
 1601        };
 1602        if let Some(breakpoints) = this.breakpoint_store.as_ref() {
 1603            this._subscriptions
 1604                .push(cx.observe(breakpoints, |_, _, cx| {
 1605                    cx.notify();
 1606                }));
 1607        }
 1608        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1609        this._subscriptions.extend(project_subscriptions);
 1610        this._subscriptions
 1611            .push(cx.subscribe_self(|editor, e: &EditorEvent, cx| {
 1612                if let EditorEvent::SelectionsChanged { local } = e {
 1613                    if *local {
 1614                        let new_anchor = editor.scroll_manager.anchor();
 1615                        editor.update_restoration_data(cx, move |data| {
 1616                            data.scroll_anchor = new_anchor;
 1617                        });
 1618                    }
 1619                }
 1620            }));
 1621
 1622        this.end_selection(window, cx);
 1623        this.scroll_manager.show_scrollbars(window, cx);
 1624        jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
 1625
 1626        if mode == EditorMode::Full {
 1627            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1628            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1629
 1630            if this.git_blame_inline_enabled {
 1631                this.git_blame_inline_enabled = true;
 1632                this.start_git_blame_inline(false, window, cx);
 1633            }
 1634
 1635            this.go_to_active_debug_line(window, cx);
 1636
 1637            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1638                if let Some(project) = this.project.as_ref() {
 1639                    let handle = project.update(cx, |project, cx| {
 1640                        project.register_buffer_with_language_servers(&buffer, cx)
 1641                    });
 1642                    this.registered_buffers
 1643                        .insert(buffer.read(cx).remote_id(), handle);
 1644                }
 1645            }
 1646        }
 1647
 1648        this.report_editor_event("Editor Opened", None, cx);
 1649        this
 1650    }
 1651
 1652    pub fn deploy_mouse_context_menu(
 1653        &mut self,
 1654        position: gpui::Point<Pixels>,
 1655        context_menu: Entity<ContextMenu>,
 1656        window: &mut Window,
 1657        cx: &mut Context<Self>,
 1658    ) {
 1659        self.mouse_context_menu = Some(MouseContextMenu::new(
 1660            crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
 1661            context_menu,
 1662            window,
 1663            cx,
 1664        ));
 1665    }
 1666
 1667    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1668        self.mouse_context_menu
 1669            .as_ref()
 1670            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1671    }
 1672
 1673    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1674        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1675    }
 1676
 1677    fn key_context_internal(
 1678        &self,
 1679        has_active_edit_prediction: bool,
 1680        window: &Window,
 1681        cx: &App,
 1682    ) -> KeyContext {
 1683        let mut key_context = KeyContext::new_with_defaults();
 1684        key_context.add("Editor");
 1685        let mode = match self.mode {
 1686            EditorMode::SingleLine { .. } => "single_line",
 1687            EditorMode::AutoHeight { .. } => "auto_height",
 1688            EditorMode::Full => "full",
 1689        };
 1690
 1691        if EditorSettings::jupyter_enabled(cx) {
 1692            key_context.add("jupyter");
 1693        }
 1694
 1695        key_context.set("mode", mode);
 1696        if self.pending_rename.is_some() {
 1697            key_context.add("renaming");
 1698        }
 1699
 1700        match self.context_menu.borrow().as_ref() {
 1701            Some(CodeContextMenu::Completions(_)) => {
 1702                key_context.add("menu");
 1703                key_context.add("showing_completions");
 1704            }
 1705            Some(CodeContextMenu::CodeActions(_)) => {
 1706                key_context.add("menu");
 1707                key_context.add("showing_code_actions")
 1708            }
 1709            None => {}
 1710        }
 1711
 1712        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1713        if !self.focus_handle(cx).contains_focused(window, cx)
 1714            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1715        {
 1716            for addon in self.addons.values() {
 1717                addon.extend_key_context(&mut key_context, cx)
 1718            }
 1719        }
 1720
 1721        if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
 1722            if let Some(extension) = singleton_buffer
 1723                .read(cx)
 1724                .file()
 1725                .and_then(|file| file.path().extension()?.to_str())
 1726            {
 1727                key_context.set("extension", extension.to_string());
 1728            }
 1729        } else {
 1730            key_context.add("multibuffer");
 1731        }
 1732
 1733        if has_active_edit_prediction {
 1734            if self.edit_prediction_in_conflict() {
 1735                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1736            } else {
 1737                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1738                key_context.add("copilot_suggestion");
 1739            }
 1740        }
 1741
 1742        if self.selection_mark_mode {
 1743            key_context.add("selection_mode");
 1744        }
 1745
 1746        key_context
 1747    }
 1748
 1749    pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
 1750        self.mouse_cursor_hidden = match origin {
 1751            HideMouseCursorOrigin::TypingAction => {
 1752                matches!(
 1753                    self.hide_mouse_mode,
 1754                    HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
 1755                )
 1756            }
 1757            HideMouseCursorOrigin::MovementAction => {
 1758                matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
 1759            }
 1760        };
 1761    }
 1762
 1763    pub fn edit_prediction_in_conflict(&self) -> bool {
 1764        if !self.show_edit_predictions_in_menu() {
 1765            return false;
 1766        }
 1767
 1768        let showing_completions = self
 1769            .context_menu
 1770            .borrow()
 1771            .as_ref()
 1772            .map_or(false, |context| {
 1773                matches!(context, CodeContextMenu::Completions(_))
 1774            });
 1775
 1776        showing_completions
 1777            || self.edit_prediction_requires_modifier()
 1778            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1779            // bindings to insert tab characters.
 1780            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1781    }
 1782
 1783    pub fn accept_edit_prediction_keybind(
 1784        &self,
 1785        window: &Window,
 1786        cx: &App,
 1787    ) -> AcceptEditPredictionBinding {
 1788        let key_context = self.key_context_internal(true, window, cx);
 1789        let in_conflict = self.edit_prediction_in_conflict();
 1790
 1791        AcceptEditPredictionBinding(
 1792            window
 1793                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1794                .into_iter()
 1795                .filter(|binding| {
 1796                    !in_conflict
 1797                        || binding
 1798                            .keystrokes()
 1799                            .first()
 1800                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1801                })
 1802                .rev()
 1803                .min_by_key(|binding| {
 1804                    binding
 1805                        .keystrokes()
 1806                        .first()
 1807                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1808                }),
 1809        )
 1810    }
 1811
 1812    pub fn new_file(
 1813        workspace: &mut Workspace,
 1814        _: &workspace::NewFile,
 1815        window: &mut Window,
 1816        cx: &mut Context<Workspace>,
 1817    ) {
 1818        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1819            "Failed to create buffer",
 1820            window,
 1821            cx,
 1822            |e, _, _| match e.error_code() {
 1823                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1824                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1825                e.error_tag("required").unwrap_or("the latest version")
 1826            )),
 1827                _ => None,
 1828            },
 1829        );
 1830    }
 1831
 1832    pub fn new_in_workspace(
 1833        workspace: &mut Workspace,
 1834        window: &mut Window,
 1835        cx: &mut Context<Workspace>,
 1836    ) -> Task<Result<Entity<Editor>>> {
 1837        let project = workspace.project().clone();
 1838        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1839
 1840        cx.spawn_in(window, async move |workspace, cx| {
 1841            let buffer = create.await?;
 1842            workspace.update_in(cx, |workspace, window, cx| {
 1843                let editor =
 1844                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1845                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1846                editor
 1847            })
 1848        })
 1849    }
 1850
 1851    fn new_file_vertical(
 1852        workspace: &mut Workspace,
 1853        _: &workspace::NewFileSplitVertical,
 1854        window: &mut Window,
 1855        cx: &mut Context<Workspace>,
 1856    ) {
 1857        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1858    }
 1859
 1860    fn new_file_horizontal(
 1861        workspace: &mut Workspace,
 1862        _: &workspace::NewFileSplitHorizontal,
 1863        window: &mut Window,
 1864        cx: &mut Context<Workspace>,
 1865    ) {
 1866        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1867    }
 1868
 1869    fn new_file_in_direction(
 1870        workspace: &mut Workspace,
 1871        direction: SplitDirection,
 1872        window: &mut Window,
 1873        cx: &mut Context<Workspace>,
 1874    ) {
 1875        let project = workspace.project().clone();
 1876        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1877
 1878        cx.spawn_in(window, async move |workspace, cx| {
 1879            let buffer = create.await?;
 1880            workspace.update_in(cx, move |workspace, window, cx| {
 1881                workspace.split_item(
 1882                    direction,
 1883                    Box::new(
 1884                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1885                    ),
 1886                    window,
 1887                    cx,
 1888                )
 1889            })?;
 1890            anyhow::Ok(())
 1891        })
 1892        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1893            match e.error_code() {
 1894                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1895                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1896                e.error_tag("required").unwrap_or("the latest version")
 1897            )),
 1898                _ => None,
 1899            }
 1900        });
 1901    }
 1902
 1903    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1904        self.leader_peer_id
 1905    }
 1906
 1907    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1908        &self.buffer
 1909    }
 1910
 1911    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1912        self.workspace.as_ref()?.0.upgrade()
 1913    }
 1914
 1915    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1916        self.buffer().read(cx).title(cx)
 1917    }
 1918
 1919    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1920        let git_blame_gutter_max_author_length = self
 1921            .render_git_blame_gutter(cx)
 1922            .then(|| {
 1923                if let Some(blame) = self.blame.as_ref() {
 1924                    let max_author_length =
 1925                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1926                    Some(max_author_length)
 1927                } else {
 1928                    None
 1929                }
 1930            })
 1931            .flatten();
 1932
 1933        EditorSnapshot {
 1934            mode: self.mode,
 1935            show_gutter: self.show_gutter,
 1936            show_line_numbers: self.show_line_numbers,
 1937            show_git_diff_gutter: self.show_git_diff_gutter,
 1938            show_code_actions: self.show_code_actions,
 1939            show_runnables: self.show_runnables,
 1940            show_breakpoints: self.show_breakpoints,
 1941            git_blame_gutter_max_author_length,
 1942            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1943            scroll_anchor: self.scroll_manager.anchor(),
 1944            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1945            placeholder_text: self.placeholder_text.clone(),
 1946            is_focused: self.focus_handle.is_focused(window),
 1947            current_line_highlight: self
 1948                .current_line_highlight
 1949                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1950            gutter_hovered: self.gutter_hovered,
 1951        }
 1952    }
 1953
 1954    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1955        self.buffer.read(cx).language_at(point, cx)
 1956    }
 1957
 1958    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1959        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1960    }
 1961
 1962    pub fn active_excerpt(
 1963        &self,
 1964        cx: &App,
 1965    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1966        self.buffer
 1967            .read(cx)
 1968            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1969    }
 1970
 1971    pub fn mode(&self) -> EditorMode {
 1972        self.mode
 1973    }
 1974
 1975    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1976        self.collaboration_hub.as_deref()
 1977    }
 1978
 1979    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1980        self.collaboration_hub = Some(hub);
 1981    }
 1982
 1983    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1984        self.in_project_search = in_project_search;
 1985    }
 1986
 1987    pub fn set_custom_context_menu(
 1988        &mut self,
 1989        f: impl 'static
 1990        + Fn(
 1991            &mut Self,
 1992            DisplayPoint,
 1993            &mut Window,
 1994            &mut Context<Self>,
 1995        ) -> Option<Entity<ui::ContextMenu>>,
 1996    ) {
 1997        self.custom_context_menu = Some(Box::new(f))
 1998    }
 1999
 2000    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 2001        self.completion_provider = provider;
 2002    }
 2003
 2004    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 2005        self.semantics_provider.clone()
 2006    }
 2007
 2008    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 2009        self.semantics_provider = provider;
 2010    }
 2011
 2012    pub fn set_edit_prediction_provider<T>(
 2013        &mut self,
 2014        provider: Option<Entity<T>>,
 2015        window: &mut Window,
 2016        cx: &mut Context<Self>,
 2017    ) where
 2018        T: EditPredictionProvider,
 2019    {
 2020        self.edit_prediction_provider =
 2021            provider.map(|provider| RegisteredInlineCompletionProvider {
 2022                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 2023                    if this.focus_handle.is_focused(window) {
 2024                        this.update_visible_inline_completion(window, cx);
 2025                    }
 2026                }),
 2027                provider: Arc::new(provider),
 2028            });
 2029        self.update_edit_prediction_settings(cx);
 2030        self.refresh_inline_completion(false, false, window, cx);
 2031    }
 2032
 2033    pub fn placeholder_text(&self) -> Option<&str> {
 2034        self.placeholder_text.as_deref()
 2035    }
 2036
 2037    pub fn set_placeholder_text(
 2038        &mut self,
 2039        placeholder_text: impl Into<Arc<str>>,
 2040        cx: &mut Context<Self>,
 2041    ) {
 2042        let placeholder_text = Some(placeholder_text.into());
 2043        if self.placeholder_text != placeholder_text {
 2044            self.placeholder_text = placeholder_text;
 2045            cx.notify();
 2046        }
 2047    }
 2048
 2049    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 2050        self.cursor_shape = cursor_shape;
 2051
 2052        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2053        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2054
 2055        cx.notify();
 2056    }
 2057
 2058    pub fn set_current_line_highlight(
 2059        &mut self,
 2060        current_line_highlight: Option<CurrentLineHighlight>,
 2061    ) {
 2062        self.current_line_highlight = current_line_highlight;
 2063    }
 2064
 2065    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2066        self.collapse_matches = collapse_matches;
 2067    }
 2068
 2069    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 2070        let buffers = self.buffer.read(cx).all_buffers();
 2071        let Some(project) = self.project.as_ref() else {
 2072            return;
 2073        };
 2074        project.update(cx, |project, cx| {
 2075            for buffer in buffers {
 2076                self.registered_buffers
 2077                    .entry(buffer.read(cx).remote_id())
 2078                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 2079            }
 2080        })
 2081    }
 2082
 2083    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2084        if self.collapse_matches {
 2085            return range.start..range.start;
 2086        }
 2087        range.clone()
 2088    }
 2089
 2090    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 2091        if self.display_map.read(cx).clip_at_line_ends != clip {
 2092            self.display_map
 2093                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2094        }
 2095    }
 2096
 2097    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2098        self.input_enabled = input_enabled;
 2099    }
 2100
 2101    pub fn set_inline_completions_hidden_for_vim_mode(
 2102        &mut self,
 2103        hidden: bool,
 2104        window: &mut Window,
 2105        cx: &mut Context<Self>,
 2106    ) {
 2107        if hidden != self.inline_completions_hidden_for_vim_mode {
 2108            self.inline_completions_hidden_for_vim_mode = hidden;
 2109            if hidden {
 2110                self.update_visible_inline_completion(window, cx);
 2111            } else {
 2112                self.refresh_inline_completion(true, false, window, cx);
 2113            }
 2114        }
 2115    }
 2116
 2117    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 2118        self.menu_inline_completions_policy = value;
 2119    }
 2120
 2121    pub fn set_autoindent(&mut self, autoindent: bool) {
 2122        if autoindent {
 2123            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2124        } else {
 2125            self.autoindent_mode = None;
 2126        }
 2127    }
 2128
 2129    pub fn read_only(&self, cx: &App) -> bool {
 2130        self.read_only || self.buffer.read(cx).read_only()
 2131    }
 2132
 2133    pub fn set_read_only(&mut self, read_only: bool) {
 2134        self.read_only = read_only;
 2135    }
 2136
 2137    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2138        self.use_autoclose = autoclose;
 2139    }
 2140
 2141    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2142        self.use_auto_surround = auto_surround;
 2143    }
 2144
 2145    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2146        self.auto_replace_emoji_shortcode = auto_replace;
 2147    }
 2148
 2149    pub fn toggle_edit_predictions(
 2150        &mut self,
 2151        _: &ToggleEditPrediction,
 2152        window: &mut Window,
 2153        cx: &mut Context<Self>,
 2154    ) {
 2155        if self.show_inline_completions_override.is_some() {
 2156            self.set_show_edit_predictions(None, window, cx);
 2157        } else {
 2158            let show_edit_predictions = !self.edit_predictions_enabled();
 2159            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2160        }
 2161    }
 2162
 2163    pub fn set_show_edit_predictions(
 2164        &mut self,
 2165        show_edit_predictions: Option<bool>,
 2166        window: &mut Window,
 2167        cx: &mut Context<Self>,
 2168    ) {
 2169        self.show_inline_completions_override = show_edit_predictions;
 2170        self.update_edit_prediction_settings(cx);
 2171
 2172        if let Some(false) = show_edit_predictions {
 2173            self.discard_inline_completion(false, cx);
 2174        } else {
 2175            self.refresh_inline_completion(false, true, window, cx);
 2176        }
 2177    }
 2178
 2179    fn inline_completions_disabled_in_scope(
 2180        &self,
 2181        buffer: &Entity<Buffer>,
 2182        buffer_position: language::Anchor,
 2183        cx: &App,
 2184    ) -> bool {
 2185        let snapshot = buffer.read(cx).snapshot();
 2186        let settings = snapshot.settings_at(buffer_position, cx);
 2187
 2188        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2189            return false;
 2190        };
 2191
 2192        scope.override_name().map_or(false, |scope_name| {
 2193            settings
 2194                .edit_predictions_disabled_in
 2195                .iter()
 2196                .any(|s| s == scope_name)
 2197        })
 2198    }
 2199
 2200    pub fn set_use_modal_editing(&mut self, to: bool) {
 2201        self.use_modal_editing = to;
 2202    }
 2203
 2204    pub fn use_modal_editing(&self) -> bool {
 2205        self.use_modal_editing
 2206    }
 2207
 2208    fn selections_did_change(
 2209        &mut self,
 2210        local: bool,
 2211        old_cursor_position: &Anchor,
 2212        show_completions: bool,
 2213        window: &mut Window,
 2214        cx: &mut Context<Self>,
 2215    ) {
 2216        window.invalidate_character_coordinates();
 2217
 2218        // Copy selections to primary selection buffer
 2219        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2220        if local {
 2221            let selections = self.selections.all::<usize>(cx);
 2222            let buffer_handle = self.buffer.read(cx).read(cx);
 2223
 2224            let mut text = String::new();
 2225            for (index, selection) in selections.iter().enumerate() {
 2226                let text_for_selection = buffer_handle
 2227                    .text_for_range(selection.start..selection.end)
 2228                    .collect::<String>();
 2229
 2230                text.push_str(&text_for_selection);
 2231                if index != selections.len() - 1 {
 2232                    text.push('\n');
 2233                }
 2234            }
 2235
 2236            if !text.is_empty() {
 2237                cx.write_to_primary(ClipboardItem::new_string(text));
 2238            }
 2239        }
 2240
 2241        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2242            self.buffer.update(cx, |buffer, cx| {
 2243                buffer.set_active_selections(
 2244                    &self.selections.disjoint_anchors(),
 2245                    self.selections.line_mode,
 2246                    self.cursor_shape,
 2247                    cx,
 2248                )
 2249            });
 2250        }
 2251        let display_map = self
 2252            .display_map
 2253            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2254        let buffer = &display_map.buffer_snapshot;
 2255        self.add_selections_state = None;
 2256        self.select_next_state = None;
 2257        self.select_prev_state = None;
 2258        self.select_syntax_node_history.try_clear();
 2259        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2260        self.snippet_stack
 2261            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2262        self.take_rename(false, window, cx);
 2263
 2264        let new_cursor_position = self.selections.newest_anchor().head();
 2265
 2266        self.push_to_nav_history(
 2267            *old_cursor_position,
 2268            Some(new_cursor_position.to_point(buffer)),
 2269            false,
 2270            cx,
 2271        );
 2272
 2273        if local {
 2274            let new_cursor_position = self.selections.newest_anchor().head();
 2275            let mut context_menu = self.context_menu.borrow_mut();
 2276            let completion_menu = match context_menu.as_ref() {
 2277                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2278                _ => {
 2279                    *context_menu = None;
 2280                    None
 2281                }
 2282            };
 2283            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2284                if !self.registered_buffers.contains_key(&buffer_id) {
 2285                    if let Some(project) = self.project.as_ref() {
 2286                        project.update(cx, |project, cx| {
 2287                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2288                                return;
 2289                            };
 2290                            self.registered_buffers.insert(
 2291                                buffer_id,
 2292                                project.register_buffer_with_language_servers(&buffer, cx),
 2293                            );
 2294                        })
 2295                    }
 2296                }
 2297            }
 2298
 2299            if let Some(completion_menu) = completion_menu {
 2300                let cursor_position = new_cursor_position.to_offset(buffer);
 2301                let (word_range, kind) =
 2302                    buffer.surrounding_word(completion_menu.initial_position, true);
 2303                if kind == Some(CharKind::Word)
 2304                    && word_range.to_inclusive().contains(&cursor_position)
 2305                {
 2306                    let mut completion_menu = completion_menu.clone();
 2307                    drop(context_menu);
 2308
 2309                    let query = Self::completion_query(buffer, cursor_position);
 2310                    cx.spawn(async move |this, cx| {
 2311                        completion_menu
 2312                            .filter(query.as_deref(), cx.background_executor().clone())
 2313                            .await;
 2314
 2315                        this.update(cx, |this, cx| {
 2316                            let mut context_menu = this.context_menu.borrow_mut();
 2317                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2318                            else {
 2319                                return;
 2320                            };
 2321
 2322                            if menu.id > completion_menu.id {
 2323                                return;
 2324                            }
 2325
 2326                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2327                            drop(context_menu);
 2328                            cx.notify();
 2329                        })
 2330                    })
 2331                    .detach();
 2332
 2333                    if show_completions {
 2334                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2335                    }
 2336                } else {
 2337                    drop(context_menu);
 2338                    self.hide_context_menu(window, cx);
 2339                }
 2340            } else {
 2341                drop(context_menu);
 2342            }
 2343
 2344            hide_hover(self, cx);
 2345
 2346            if old_cursor_position.to_display_point(&display_map).row()
 2347                != new_cursor_position.to_display_point(&display_map).row()
 2348            {
 2349                self.available_code_actions.take();
 2350            }
 2351            self.refresh_code_actions(window, cx);
 2352            self.refresh_document_highlights(cx);
 2353            self.refresh_selected_text_highlights(window, cx);
 2354            refresh_matching_bracket_highlights(self, window, cx);
 2355            self.update_visible_inline_completion(window, cx);
 2356            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2357            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2358            if self.git_blame_inline_enabled {
 2359                self.start_inline_blame_timer(window, cx);
 2360            }
 2361        }
 2362
 2363        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2364        cx.emit(EditorEvent::SelectionsChanged { local });
 2365
 2366        let selections = &self.selections.disjoint;
 2367        if selections.len() == 1 {
 2368            cx.emit(SearchEvent::ActiveMatchChanged)
 2369        }
 2370        if local && self.is_singleton(cx) {
 2371            let inmemory_selections = selections.iter().map(|s| s.range()).collect();
 2372            self.update_restoration_data(cx, |data| {
 2373                data.selections = inmemory_selections;
 2374            });
 2375
 2376            if WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2377            {
 2378                if let Some(workspace_id) =
 2379                    self.workspace.as_ref().and_then(|workspace| workspace.1)
 2380                {
 2381                    let snapshot = self.buffer().read(cx).snapshot(cx);
 2382                    let selections = selections.clone();
 2383                    let background_executor = cx.background_executor().clone();
 2384                    let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2385                    self.serialize_selections = cx.background_spawn(async move {
 2386                    background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2387                    let db_selections = selections
 2388                        .iter()
 2389                        .map(|selection| {
 2390                            (
 2391                                selection.start.to_offset(&snapshot),
 2392                                selection.end.to_offset(&snapshot),
 2393                            )
 2394                        })
 2395                        .collect();
 2396
 2397                    DB.save_editor_selections(editor_id, workspace_id, db_selections)
 2398                        .await
 2399                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2400                        .log_err();
 2401                });
 2402                }
 2403            }
 2404        }
 2405
 2406        cx.notify();
 2407    }
 2408
 2409    fn folds_did_change(&mut self, cx: &mut Context<Self>) {
 2410        if !self.is_singleton(cx)
 2411            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
 2412        {
 2413            return;
 2414        }
 2415
 2416        let snapshot = self.buffer().read(cx).snapshot(cx);
 2417        let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
 2418            display_map
 2419                .snapshot(cx)
 2420                .folds_in_range(0..snapshot.len())
 2421                .map(|fold| fold.range.deref().clone())
 2422                .collect()
 2423        });
 2424        self.update_restoration_data(cx, |data| {
 2425            data.folds = inmemory_folds;
 2426        });
 2427
 2428        let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
 2429            return;
 2430        };
 2431        let background_executor = cx.background_executor().clone();
 2432        let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2433        let db_folds = self.display_map.update(cx, |display_map, cx| {
 2434            display_map
 2435                .snapshot(cx)
 2436                .folds_in_range(0..snapshot.len())
 2437                .map(|fold| {
 2438                    (
 2439                        fold.range.start.to_offset(&snapshot),
 2440                        fold.range.end.to_offset(&snapshot),
 2441                    )
 2442                })
 2443                .collect()
 2444        });
 2445        self.serialize_folds = cx.background_spawn(async move {
 2446            background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
 2447            DB.save_editor_folds(editor_id, workspace_id, db_folds)
 2448                .await
 2449                .with_context(|| {
 2450                    format!(
 2451                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
 2452                    )
 2453                })
 2454                .log_err();
 2455        });
 2456    }
 2457
 2458    pub fn sync_selections(
 2459        &mut self,
 2460        other: Entity<Editor>,
 2461        cx: &mut Context<Self>,
 2462    ) -> gpui::Subscription {
 2463        let other_selections = other.read(cx).selections.disjoint.to_vec();
 2464        self.selections.change_with(cx, |selections| {
 2465            selections.select_anchors(other_selections);
 2466        });
 2467
 2468        let other_subscription =
 2469            cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
 2470                EditorEvent::SelectionsChanged { local: true } => {
 2471                    let other_selections = other.read(cx).selections.disjoint.to_vec();
 2472                    if other_selections.is_empty() {
 2473                        return;
 2474                    }
 2475                    this.selections.change_with(cx, |selections| {
 2476                        selections.select_anchors(other_selections);
 2477                    });
 2478                }
 2479                _ => {}
 2480            });
 2481
 2482        let this_subscription =
 2483            cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
 2484                EditorEvent::SelectionsChanged { local: true } => {
 2485                    let these_selections = this.selections.disjoint.to_vec();
 2486                    if these_selections.is_empty() {
 2487                        return;
 2488                    }
 2489                    other.update(cx, |other_editor, cx| {
 2490                        other_editor.selections.change_with(cx, |selections| {
 2491                            selections.select_anchors(these_selections);
 2492                        })
 2493                    });
 2494                }
 2495                _ => {}
 2496            });
 2497
 2498        Subscription::join(other_subscription, this_subscription)
 2499    }
 2500
 2501    pub fn change_selections<R>(
 2502        &mut self,
 2503        autoscroll: Option<Autoscroll>,
 2504        window: &mut Window,
 2505        cx: &mut Context<Self>,
 2506        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2507    ) -> R {
 2508        self.change_selections_inner(autoscroll, true, window, cx, change)
 2509    }
 2510
 2511    fn change_selections_inner<R>(
 2512        &mut self,
 2513        autoscroll: Option<Autoscroll>,
 2514        request_completions: bool,
 2515        window: &mut Window,
 2516        cx: &mut Context<Self>,
 2517        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2518    ) -> R {
 2519        let old_cursor_position = self.selections.newest_anchor().head();
 2520        self.push_to_selection_history();
 2521
 2522        let (changed, result) = self.selections.change_with(cx, change);
 2523
 2524        if changed {
 2525            if let Some(autoscroll) = autoscroll {
 2526                self.request_autoscroll(autoscroll, cx);
 2527            }
 2528            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2529
 2530            if self.should_open_signature_help_automatically(
 2531                &old_cursor_position,
 2532                self.signature_help_state.backspace_pressed(),
 2533                cx,
 2534            ) {
 2535                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2536            }
 2537            self.signature_help_state.set_backspace_pressed(false);
 2538        }
 2539
 2540        result
 2541    }
 2542
 2543    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2544    where
 2545        I: IntoIterator<Item = (Range<S>, T)>,
 2546        S: ToOffset,
 2547        T: Into<Arc<str>>,
 2548    {
 2549        if self.read_only(cx) {
 2550            return;
 2551        }
 2552
 2553        self.buffer
 2554            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2555    }
 2556
 2557    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2558    where
 2559        I: IntoIterator<Item = (Range<S>, T)>,
 2560        S: ToOffset,
 2561        T: Into<Arc<str>>,
 2562    {
 2563        if self.read_only(cx) {
 2564            return;
 2565        }
 2566
 2567        self.buffer.update(cx, |buffer, cx| {
 2568            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2569        });
 2570    }
 2571
 2572    pub fn edit_with_block_indent<I, S, T>(
 2573        &mut self,
 2574        edits: I,
 2575        original_indent_columns: Vec<Option<u32>>,
 2576        cx: &mut Context<Self>,
 2577    ) where
 2578        I: IntoIterator<Item = (Range<S>, T)>,
 2579        S: ToOffset,
 2580        T: Into<Arc<str>>,
 2581    {
 2582        if self.read_only(cx) {
 2583            return;
 2584        }
 2585
 2586        self.buffer.update(cx, |buffer, cx| {
 2587            buffer.edit(
 2588                edits,
 2589                Some(AutoindentMode::Block {
 2590                    original_indent_columns,
 2591                }),
 2592                cx,
 2593            )
 2594        });
 2595    }
 2596
 2597    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2598        self.hide_context_menu(window, cx);
 2599
 2600        match phase {
 2601            SelectPhase::Begin {
 2602                position,
 2603                add,
 2604                click_count,
 2605            } => self.begin_selection(position, add, click_count, window, cx),
 2606            SelectPhase::BeginColumnar {
 2607                position,
 2608                goal_column,
 2609                reset,
 2610            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2611            SelectPhase::Extend {
 2612                position,
 2613                click_count,
 2614            } => self.extend_selection(position, click_count, window, cx),
 2615            SelectPhase::Update {
 2616                position,
 2617                goal_column,
 2618                scroll_delta,
 2619            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2620            SelectPhase::End => self.end_selection(window, cx),
 2621        }
 2622    }
 2623
 2624    fn extend_selection(
 2625        &mut self,
 2626        position: DisplayPoint,
 2627        click_count: usize,
 2628        window: &mut Window,
 2629        cx: &mut Context<Self>,
 2630    ) {
 2631        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2632        let tail = self.selections.newest::<usize>(cx).tail();
 2633        self.begin_selection(position, false, click_count, window, cx);
 2634
 2635        let position = position.to_offset(&display_map, Bias::Left);
 2636        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2637
 2638        let mut pending_selection = self
 2639            .selections
 2640            .pending_anchor()
 2641            .expect("extend_selection not called with pending selection");
 2642        if position >= tail {
 2643            pending_selection.start = tail_anchor;
 2644        } else {
 2645            pending_selection.end = tail_anchor;
 2646            pending_selection.reversed = true;
 2647        }
 2648
 2649        let mut pending_mode = self.selections.pending_mode().unwrap();
 2650        match &mut pending_mode {
 2651            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2652            _ => {}
 2653        }
 2654
 2655        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2656            s.set_pending(pending_selection, pending_mode)
 2657        });
 2658    }
 2659
 2660    fn begin_selection(
 2661        &mut self,
 2662        position: DisplayPoint,
 2663        add: bool,
 2664        click_count: usize,
 2665        window: &mut Window,
 2666        cx: &mut Context<Self>,
 2667    ) {
 2668        if !self.focus_handle.is_focused(window) {
 2669            self.last_focused_descendant = None;
 2670            window.focus(&self.focus_handle);
 2671        }
 2672
 2673        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2674        let buffer = &display_map.buffer_snapshot;
 2675        let newest_selection = self.selections.newest_anchor().clone();
 2676        let position = display_map.clip_point(position, Bias::Left);
 2677
 2678        let start;
 2679        let end;
 2680        let mode;
 2681        let mut auto_scroll;
 2682        match click_count {
 2683            1 => {
 2684                start = buffer.anchor_before(position.to_point(&display_map));
 2685                end = start;
 2686                mode = SelectMode::Character;
 2687                auto_scroll = true;
 2688            }
 2689            2 => {
 2690                let range = movement::surrounding_word(&display_map, position);
 2691                start = buffer.anchor_before(range.start.to_point(&display_map));
 2692                end = buffer.anchor_before(range.end.to_point(&display_map));
 2693                mode = SelectMode::Word(start..end);
 2694                auto_scroll = true;
 2695            }
 2696            3 => {
 2697                let position = display_map
 2698                    .clip_point(position, Bias::Left)
 2699                    .to_point(&display_map);
 2700                let line_start = display_map.prev_line_boundary(position).0;
 2701                let next_line_start = buffer.clip_point(
 2702                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2703                    Bias::Left,
 2704                );
 2705                start = buffer.anchor_before(line_start);
 2706                end = buffer.anchor_before(next_line_start);
 2707                mode = SelectMode::Line(start..end);
 2708                auto_scroll = true;
 2709            }
 2710            _ => {
 2711                start = buffer.anchor_before(0);
 2712                end = buffer.anchor_before(buffer.len());
 2713                mode = SelectMode::All;
 2714                auto_scroll = false;
 2715            }
 2716        }
 2717        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2718
 2719        let point_to_delete: Option<usize> = {
 2720            let selected_points: Vec<Selection<Point>> =
 2721                self.selections.disjoint_in_range(start..end, cx);
 2722
 2723            if !add || click_count > 1 {
 2724                None
 2725            } else if !selected_points.is_empty() {
 2726                Some(selected_points[0].id)
 2727            } else {
 2728                let clicked_point_already_selected =
 2729                    self.selections.disjoint.iter().find(|selection| {
 2730                        selection.start.to_point(buffer) == start.to_point(buffer)
 2731                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2732                    });
 2733
 2734                clicked_point_already_selected.map(|selection| selection.id)
 2735            }
 2736        };
 2737
 2738        let selections_count = self.selections.count();
 2739
 2740        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2741            if let Some(point_to_delete) = point_to_delete {
 2742                s.delete(point_to_delete);
 2743
 2744                if selections_count == 1 {
 2745                    s.set_pending_anchor_range(start..end, mode);
 2746                }
 2747            } else {
 2748                if !add {
 2749                    s.clear_disjoint();
 2750                } else if click_count > 1 {
 2751                    s.delete(newest_selection.id)
 2752                }
 2753
 2754                s.set_pending_anchor_range(start..end, mode);
 2755            }
 2756        });
 2757    }
 2758
 2759    fn begin_columnar_selection(
 2760        &mut self,
 2761        position: DisplayPoint,
 2762        goal_column: u32,
 2763        reset: bool,
 2764        window: &mut Window,
 2765        cx: &mut Context<Self>,
 2766    ) {
 2767        if !self.focus_handle.is_focused(window) {
 2768            self.last_focused_descendant = None;
 2769            window.focus(&self.focus_handle);
 2770        }
 2771
 2772        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2773
 2774        if reset {
 2775            let pointer_position = display_map
 2776                .buffer_snapshot
 2777                .anchor_before(position.to_point(&display_map));
 2778
 2779            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2780                s.clear_disjoint();
 2781                s.set_pending_anchor_range(
 2782                    pointer_position..pointer_position,
 2783                    SelectMode::Character,
 2784                );
 2785            });
 2786        }
 2787
 2788        let tail = self.selections.newest::<Point>(cx).tail();
 2789        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2790
 2791        if !reset {
 2792            self.select_columns(
 2793                tail.to_display_point(&display_map),
 2794                position,
 2795                goal_column,
 2796                &display_map,
 2797                window,
 2798                cx,
 2799            );
 2800        }
 2801    }
 2802
 2803    fn update_selection(
 2804        &mut self,
 2805        position: DisplayPoint,
 2806        goal_column: u32,
 2807        scroll_delta: gpui::Point<f32>,
 2808        window: &mut Window,
 2809        cx: &mut Context<Self>,
 2810    ) {
 2811        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2812
 2813        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2814            let tail = tail.to_display_point(&display_map);
 2815            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2816        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2817            let buffer = self.buffer.read(cx).snapshot(cx);
 2818            let head;
 2819            let tail;
 2820            let mode = self.selections.pending_mode().unwrap();
 2821            match &mode {
 2822                SelectMode::Character => {
 2823                    head = position.to_point(&display_map);
 2824                    tail = pending.tail().to_point(&buffer);
 2825                }
 2826                SelectMode::Word(original_range) => {
 2827                    let original_display_range = original_range.start.to_display_point(&display_map)
 2828                        ..original_range.end.to_display_point(&display_map);
 2829                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2830                        ..original_display_range.end.to_point(&display_map);
 2831                    if movement::is_inside_word(&display_map, position)
 2832                        || original_display_range.contains(&position)
 2833                    {
 2834                        let word_range = movement::surrounding_word(&display_map, position);
 2835                        if word_range.start < original_display_range.start {
 2836                            head = word_range.start.to_point(&display_map);
 2837                        } else {
 2838                            head = word_range.end.to_point(&display_map);
 2839                        }
 2840                    } else {
 2841                        head = position.to_point(&display_map);
 2842                    }
 2843
 2844                    if head <= original_buffer_range.start {
 2845                        tail = original_buffer_range.end;
 2846                    } else {
 2847                        tail = original_buffer_range.start;
 2848                    }
 2849                }
 2850                SelectMode::Line(original_range) => {
 2851                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2852
 2853                    let position = display_map
 2854                        .clip_point(position, Bias::Left)
 2855                        .to_point(&display_map);
 2856                    let line_start = display_map.prev_line_boundary(position).0;
 2857                    let next_line_start = buffer.clip_point(
 2858                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2859                        Bias::Left,
 2860                    );
 2861
 2862                    if line_start < original_range.start {
 2863                        head = line_start
 2864                    } else {
 2865                        head = next_line_start
 2866                    }
 2867
 2868                    if head <= original_range.start {
 2869                        tail = original_range.end;
 2870                    } else {
 2871                        tail = original_range.start;
 2872                    }
 2873                }
 2874                SelectMode::All => {
 2875                    return;
 2876                }
 2877            };
 2878
 2879            if head < tail {
 2880                pending.start = buffer.anchor_before(head);
 2881                pending.end = buffer.anchor_before(tail);
 2882                pending.reversed = true;
 2883            } else {
 2884                pending.start = buffer.anchor_before(tail);
 2885                pending.end = buffer.anchor_before(head);
 2886                pending.reversed = false;
 2887            }
 2888
 2889            self.change_selections(None, window, cx, |s| {
 2890                s.set_pending(pending, mode);
 2891            });
 2892        } else {
 2893            log::error!("update_selection dispatched with no pending selection");
 2894            return;
 2895        }
 2896
 2897        self.apply_scroll_delta(scroll_delta, window, cx);
 2898        cx.notify();
 2899    }
 2900
 2901    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2902        self.columnar_selection_tail.take();
 2903        if self.selections.pending_anchor().is_some() {
 2904            let selections = self.selections.all::<usize>(cx);
 2905            self.change_selections(None, window, cx, |s| {
 2906                s.select(selections);
 2907                s.clear_pending();
 2908            });
 2909        }
 2910    }
 2911
 2912    fn select_columns(
 2913        &mut self,
 2914        tail: DisplayPoint,
 2915        head: DisplayPoint,
 2916        goal_column: u32,
 2917        display_map: &DisplaySnapshot,
 2918        window: &mut Window,
 2919        cx: &mut Context<Self>,
 2920    ) {
 2921        let start_row = cmp::min(tail.row(), head.row());
 2922        let end_row = cmp::max(tail.row(), head.row());
 2923        let start_column = cmp::min(tail.column(), goal_column);
 2924        let end_column = cmp::max(tail.column(), goal_column);
 2925        let reversed = start_column < tail.column();
 2926
 2927        let selection_ranges = (start_row.0..=end_row.0)
 2928            .map(DisplayRow)
 2929            .filter_map(|row| {
 2930                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2931                    let start = display_map
 2932                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2933                        .to_point(display_map);
 2934                    let end = display_map
 2935                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2936                        .to_point(display_map);
 2937                    if reversed {
 2938                        Some(end..start)
 2939                    } else {
 2940                        Some(start..end)
 2941                    }
 2942                } else {
 2943                    None
 2944                }
 2945            })
 2946            .collect::<Vec<_>>();
 2947
 2948        self.change_selections(None, window, cx, |s| {
 2949            s.select_ranges(selection_ranges);
 2950        });
 2951        cx.notify();
 2952    }
 2953
 2954    pub fn has_pending_nonempty_selection(&self) -> bool {
 2955        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2956            Some(Selection { start, end, .. }) => start != end,
 2957            None => false,
 2958        };
 2959
 2960        pending_nonempty_selection
 2961            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2962    }
 2963
 2964    pub fn has_pending_selection(&self) -> bool {
 2965        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2966    }
 2967
 2968    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2969        self.selection_mark_mode = false;
 2970
 2971        if self.clear_expanded_diff_hunks(cx) {
 2972            cx.notify();
 2973            return;
 2974        }
 2975        if self.dismiss_menus_and_popups(true, window, cx) {
 2976            return;
 2977        }
 2978
 2979        if self.mode == EditorMode::Full
 2980            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2981        {
 2982            return;
 2983        }
 2984
 2985        cx.propagate();
 2986    }
 2987
 2988    pub fn dismiss_menus_and_popups(
 2989        &mut self,
 2990        is_user_requested: bool,
 2991        window: &mut Window,
 2992        cx: &mut Context<Self>,
 2993    ) -> bool {
 2994        if self.take_rename(false, window, cx).is_some() {
 2995            return true;
 2996        }
 2997
 2998        if hide_hover(self, cx) {
 2999            return true;
 3000        }
 3001
 3002        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3003            return true;
 3004        }
 3005
 3006        if self.hide_context_menu(window, cx).is_some() {
 3007            return true;
 3008        }
 3009
 3010        if self.mouse_context_menu.take().is_some() {
 3011            return true;
 3012        }
 3013
 3014        if is_user_requested && self.discard_inline_completion(true, cx) {
 3015            return true;
 3016        }
 3017
 3018        if self.snippet_stack.pop().is_some() {
 3019            return true;
 3020        }
 3021
 3022        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3023            self.dismiss_diagnostics(cx);
 3024            return true;
 3025        }
 3026
 3027        false
 3028    }
 3029
 3030    fn linked_editing_ranges_for(
 3031        &self,
 3032        selection: Range<text::Anchor>,
 3033        cx: &App,
 3034    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 3035        if self.linked_edit_ranges.is_empty() {
 3036            return None;
 3037        }
 3038        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3039            selection.end.buffer_id.and_then(|end_buffer_id| {
 3040                if selection.start.buffer_id != Some(end_buffer_id) {
 3041                    return None;
 3042                }
 3043                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3044                let snapshot = buffer.read(cx).snapshot();
 3045                self.linked_edit_ranges
 3046                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3047                    .map(|ranges| (ranges, snapshot, buffer))
 3048            })?;
 3049        use text::ToOffset as TO;
 3050        // find offset from the start of current range to current cursor position
 3051        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3052
 3053        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3054        let start_difference = start_offset - start_byte_offset;
 3055        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3056        let end_difference = end_offset - start_byte_offset;
 3057        // Current range has associated linked ranges.
 3058        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3059        for range in linked_ranges.iter() {
 3060            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3061            let end_offset = start_offset + end_difference;
 3062            let start_offset = start_offset + start_difference;
 3063            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3064                continue;
 3065            }
 3066            if self.selections.disjoint_anchor_ranges().any(|s| {
 3067                if s.start.buffer_id != selection.start.buffer_id
 3068                    || s.end.buffer_id != selection.end.buffer_id
 3069                {
 3070                    return false;
 3071                }
 3072                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3073                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3074            }) {
 3075                continue;
 3076            }
 3077            let start = buffer_snapshot.anchor_after(start_offset);
 3078            let end = buffer_snapshot.anchor_after(end_offset);
 3079            linked_edits
 3080                .entry(buffer.clone())
 3081                .or_default()
 3082                .push(start..end);
 3083        }
 3084        Some(linked_edits)
 3085    }
 3086
 3087    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3088        let text: Arc<str> = text.into();
 3089
 3090        if self.read_only(cx) {
 3091            return;
 3092        }
 3093
 3094        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3095
 3096        let selections = self.selections.all_adjusted(cx);
 3097        let mut bracket_inserted = false;
 3098        let mut edits = Vec::new();
 3099        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3100        let mut new_selections = Vec::with_capacity(selections.len());
 3101        let mut new_autoclose_regions = Vec::new();
 3102        let snapshot = self.buffer.read(cx).read(cx);
 3103
 3104        for (selection, autoclose_region) in
 3105            self.selections_with_autoclose_regions(selections, &snapshot)
 3106        {
 3107            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3108                // Determine if the inserted text matches the opening or closing
 3109                // bracket of any of this language's bracket pairs.
 3110                let mut bracket_pair = None;
 3111                let mut is_bracket_pair_start = false;
 3112                let mut is_bracket_pair_end = false;
 3113                if !text.is_empty() {
 3114                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3115                    //  and they are removing the character that triggered IME popup.
 3116                    for (pair, enabled) in scope.brackets() {
 3117                        if !pair.close && !pair.surround {
 3118                            continue;
 3119                        }
 3120
 3121                        if enabled && pair.start.ends_with(text.as_ref()) {
 3122                            let prefix_len = pair.start.len() - text.len();
 3123                            let preceding_text_matches_prefix = prefix_len == 0
 3124                                || (selection.start.column >= (prefix_len as u32)
 3125                                    && snapshot.contains_str_at(
 3126                                        Point::new(
 3127                                            selection.start.row,
 3128                                            selection.start.column - (prefix_len as u32),
 3129                                        ),
 3130                                        &pair.start[..prefix_len],
 3131                                    ));
 3132                            if preceding_text_matches_prefix {
 3133                                bracket_pair = Some(pair.clone());
 3134                                is_bracket_pair_start = true;
 3135                                break;
 3136                            }
 3137                        }
 3138                        if pair.end.as_str() == text.as_ref() {
 3139                            bracket_pair = Some(pair.clone());
 3140                            is_bracket_pair_end = true;
 3141                            break;
 3142                        }
 3143                    }
 3144                }
 3145
 3146                if let Some(bracket_pair) = bracket_pair {
 3147                    let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
 3148                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3149                    let auto_surround =
 3150                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3151                    if selection.is_empty() {
 3152                        if is_bracket_pair_start {
 3153                            // If the inserted text is a suffix of an opening bracket and the
 3154                            // selection is preceded by the rest of the opening bracket, then
 3155                            // insert the closing bracket.
 3156                            let following_text_allows_autoclose = snapshot
 3157                                .chars_at(selection.start)
 3158                                .next()
 3159                                .map_or(true, |c| scope.should_autoclose_before(c));
 3160
 3161                            let preceding_text_allows_autoclose = selection.start.column == 0
 3162                                || snapshot.reversed_chars_at(selection.start).next().map_or(
 3163                                    true,
 3164                                    |c| {
 3165                                        bracket_pair.start != bracket_pair.end
 3166                                            || !snapshot
 3167                                                .char_classifier_at(selection.start)
 3168                                                .is_word(c)
 3169                                    },
 3170                                );
 3171
 3172                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 3173                                && bracket_pair.start.len() == 1
 3174                            {
 3175                                let target = bracket_pair.start.chars().next().unwrap();
 3176                                let current_line_count = snapshot
 3177                                    .reversed_chars_at(selection.start)
 3178                                    .take_while(|&c| c != '\n')
 3179                                    .filter(|&c| c == target)
 3180                                    .count();
 3181                                current_line_count % 2 == 1
 3182                            } else {
 3183                                false
 3184                            };
 3185
 3186                            if autoclose
 3187                                && bracket_pair.close
 3188                                && following_text_allows_autoclose
 3189                                && preceding_text_allows_autoclose
 3190                                && !is_closing_quote
 3191                            {
 3192                                let anchor = snapshot.anchor_before(selection.end);
 3193                                new_selections.push((selection.map(|_| anchor), text.len()));
 3194                                new_autoclose_regions.push((
 3195                                    anchor,
 3196                                    text.len(),
 3197                                    selection.id,
 3198                                    bracket_pair.clone(),
 3199                                ));
 3200                                edits.push((
 3201                                    selection.range(),
 3202                                    format!("{}{}", text, bracket_pair.end).into(),
 3203                                ));
 3204                                bracket_inserted = true;
 3205                                continue;
 3206                            }
 3207                        }
 3208
 3209                        if let Some(region) = autoclose_region {
 3210                            // If the selection is followed by an auto-inserted closing bracket,
 3211                            // then don't insert that closing bracket again; just move the selection
 3212                            // past the closing bracket.
 3213                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3214                                && text.as_ref() == region.pair.end.as_str();
 3215                            if should_skip {
 3216                                let anchor = snapshot.anchor_after(selection.end);
 3217                                new_selections
 3218                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3219                                continue;
 3220                            }
 3221                        }
 3222
 3223                        let always_treat_brackets_as_autoclosed = snapshot
 3224                            .language_settings_at(selection.start, cx)
 3225                            .always_treat_brackets_as_autoclosed;
 3226                        if always_treat_brackets_as_autoclosed
 3227                            && is_bracket_pair_end
 3228                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3229                        {
 3230                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3231                            // and the inserted text is a closing bracket and the selection is followed
 3232                            // by the closing bracket then move the selection past the closing bracket.
 3233                            let anchor = snapshot.anchor_after(selection.end);
 3234                            new_selections.push((selection.map(|_| anchor), text.len()));
 3235                            continue;
 3236                        }
 3237                    }
 3238                    // If an opening bracket is 1 character long and is typed while
 3239                    // text is selected, then surround that text with the bracket pair.
 3240                    else if auto_surround
 3241                        && bracket_pair.surround
 3242                        && is_bracket_pair_start
 3243                        && bracket_pair.start.chars().count() == 1
 3244                    {
 3245                        edits.push((selection.start..selection.start, text.clone()));
 3246                        edits.push((
 3247                            selection.end..selection.end,
 3248                            bracket_pair.end.as_str().into(),
 3249                        ));
 3250                        bracket_inserted = true;
 3251                        new_selections.push((
 3252                            Selection {
 3253                                id: selection.id,
 3254                                start: snapshot.anchor_after(selection.start),
 3255                                end: snapshot.anchor_before(selection.end),
 3256                                reversed: selection.reversed,
 3257                                goal: selection.goal,
 3258                            },
 3259                            0,
 3260                        ));
 3261                        continue;
 3262                    }
 3263                }
 3264            }
 3265
 3266            if self.auto_replace_emoji_shortcode
 3267                && selection.is_empty()
 3268                && text.as_ref().ends_with(':')
 3269            {
 3270                if let Some(possible_emoji_short_code) =
 3271                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3272                {
 3273                    if !possible_emoji_short_code.is_empty() {
 3274                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3275                            let emoji_shortcode_start = Point::new(
 3276                                selection.start.row,
 3277                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3278                            );
 3279
 3280                            // Remove shortcode from buffer
 3281                            edits.push((
 3282                                emoji_shortcode_start..selection.start,
 3283                                "".to_string().into(),
 3284                            ));
 3285                            new_selections.push((
 3286                                Selection {
 3287                                    id: selection.id,
 3288                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3289                                    end: snapshot.anchor_before(selection.start),
 3290                                    reversed: selection.reversed,
 3291                                    goal: selection.goal,
 3292                                },
 3293                                0,
 3294                            ));
 3295
 3296                            // Insert emoji
 3297                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3298                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3299                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3300
 3301                            continue;
 3302                        }
 3303                    }
 3304                }
 3305            }
 3306
 3307            // If not handling any auto-close operation, then just replace the selected
 3308            // text with the given input and move the selection to the end of the
 3309            // newly inserted text.
 3310            let anchor = snapshot.anchor_after(selection.end);
 3311            if !self.linked_edit_ranges.is_empty() {
 3312                let start_anchor = snapshot.anchor_before(selection.start);
 3313
 3314                let is_word_char = text.chars().next().map_or(true, |char| {
 3315                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3316                    classifier.is_word(char)
 3317                });
 3318
 3319                if is_word_char {
 3320                    if let Some(ranges) = self
 3321                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3322                    {
 3323                        for (buffer, edits) in ranges {
 3324                            linked_edits
 3325                                .entry(buffer.clone())
 3326                                .or_default()
 3327                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3328                        }
 3329                    }
 3330                }
 3331            }
 3332
 3333            new_selections.push((selection.map(|_| anchor), 0));
 3334            edits.push((selection.start..selection.end, text.clone()));
 3335        }
 3336
 3337        drop(snapshot);
 3338
 3339        self.transact(window, cx, |this, window, cx| {
 3340            let initial_buffer_versions =
 3341                jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
 3342
 3343            this.buffer.update(cx, |buffer, cx| {
 3344                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3345            });
 3346            for (buffer, edits) in linked_edits {
 3347                buffer.update(cx, |buffer, cx| {
 3348                    let snapshot = buffer.snapshot();
 3349                    let edits = edits
 3350                        .into_iter()
 3351                        .map(|(range, text)| {
 3352                            use text::ToPoint as TP;
 3353                            let end_point = TP::to_point(&range.end, &snapshot);
 3354                            let start_point = TP::to_point(&range.start, &snapshot);
 3355                            (start_point..end_point, text)
 3356                        })
 3357                        .sorted_by_key(|(range, _)| range.start);
 3358                    buffer.edit(edits, None, cx);
 3359                })
 3360            }
 3361            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3362            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3363            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3364            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3365                .zip(new_selection_deltas)
 3366                .map(|(selection, delta)| Selection {
 3367                    id: selection.id,
 3368                    start: selection.start + delta,
 3369                    end: selection.end + delta,
 3370                    reversed: selection.reversed,
 3371                    goal: SelectionGoal::None,
 3372                })
 3373                .collect::<Vec<_>>();
 3374
 3375            let mut i = 0;
 3376            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3377                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3378                let start = map.buffer_snapshot.anchor_before(position);
 3379                let end = map.buffer_snapshot.anchor_after(position);
 3380                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3381                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3382                        Ordering::Less => i += 1,
 3383                        Ordering::Greater => break,
 3384                        Ordering::Equal => {
 3385                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3386                                Ordering::Less => i += 1,
 3387                                Ordering::Equal => break,
 3388                                Ordering::Greater => break,
 3389                            }
 3390                        }
 3391                    }
 3392                }
 3393                this.autoclose_regions.insert(
 3394                    i,
 3395                    AutocloseRegion {
 3396                        selection_id,
 3397                        range: start..end,
 3398                        pair,
 3399                    },
 3400                );
 3401            }
 3402
 3403            let had_active_inline_completion = this.has_active_inline_completion();
 3404            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3405                s.select(new_selections)
 3406            });
 3407
 3408            if !bracket_inserted {
 3409                if let Some(on_type_format_task) =
 3410                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3411                {
 3412                    on_type_format_task.detach_and_log_err(cx);
 3413                }
 3414            }
 3415
 3416            let editor_settings = EditorSettings::get_global(cx);
 3417            if bracket_inserted
 3418                && (editor_settings.auto_signature_help
 3419                    || editor_settings.show_signature_help_after_edits)
 3420            {
 3421                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3422            }
 3423
 3424            let trigger_in_words =
 3425                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3426            if this.hard_wrap.is_some() {
 3427                let latest: Range<Point> = this.selections.newest(cx).range();
 3428                if latest.is_empty()
 3429                    && this
 3430                        .buffer()
 3431                        .read(cx)
 3432                        .snapshot(cx)
 3433                        .line_len(MultiBufferRow(latest.start.row))
 3434                        == latest.start.column
 3435                {
 3436                    this.rewrap_impl(
 3437                        RewrapOptions {
 3438                            override_language_settings: true,
 3439                            preserve_existing_whitespace: true,
 3440                        },
 3441                        cx,
 3442                    )
 3443                }
 3444            }
 3445            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3446            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3447            this.refresh_inline_completion(true, false, window, cx);
 3448            jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
 3449        });
 3450    }
 3451
 3452    fn find_possible_emoji_shortcode_at_position(
 3453        snapshot: &MultiBufferSnapshot,
 3454        position: Point,
 3455    ) -> Option<String> {
 3456        let mut chars = Vec::new();
 3457        let mut found_colon = false;
 3458        for char in snapshot.reversed_chars_at(position).take(100) {
 3459            // Found a possible emoji shortcode in the middle of the buffer
 3460            if found_colon {
 3461                if char.is_whitespace() {
 3462                    chars.reverse();
 3463                    return Some(chars.iter().collect());
 3464                }
 3465                // If the previous character is not a whitespace, we are in the middle of a word
 3466                // and we only want to complete the shortcode if the word is made up of other emojis
 3467                let mut containing_word = String::new();
 3468                for ch in snapshot
 3469                    .reversed_chars_at(position)
 3470                    .skip(chars.len() + 1)
 3471                    .take(100)
 3472                {
 3473                    if ch.is_whitespace() {
 3474                        break;
 3475                    }
 3476                    containing_word.push(ch);
 3477                }
 3478                let containing_word = containing_word.chars().rev().collect::<String>();
 3479                if util::word_consists_of_emojis(containing_word.as_str()) {
 3480                    chars.reverse();
 3481                    return Some(chars.iter().collect());
 3482                }
 3483            }
 3484
 3485            if char.is_whitespace() || !char.is_ascii() {
 3486                return None;
 3487            }
 3488            if char == ':' {
 3489                found_colon = true;
 3490            } else {
 3491                chars.push(char);
 3492            }
 3493        }
 3494        // Found a possible emoji shortcode at the beginning of the buffer
 3495        chars.reverse();
 3496        Some(chars.iter().collect())
 3497    }
 3498
 3499    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3500        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3501        self.transact(window, cx, |this, window, cx| {
 3502            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3503                let selections = this.selections.all::<usize>(cx);
 3504                let multi_buffer = this.buffer.read(cx);
 3505                let buffer = multi_buffer.snapshot(cx);
 3506                selections
 3507                    .iter()
 3508                    .map(|selection| {
 3509                        let start_point = selection.start.to_point(&buffer);
 3510                        let mut indent =
 3511                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3512                        indent.len = cmp::min(indent.len, start_point.column);
 3513                        let start = selection.start;
 3514                        let end = selection.end;
 3515                        let selection_is_empty = start == end;
 3516                        let language_scope = buffer.language_scope_at(start);
 3517                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3518                            &language_scope
 3519                        {
 3520                            let insert_extra_newline =
 3521                                insert_extra_newline_brackets(&buffer, start..end, language)
 3522                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3523
 3524                            // Comment extension on newline is allowed only for cursor selections
 3525                            let comment_delimiter = maybe!({
 3526                                if !selection_is_empty {
 3527                                    return None;
 3528                                }
 3529
 3530                                if !multi_buffer.language_settings(cx).extend_comment_on_newline {
 3531                                    return None;
 3532                                }
 3533
 3534                                let delimiters = language.line_comment_prefixes();
 3535                                let max_len_of_delimiter =
 3536                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3537                                let (snapshot, range) =
 3538                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3539
 3540                                let mut index_of_first_non_whitespace = 0;
 3541                                let comment_candidate = snapshot
 3542                                    .chars_for_range(range)
 3543                                    .skip_while(|c| {
 3544                                        let should_skip = c.is_whitespace();
 3545                                        if should_skip {
 3546                                            index_of_first_non_whitespace += 1;
 3547                                        }
 3548                                        should_skip
 3549                                    })
 3550                                    .take(max_len_of_delimiter)
 3551                                    .collect::<String>();
 3552                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3553                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3554                                })?;
 3555                                let cursor_is_placed_after_comment_marker =
 3556                                    index_of_first_non_whitespace + comment_prefix.len()
 3557                                        <= start_point.column as usize;
 3558                                if cursor_is_placed_after_comment_marker {
 3559                                    Some(comment_prefix.clone())
 3560                                } else {
 3561                                    None
 3562                                }
 3563                            });
 3564                            (comment_delimiter, insert_extra_newline)
 3565                        } else {
 3566                            (None, false)
 3567                        };
 3568
 3569                        let capacity_for_delimiter = comment_delimiter
 3570                            .as_deref()
 3571                            .map(str::len)
 3572                            .unwrap_or_default();
 3573                        let mut new_text =
 3574                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3575                        new_text.push('\n');
 3576                        new_text.extend(indent.chars());
 3577                        if let Some(delimiter) = &comment_delimiter {
 3578                            new_text.push_str(delimiter);
 3579                        }
 3580                        if insert_extra_newline {
 3581                            new_text = new_text.repeat(2);
 3582                        }
 3583
 3584                        let anchor = buffer.anchor_after(end);
 3585                        let new_selection = selection.map(|_| anchor);
 3586                        (
 3587                            (start..end, new_text),
 3588                            (insert_extra_newline, new_selection),
 3589                        )
 3590                    })
 3591                    .unzip()
 3592            };
 3593
 3594            this.edit_with_autoindent(edits, cx);
 3595            let buffer = this.buffer.read(cx).snapshot(cx);
 3596            let new_selections = selection_fixup_info
 3597                .into_iter()
 3598                .map(|(extra_newline_inserted, new_selection)| {
 3599                    let mut cursor = new_selection.end.to_point(&buffer);
 3600                    if extra_newline_inserted {
 3601                        cursor.row -= 1;
 3602                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3603                    }
 3604                    new_selection.map(|_| cursor)
 3605                })
 3606                .collect();
 3607
 3608            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3609                s.select(new_selections)
 3610            });
 3611            this.refresh_inline_completion(true, false, window, cx);
 3612        });
 3613    }
 3614
 3615    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3616        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3617
 3618        let buffer = self.buffer.read(cx);
 3619        let snapshot = buffer.snapshot(cx);
 3620
 3621        let mut edits = Vec::new();
 3622        let mut rows = Vec::new();
 3623
 3624        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3625            let cursor = selection.head();
 3626            let row = cursor.row;
 3627
 3628            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3629
 3630            let newline = "\n".to_string();
 3631            edits.push((start_of_line..start_of_line, newline));
 3632
 3633            rows.push(row + rows_inserted as u32);
 3634        }
 3635
 3636        self.transact(window, cx, |editor, window, cx| {
 3637            editor.edit(edits, cx);
 3638
 3639            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3640                let mut index = 0;
 3641                s.move_cursors_with(|map, _, _| {
 3642                    let row = rows[index];
 3643                    index += 1;
 3644
 3645                    let point = Point::new(row, 0);
 3646                    let boundary = map.next_line_boundary(point).1;
 3647                    let clipped = map.clip_point(boundary, Bias::Left);
 3648
 3649                    (clipped, SelectionGoal::None)
 3650                });
 3651            });
 3652
 3653            let mut indent_edits = Vec::new();
 3654            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3655            for row in rows {
 3656                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3657                for (row, indent) in indents {
 3658                    if indent.len == 0 {
 3659                        continue;
 3660                    }
 3661
 3662                    let text = match indent.kind {
 3663                        IndentKind::Space => " ".repeat(indent.len as usize),
 3664                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3665                    };
 3666                    let point = Point::new(row.0, 0);
 3667                    indent_edits.push((point..point, text));
 3668                }
 3669            }
 3670            editor.edit(indent_edits, cx);
 3671        });
 3672    }
 3673
 3674    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3675        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 3676
 3677        let buffer = self.buffer.read(cx);
 3678        let snapshot = buffer.snapshot(cx);
 3679
 3680        let mut edits = Vec::new();
 3681        let mut rows = Vec::new();
 3682        let mut rows_inserted = 0;
 3683
 3684        for selection in self.selections.all_adjusted(cx) {
 3685            let cursor = selection.head();
 3686            let row = cursor.row;
 3687
 3688            let point = Point::new(row + 1, 0);
 3689            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3690
 3691            let newline = "\n".to_string();
 3692            edits.push((start_of_line..start_of_line, newline));
 3693
 3694            rows_inserted += 1;
 3695            rows.push(row + rows_inserted);
 3696        }
 3697
 3698        self.transact(window, cx, |editor, window, cx| {
 3699            editor.edit(edits, cx);
 3700
 3701            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3702                let mut index = 0;
 3703                s.move_cursors_with(|map, _, _| {
 3704                    let row = rows[index];
 3705                    index += 1;
 3706
 3707                    let point = Point::new(row, 0);
 3708                    let boundary = map.next_line_boundary(point).1;
 3709                    let clipped = map.clip_point(boundary, Bias::Left);
 3710
 3711                    (clipped, SelectionGoal::None)
 3712                });
 3713            });
 3714
 3715            let mut indent_edits = Vec::new();
 3716            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3717            for row in rows {
 3718                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3719                for (row, indent) in indents {
 3720                    if indent.len == 0 {
 3721                        continue;
 3722                    }
 3723
 3724                    let text = match indent.kind {
 3725                        IndentKind::Space => " ".repeat(indent.len as usize),
 3726                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3727                    };
 3728                    let point = Point::new(row.0, 0);
 3729                    indent_edits.push((point..point, text));
 3730                }
 3731            }
 3732            editor.edit(indent_edits, cx);
 3733        });
 3734    }
 3735
 3736    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3737        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3738            original_indent_columns: Vec::new(),
 3739        });
 3740        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3741    }
 3742
 3743    fn insert_with_autoindent_mode(
 3744        &mut self,
 3745        text: &str,
 3746        autoindent_mode: Option<AutoindentMode>,
 3747        window: &mut Window,
 3748        cx: &mut Context<Self>,
 3749    ) {
 3750        if self.read_only(cx) {
 3751            return;
 3752        }
 3753
 3754        let text: Arc<str> = text.into();
 3755        self.transact(window, cx, |this, window, cx| {
 3756            let old_selections = this.selections.all_adjusted(cx);
 3757            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3758                let anchors = {
 3759                    let snapshot = buffer.read(cx);
 3760                    old_selections
 3761                        .iter()
 3762                        .map(|s| {
 3763                            let anchor = snapshot.anchor_after(s.head());
 3764                            s.map(|_| anchor)
 3765                        })
 3766                        .collect::<Vec<_>>()
 3767                };
 3768                buffer.edit(
 3769                    old_selections
 3770                        .iter()
 3771                        .map(|s| (s.start..s.end, text.clone())),
 3772                    autoindent_mode,
 3773                    cx,
 3774                );
 3775                anchors
 3776            });
 3777
 3778            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3779                s.select_anchors(selection_anchors);
 3780            });
 3781
 3782            cx.notify();
 3783        });
 3784    }
 3785
 3786    fn trigger_completion_on_input(
 3787        &mut self,
 3788        text: &str,
 3789        trigger_in_words: bool,
 3790        window: &mut Window,
 3791        cx: &mut Context<Self>,
 3792    ) {
 3793        let ignore_completion_provider = self
 3794            .context_menu
 3795            .borrow()
 3796            .as_ref()
 3797            .map(|menu| match menu {
 3798                CodeContextMenu::Completions(completions_menu) => {
 3799                    completions_menu.ignore_completion_provider
 3800                }
 3801                CodeContextMenu::CodeActions(_) => false,
 3802            })
 3803            .unwrap_or(false);
 3804
 3805        if ignore_completion_provider {
 3806            self.show_word_completions(&ShowWordCompletions, window, cx);
 3807        } else if self.is_completion_trigger(text, trigger_in_words, cx) {
 3808            self.show_completions(
 3809                &ShowCompletions {
 3810                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3811                },
 3812                window,
 3813                cx,
 3814            );
 3815        } else {
 3816            self.hide_context_menu(window, cx);
 3817        }
 3818    }
 3819
 3820    fn is_completion_trigger(
 3821        &self,
 3822        text: &str,
 3823        trigger_in_words: bool,
 3824        cx: &mut Context<Self>,
 3825    ) -> bool {
 3826        let position = self.selections.newest_anchor().head();
 3827        let multibuffer = self.buffer.read(cx);
 3828        let Some(buffer) = position
 3829            .buffer_id
 3830            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3831        else {
 3832            return false;
 3833        };
 3834
 3835        if let Some(completion_provider) = &self.completion_provider {
 3836            completion_provider.is_completion_trigger(
 3837                &buffer,
 3838                position.text_anchor,
 3839                text,
 3840                trigger_in_words,
 3841                cx,
 3842            )
 3843        } else {
 3844            false
 3845        }
 3846    }
 3847
 3848    /// If any empty selections is touching the start of its innermost containing autoclose
 3849    /// region, expand it to select the brackets.
 3850    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3851        let selections = self.selections.all::<usize>(cx);
 3852        let buffer = self.buffer.read(cx).read(cx);
 3853        let new_selections = self
 3854            .selections_with_autoclose_regions(selections, &buffer)
 3855            .map(|(mut selection, region)| {
 3856                if !selection.is_empty() {
 3857                    return selection;
 3858                }
 3859
 3860                if let Some(region) = region {
 3861                    let mut range = region.range.to_offset(&buffer);
 3862                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3863                        range.start -= region.pair.start.len();
 3864                        if buffer.contains_str_at(range.start, &region.pair.start)
 3865                            && buffer.contains_str_at(range.end, &region.pair.end)
 3866                        {
 3867                            range.end += region.pair.end.len();
 3868                            selection.start = range.start;
 3869                            selection.end = range.end;
 3870
 3871                            return selection;
 3872                        }
 3873                    }
 3874                }
 3875
 3876                let always_treat_brackets_as_autoclosed = buffer
 3877                    .language_settings_at(selection.start, cx)
 3878                    .always_treat_brackets_as_autoclosed;
 3879
 3880                if !always_treat_brackets_as_autoclosed {
 3881                    return selection;
 3882                }
 3883
 3884                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3885                    for (pair, enabled) in scope.brackets() {
 3886                        if !enabled || !pair.close {
 3887                            continue;
 3888                        }
 3889
 3890                        if buffer.contains_str_at(selection.start, &pair.end) {
 3891                            let pair_start_len = pair.start.len();
 3892                            if buffer.contains_str_at(
 3893                                selection.start.saturating_sub(pair_start_len),
 3894                                &pair.start,
 3895                            ) {
 3896                                selection.start -= pair_start_len;
 3897                                selection.end += pair.end.len();
 3898
 3899                                return selection;
 3900                            }
 3901                        }
 3902                    }
 3903                }
 3904
 3905                selection
 3906            })
 3907            .collect();
 3908
 3909        drop(buffer);
 3910        self.change_selections(None, window, cx, |selections| {
 3911            selections.select(new_selections)
 3912        });
 3913    }
 3914
 3915    /// Iterate the given selections, and for each one, find the smallest surrounding
 3916    /// autoclose region. This uses the ordering of the selections and the autoclose
 3917    /// regions to avoid repeated comparisons.
 3918    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3919        &'a self,
 3920        selections: impl IntoIterator<Item = Selection<D>>,
 3921        buffer: &'a MultiBufferSnapshot,
 3922    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3923        let mut i = 0;
 3924        let mut regions = self.autoclose_regions.as_slice();
 3925        selections.into_iter().map(move |selection| {
 3926            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3927
 3928            let mut enclosing = None;
 3929            while let Some(pair_state) = regions.get(i) {
 3930                if pair_state.range.end.to_offset(buffer) < range.start {
 3931                    regions = &regions[i + 1..];
 3932                    i = 0;
 3933                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3934                    break;
 3935                } else {
 3936                    if pair_state.selection_id == selection.id {
 3937                        enclosing = Some(pair_state);
 3938                    }
 3939                    i += 1;
 3940                }
 3941            }
 3942
 3943            (selection, enclosing)
 3944        })
 3945    }
 3946
 3947    /// Remove any autoclose regions that no longer contain their selection.
 3948    fn invalidate_autoclose_regions(
 3949        &mut self,
 3950        mut selections: &[Selection<Anchor>],
 3951        buffer: &MultiBufferSnapshot,
 3952    ) {
 3953        self.autoclose_regions.retain(|state| {
 3954            let mut i = 0;
 3955            while let Some(selection) = selections.get(i) {
 3956                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3957                    selections = &selections[1..];
 3958                    continue;
 3959                }
 3960                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3961                    break;
 3962                }
 3963                if selection.id == state.selection_id {
 3964                    return true;
 3965                } else {
 3966                    i += 1;
 3967                }
 3968            }
 3969            false
 3970        });
 3971    }
 3972
 3973    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3974        let offset = position.to_offset(buffer);
 3975        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3976        if offset > word_range.start && kind == Some(CharKind::Word) {
 3977            Some(
 3978                buffer
 3979                    .text_for_range(word_range.start..offset)
 3980                    .collect::<String>(),
 3981            )
 3982        } else {
 3983            None
 3984        }
 3985    }
 3986
 3987    pub fn toggle_inlay_hints(
 3988        &mut self,
 3989        _: &ToggleInlayHints,
 3990        _: &mut Window,
 3991        cx: &mut Context<Self>,
 3992    ) {
 3993        self.refresh_inlay_hints(
 3994            InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
 3995            cx,
 3996        );
 3997    }
 3998
 3999    pub fn inlay_hints_enabled(&self) -> bool {
 4000        self.inlay_hint_cache.enabled
 4001    }
 4002
 4003    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 4004        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 4005            return;
 4006        }
 4007
 4008        let reason_description = reason.description();
 4009        let ignore_debounce = matches!(
 4010            reason,
 4011            InlayHintRefreshReason::SettingsChange(_)
 4012                | InlayHintRefreshReason::Toggle(_)
 4013                | InlayHintRefreshReason::ExcerptsRemoved(_)
 4014                | InlayHintRefreshReason::ModifiersChanged(_)
 4015        );
 4016        let (invalidate_cache, required_languages) = match reason {
 4017            InlayHintRefreshReason::ModifiersChanged(enabled) => {
 4018                match self.inlay_hint_cache.modifiers_override(enabled) {
 4019                    Some(enabled) => {
 4020                        if enabled {
 4021                            (InvalidationStrategy::RefreshRequested, None)
 4022                        } else {
 4023                            self.splice_inlays(
 4024                                &self
 4025                                    .visible_inlay_hints(cx)
 4026                                    .iter()
 4027                                    .map(|inlay| inlay.id)
 4028                                    .collect::<Vec<InlayId>>(),
 4029                                Vec::new(),
 4030                                cx,
 4031                            );
 4032                            return;
 4033                        }
 4034                    }
 4035                    None => return,
 4036                }
 4037            }
 4038            InlayHintRefreshReason::Toggle(enabled) => {
 4039                if self.inlay_hint_cache.toggle(enabled) {
 4040                    if enabled {
 4041                        (InvalidationStrategy::RefreshRequested, None)
 4042                    } else {
 4043                        self.splice_inlays(
 4044                            &self
 4045                                .visible_inlay_hints(cx)
 4046                                .iter()
 4047                                .map(|inlay| inlay.id)
 4048                                .collect::<Vec<InlayId>>(),
 4049                            Vec::new(),
 4050                            cx,
 4051                        );
 4052                        return;
 4053                    }
 4054                } else {
 4055                    return;
 4056                }
 4057            }
 4058            InlayHintRefreshReason::SettingsChange(new_settings) => {
 4059                match self.inlay_hint_cache.update_settings(
 4060                    &self.buffer,
 4061                    new_settings,
 4062                    self.visible_inlay_hints(cx),
 4063                    cx,
 4064                ) {
 4065                    ControlFlow::Break(Some(InlaySplice {
 4066                        to_remove,
 4067                        to_insert,
 4068                    })) => {
 4069                        self.splice_inlays(&to_remove, to_insert, cx);
 4070                        return;
 4071                    }
 4072                    ControlFlow::Break(None) => return,
 4073                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4074                }
 4075            }
 4076            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4077                if let Some(InlaySplice {
 4078                    to_remove,
 4079                    to_insert,
 4080                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4081                {
 4082                    self.splice_inlays(&to_remove, to_insert, cx);
 4083                }
 4084                return;
 4085            }
 4086            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4087            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4088                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4089            }
 4090            InlayHintRefreshReason::RefreshRequested => {
 4091                (InvalidationStrategy::RefreshRequested, None)
 4092            }
 4093        };
 4094
 4095        if let Some(InlaySplice {
 4096            to_remove,
 4097            to_insert,
 4098        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4099            reason_description,
 4100            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4101            invalidate_cache,
 4102            ignore_debounce,
 4103            cx,
 4104        ) {
 4105            self.splice_inlays(&to_remove, to_insert, cx);
 4106        }
 4107    }
 4108
 4109    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 4110        self.display_map
 4111            .read(cx)
 4112            .current_inlays()
 4113            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4114            .cloned()
 4115            .collect()
 4116    }
 4117
 4118    pub fn excerpts_for_inlay_hints_query(
 4119        &self,
 4120        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4121        cx: &mut Context<Editor>,
 4122    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 4123        let Some(project) = self.project.as_ref() else {
 4124            return HashMap::default();
 4125        };
 4126        let project = project.read(cx);
 4127        let multi_buffer = self.buffer().read(cx);
 4128        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4129        let multi_buffer_visible_start = self
 4130            .scroll_manager
 4131            .anchor()
 4132            .anchor
 4133            .to_point(&multi_buffer_snapshot);
 4134        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4135            multi_buffer_visible_start
 4136                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4137            Bias::Left,
 4138        );
 4139        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4140        multi_buffer_snapshot
 4141            .range_to_buffer_ranges(multi_buffer_visible_range)
 4142            .into_iter()
 4143            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4144            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 4145                let buffer_file = project::File::from_dyn(buffer.file())?;
 4146                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4147                let worktree_entry = buffer_worktree
 4148                    .read(cx)
 4149                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4150                if worktree_entry.is_ignored {
 4151                    return None;
 4152                }
 4153
 4154                let language = buffer.language()?;
 4155                if let Some(restrict_to_languages) = restrict_to_languages {
 4156                    if !restrict_to_languages.contains(language) {
 4157                        return None;
 4158                    }
 4159                }
 4160                Some((
 4161                    excerpt_id,
 4162                    (
 4163                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 4164                        buffer.version().clone(),
 4165                        excerpt_visible_range,
 4166                    ),
 4167                ))
 4168            })
 4169            .collect()
 4170    }
 4171
 4172    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 4173        TextLayoutDetails {
 4174            text_system: window.text_system().clone(),
 4175            editor_style: self.style.clone().unwrap(),
 4176            rem_size: window.rem_size(),
 4177            scroll_anchor: self.scroll_manager.anchor(),
 4178            visible_rows: self.visible_line_count(),
 4179            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4180        }
 4181    }
 4182
 4183    pub fn splice_inlays(
 4184        &self,
 4185        to_remove: &[InlayId],
 4186        to_insert: Vec<Inlay>,
 4187        cx: &mut Context<Self>,
 4188    ) {
 4189        self.display_map.update(cx, |display_map, cx| {
 4190            display_map.splice_inlays(to_remove, to_insert, cx)
 4191        });
 4192        cx.notify();
 4193    }
 4194
 4195    fn trigger_on_type_formatting(
 4196        &self,
 4197        input: String,
 4198        window: &mut Window,
 4199        cx: &mut Context<Self>,
 4200    ) -> Option<Task<Result<()>>> {
 4201        if input.len() != 1 {
 4202            return None;
 4203        }
 4204
 4205        let project = self.project.as_ref()?;
 4206        let position = self.selections.newest_anchor().head();
 4207        let (buffer, buffer_position) = self
 4208            .buffer
 4209            .read(cx)
 4210            .text_anchor_for_position(position, cx)?;
 4211
 4212        let settings = language_settings::language_settings(
 4213            buffer
 4214                .read(cx)
 4215                .language_at(buffer_position)
 4216                .map(|l| l.name()),
 4217            buffer.read(cx).file(),
 4218            cx,
 4219        );
 4220        if !settings.use_on_type_format {
 4221            return None;
 4222        }
 4223
 4224        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4225        // hence we do LSP request & edit on host side only — add formats to host's history.
 4226        let push_to_lsp_host_history = true;
 4227        // If this is not the host, append its history with new edits.
 4228        let push_to_client_history = project.read(cx).is_via_collab();
 4229
 4230        let on_type_formatting = project.update(cx, |project, cx| {
 4231            project.on_type_format(
 4232                buffer.clone(),
 4233                buffer_position,
 4234                input,
 4235                push_to_lsp_host_history,
 4236                cx,
 4237            )
 4238        });
 4239        Some(cx.spawn_in(window, async move |editor, cx| {
 4240            if let Some(transaction) = on_type_formatting.await? {
 4241                if push_to_client_history {
 4242                    buffer
 4243                        .update(cx, |buffer, _| {
 4244                            buffer.push_transaction(transaction, Instant::now());
 4245                        })
 4246                        .ok();
 4247                }
 4248                editor.update(cx, |editor, cx| {
 4249                    editor.refresh_document_highlights(cx);
 4250                })?;
 4251            }
 4252            Ok(())
 4253        }))
 4254    }
 4255
 4256    pub fn show_word_completions(
 4257        &mut self,
 4258        _: &ShowWordCompletions,
 4259        window: &mut Window,
 4260        cx: &mut Context<Self>,
 4261    ) {
 4262        self.open_completions_menu(true, None, window, cx);
 4263    }
 4264
 4265    pub fn show_completions(
 4266        &mut self,
 4267        options: &ShowCompletions,
 4268        window: &mut Window,
 4269        cx: &mut Context<Self>,
 4270    ) {
 4271        self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
 4272    }
 4273
 4274    fn open_completions_menu(
 4275        &mut self,
 4276        ignore_completion_provider: bool,
 4277        trigger: Option<&str>,
 4278        window: &mut Window,
 4279        cx: &mut Context<Self>,
 4280    ) {
 4281        if self.pending_rename.is_some() {
 4282            return;
 4283        }
 4284        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 4285            return;
 4286        }
 4287
 4288        let position = self.selections.newest_anchor().head();
 4289        if position.diff_base_anchor.is_some() {
 4290            return;
 4291        }
 4292        let (buffer, buffer_position) =
 4293            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4294                output
 4295            } else {
 4296                return;
 4297            };
 4298        let buffer_snapshot = buffer.read(cx).snapshot();
 4299        let show_completion_documentation = buffer_snapshot
 4300            .settings_at(buffer_position, cx)
 4301            .show_completion_documentation;
 4302
 4303        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4304
 4305        let trigger_kind = match trigger {
 4306            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4307                CompletionTriggerKind::TRIGGER_CHARACTER
 4308            }
 4309            _ => CompletionTriggerKind::INVOKED,
 4310        };
 4311        let completion_context = CompletionContext {
 4312            trigger_character: trigger.and_then(|trigger| {
 4313                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4314                    Some(String::from(trigger))
 4315                } else {
 4316                    None
 4317                }
 4318            }),
 4319            trigger_kind,
 4320        };
 4321
 4322        let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
 4323        let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
 4324            let word_to_exclude = buffer_snapshot
 4325                .text_for_range(old_range.clone())
 4326                .collect::<String>();
 4327            (
 4328                buffer_snapshot.anchor_before(old_range.start)
 4329                    ..buffer_snapshot.anchor_after(old_range.end),
 4330                Some(word_to_exclude),
 4331            )
 4332        } else {
 4333            (buffer_position..buffer_position, None)
 4334        };
 4335
 4336        let completion_settings = language_settings(
 4337            buffer_snapshot
 4338                .language_at(buffer_position)
 4339                .map(|language| language.name()),
 4340            buffer_snapshot.file(),
 4341            cx,
 4342        )
 4343        .completions;
 4344
 4345        // The document can be large, so stay in reasonable bounds when searching for words,
 4346        // otherwise completion pop-up might be slow to appear.
 4347        const WORD_LOOKUP_ROWS: u32 = 5_000;
 4348        let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
 4349        let min_word_search = buffer_snapshot.clip_point(
 4350            Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
 4351            Bias::Left,
 4352        );
 4353        let max_word_search = buffer_snapshot.clip_point(
 4354            Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
 4355            Bias::Right,
 4356        );
 4357        let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
 4358            ..buffer_snapshot.point_to_offset(max_word_search);
 4359
 4360        let provider = self
 4361            .completion_provider
 4362            .as_ref()
 4363            .filter(|_| !ignore_completion_provider);
 4364        let skip_digits = query
 4365            .as_ref()
 4366            .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
 4367
 4368        let (mut words, provided_completions) = match provider {
 4369            Some(provider) => {
 4370                let completions = provider.completions(
 4371                    position.excerpt_id,
 4372                    &buffer,
 4373                    buffer_position,
 4374                    completion_context,
 4375                    window,
 4376                    cx,
 4377                );
 4378
 4379                let words = match completion_settings.words {
 4380                    WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
 4381                    WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
 4382                        .background_spawn(async move {
 4383                            buffer_snapshot.words_in_range(WordsQuery {
 4384                                fuzzy_contents: None,
 4385                                range: word_search_range,
 4386                                skip_digits,
 4387                            })
 4388                        }),
 4389                };
 4390
 4391                (words, completions)
 4392            }
 4393            None => (
 4394                cx.background_spawn(async move {
 4395                    buffer_snapshot.words_in_range(WordsQuery {
 4396                        fuzzy_contents: None,
 4397                        range: word_search_range,
 4398                        skip_digits,
 4399                    })
 4400                }),
 4401                Task::ready(Ok(None)),
 4402            ),
 4403        };
 4404
 4405        let sort_completions = provider
 4406            .as_ref()
 4407            .map_or(true, |provider| provider.sort_completions());
 4408
 4409        let filter_completions = provider
 4410            .as_ref()
 4411            .map_or(true, |provider| provider.filter_completions());
 4412
 4413        let id = post_inc(&mut self.next_completion_id);
 4414        let task = cx.spawn_in(window, async move |editor, cx| {
 4415            async move {
 4416                editor.update(cx, |this, _| {
 4417                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4418                })?;
 4419
 4420                let mut completions = Vec::new();
 4421                if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
 4422                    completions.extend(provided_completions);
 4423                    if completion_settings.words == WordsCompletionMode::Fallback {
 4424                        words = Task::ready(HashMap::default());
 4425                    }
 4426                }
 4427
 4428                let mut words = words.await;
 4429                if let Some(word_to_exclude) = &word_to_exclude {
 4430                    words.remove(word_to_exclude);
 4431                }
 4432                for lsp_completion in &completions {
 4433                    words.remove(&lsp_completion.new_text);
 4434                }
 4435                completions.extend(words.into_iter().map(|(word, word_range)| Completion {
 4436                    old_range: old_range.clone(),
 4437                    new_text: word.clone(),
 4438                    label: CodeLabel::plain(word, None),
 4439                    icon_path: None,
 4440                    documentation: None,
 4441                    source: CompletionSource::BufferWord {
 4442                        word_range,
 4443                        resolved: false,
 4444                    },
 4445                    confirm: None,
 4446                }));
 4447
 4448                let menu = if completions.is_empty() {
 4449                    None
 4450                } else {
 4451                    let mut menu = CompletionsMenu::new(
 4452                        id,
 4453                        sort_completions,
 4454                        show_completion_documentation,
 4455                        ignore_completion_provider,
 4456                        position,
 4457                        buffer.clone(),
 4458                        completions.into(),
 4459                    );
 4460
 4461                    menu.filter(
 4462                        if filter_completions {
 4463                            query.as_deref()
 4464                        } else {
 4465                            None
 4466                        },
 4467                        cx.background_executor().clone(),
 4468                    )
 4469                    .await;
 4470
 4471                    menu.visible().then_some(menu)
 4472                };
 4473
 4474                editor.update_in(cx, |editor, window, cx| {
 4475                    match editor.context_menu.borrow().as_ref() {
 4476                        None => {}
 4477                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4478                            if prev_menu.id > id {
 4479                                return;
 4480                            }
 4481                        }
 4482                        _ => return,
 4483                    }
 4484
 4485                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4486                        let mut menu = menu.unwrap();
 4487                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4488
 4489                        *editor.context_menu.borrow_mut() =
 4490                            Some(CodeContextMenu::Completions(menu));
 4491
 4492                        if editor.show_edit_predictions_in_menu() {
 4493                            editor.update_visible_inline_completion(window, cx);
 4494                        } else {
 4495                            editor.discard_inline_completion(false, cx);
 4496                        }
 4497
 4498                        cx.notify();
 4499                    } else if editor.completion_tasks.len() <= 1 {
 4500                        // If there are no more completion tasks and the last menu was
 4501                        // empty, we should hide it.
 4502                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4503                        // If it was already hidden and we don't show inline
 4504                        // completions in the menu, we should also show the
 4505                        // inline-completion when available.
 4506                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4507                            editor.update_visible_inline_completion(window, cx);
 4508                        }
 4509                    }
 4510                })?;
 4511
 4512                anyhow::Ok(())
 4513            }
 4514            .log_err()
 4515            .await
 4516        });
 4517
 4518        self.completion_tasks.push((id, task));
 4519    }
 4520
 4521    #[cfg(feature = "test-support")]
 4522    pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
 4523        let menu = self.context_menu.borrow();
 4524        if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
 4525            let completions = menu.completions.borrow();
 4526            Some(completions.to_vec())
 4527        } else {
 4528            None
 4529        }
 4530    }
 4531
 4532    pub fn confirm_completion(
 4533        &mut self,
 4534        action: &ConfirmCompletion,
 4535        window: &mut Window,
 4536        cx: &mut Context<Self>,
 4537    ) -> Option<Task<Result<()>>> {
 4538        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4539        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4540    }
 4541
 4542    pub fn compose_completion(
 4543        &mut self,
 4544        action: &ComposeCompletion,
 4545        window: &mut Window,
 4546        cx: &mut Context<Self>,
 4547    ) -> Option<Task<Result<()>>> {
 4548        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4549        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4550    }
 4551
 4552    fn do_completion(
 4553        &mut self,
 4554        item_ix: Option<usize>,
 4555        intent: CompletionIntent,
 4556        window: &mut Window,
 4557        cx: &mut Context<Editor>,
 4558    ) -> Option<Task<Result<()>>> {
 4559        use language::ToOffset as _;
 4560
 4561        let completions_menu =
 4562            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4563                menu
 4564            } else {
 4565                return None;
 4566            };
 4567
 4568        let candidate_id = {
 4569            let entries = completions_menu.entries.borrow();
 4570            let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4571            if self.show_edit_predictions_in_menu() {
 4572                self.discard_inline_completion(true, cx);
 4573            }
 4574            mat.candidate_id
 4575        };
 4576
 4577        let buffer_handle = completions_menu.buffer;
 4578        let completion = completions_menu
 4579            .completions
 4580            .borrow()
 4581            .get(candidate_id)?
 4582            .clone();
 4583        cx.stop_propagation();
 4584
 4585        let snippet;
 4586        let new_text;
 4587        if completion.is_snippet() {
 4588            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4589            new_text = snippet.as_ref().unwrap().text.clone();
 4590        } else {
 4591            snippet = None;
 4592            new_text = completion.new_text.clone();
 4593        };
 4594        let selections = self.selections.all::<usize>(cx);
 4595        let buffer = buffer_handle.read(cx);
 4596        let old_range = completion.old_range.to_offset(buffer);
 4597        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4598
 4599        let newest_selection = self.selections.newest_anchor();
 4600        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4601            return None;
 4602        }
 4603
 4604        let lookbehind = newest_selection
 4605            .start
 4606            .text_anchor
 4607            .to_offset(buffer)
 4608            .saturating_sub(old_range.start);
 4609        let lookahead = old_range
 4610            .end
 4611            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4612        let mut common_prefix_len = old_text
 4613            .bytes()
 4614            .zip(new_text.bytes())
 4615            .take_while(|(a, b)| a == b)
 4616            .count();
 4617
 4618        let snapshot = self.buffer.read(cx).snapshot(cx);
 4619        let mut range_to_replace: Option<Range<isize>> = None;
 4620        let mut ranges = Vec::new();
 4621        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4622        for selection in &selections {
 4623            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4624                let start = selection.start.saturating_sub(lookbehind);
 4625                let end = selection.end + lookahead;
 4626                if selection.id == newest_selection.id {
 4627                    range_to_replace = Some(
 4628                        ((start + common_prefix_len) as isize - selection.start as isize)
 4629                            ..(end as isize - selection.start as isize),
 4630                    );
 4631                }
 4632                ranges.push(start + common_prefix_len..end);
 4633            } else {
 4634                common_prefix_len = 0;
 4635                ranges.clear();
 4636                ranges.extend(selections.iter().map(|s| {
 4637                    if s.id == newest_selection.id {
 4638                        range_to_replace = Some(
 4639                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4640                                - selection.start as isize
 4641                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4642                                    - selection.start as isize,
 4643                        );
 4644                        old_range.clone()
 4645                    } else {
 4646                        s.start..s.end
 4647                    }
 4648                }));
 4649                break;
 4650            }
 4651            if !self.linked_edit_ranges.is_empty() {
 4652                let start_anchor = snapshot.anchor_before(selection.head());
 4653                let end_anchor = snapshot.anchor_after(selection.tail());
 4654                if let Some(ranges) = self
 4655                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4656                {
 4657                    for (buffer, edits) in ranges {
 4658                        linked_edits.entry(buffer.clone()).or_default().extend(
 4659                            edits
 4660                                .into_iter()
 4661                                .map(|range| (range, new_text[common_prefix_len..].to_owned())),
 4662                        );
 4663                    }
 4664                }
 4665            }
 4666        }
 4667        let text = &new_text[common_prefix_len..];
 4668
 4669        cx.emit(EditorEvent::InputHandled {
 4670            utf16_range_to_replace: range_to_replace,
 4671            text: text.into(),
 4672        });
 4673
 4674        self.transact(window, cx, |this, window, cx| {
 4675            if let Some(mut snippet) = snippet {
 4676                snippet.text = text.to_string();
 4677                for tabstop in snippet
 4678                    .tabstops
 4679                    .iter_mut()
 4680                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4681                {
 4682                    tabstop.start -= common_prefix_len as isize;
 4683                    tabstop.end -= common_prefix_len as isize;
 4684                }
 4685
 4686                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4687            } else {
 4688                this.buffer.update(cx, |buffer, cx| {
 4689                    let edits = ranges.iter().map(|range| (range.clone(), text));
 4690                    buffer.edit(edits, this.autoindent_mode.clone(), cx);
 4691                });
 4692            }
 4693            for (buffer, edits) in linked_edits {
 4694                buffer.update(cx, |buffer, cx| {
 4695                    let snapshot = buffer.snapshot();
 4696                    let edits = edits
 4697                        .into_iter()
 4698                        .map(|(range, text)| {
 4699                            use text::ToPoint as TP;
 4700                            let end_point = TP::to_point(&range.end, &snapshot);
 4701                            let start_point = TP::to_point(&range.start, &snapshot);
 4702                            (start_point..end_point, text)
 4703                        })
 4704                        .sorted_by_key(|(range, _)| range.start);
 4705                    buffer.edit(edits, None, cx);
 4706                })
 4707            }
 4708
 4709            this.refresh_inline_completion(true, false, window, cx);
 4710        });
 4711
 4712        let show_new_completions_on_confirm = completion
 4713            .confirm
 4714            .as_ref()
 4715            .map_or(false, |confirm| confirm(intent, window, cx));
 4716        if show_new_completions_on_confirm {
 4717            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4718        }
 4719
 4720        let provider = self.completion_provider.as_ref()?;
 4721        drop(completion);
 4722        let apply_edits = provider.apply_additional_edits_for_completion(
 4723            buffer_handle,
 4724            completions_menu.completions.clone(),
 4725            candidate_id,
 4726            true,
 4727            cx,
 4728        );
 4729
 4730        let editor_settings = EditorSettings::get_global(cx);
 4731        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4732            // After the code completion is finished, users often want to know what signatures are needed.
 4733            // so we should automatically call signature_help
 4734            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4735        }
 4736
 4737        Some(cx.foreground_executor().spawn(async move {
 4738            apply_edits.await?;
 4739            Ok(())
 4740        }))
 4741    }
 4742
 4743    pub fn toggle_code_actions(
 4744        &mut self,
 4745        action: &ToggleCodeActions,
 4746        window: &mut Window,
 4747        cx: &mut Context<Self>,
 4748    ) {
 4749        let mut context_menu = self.context_menu.borrow_mut();
 4750        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4751            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4752                // Toggle if we're selecting the same one
 4753                *context_menu = None;
 4754                cx.notify();
 4755                return;
 4756            } else {
 4757                // Otherwise, clear it and start a new one
 4758                *context_menu = None;
 4759                cx.notify();
 4760            }
 4761        }
 4762        drop(context_menu);
 4763        let snapshot = self.snapshot(window, cx);
 4764        let deployed_from_indicator = action.deployed_from_indicator;
 4765        let mut task = self.code_actions_task.take();
 4766        let action = action.clone();
 4767        cx.spawn_in(window, async move |editor, cx| {
 4768            while let Some(prev_task) = task {
 4769                prev_task.await.log_err();
 4770                task = editor.update(cx, |this, _| this.code_actions_task.take())?;
 4771            }
 4772
 4773            let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
 4774                if editor.focus_handle.is_focused(window) {
 4775                    let multibuffer_point = action
 4776                        .deployed_from_indicator
 4777                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4778                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4779                    let (buffer, buffer_row) = snapshot
 4780                        .buffer_snapshot
 4781                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4782                        .and_then(|(buffer_snapshot, range)| {
 4783                            editor
 4784                                .buffer
 4785                                .read(cx)
 4786                                .buffer(buffer_snapshot.remote_id())
 4787                                .map(|buffer| (buffer, range.start.row))
 4788                        })?;
 4789                    let (_, code_actions) = editor
 4790                        .available_code_actions
 4791                        .clone()
 4792                        .and_then(|(location, code_actions)| {
 4793                            let snapshot = location.buffer.read(cx).snapshot();
 4794                            let point_range = location.range.to_point(&snapshot);
 4795                            let point_range = point_range.start.row..=point_range.end.row;
 4796                            if point_range.contains(&buffer_row) {
 4797                                Some((location, code_actions))
 4798                            } else {
 4799                                None
 4800                            }
 4801                        })
 4802                        .unzip();
 4803                    let buffer_id = buffer.read(cx).remote_id();
 4804                    let tasks = editor
 4805                        .tasks
 4806                        .get(&(buffer_id, buffer_row))
 4807                        .map(|t| Arc::new(t.to_owned()));
 4808                    if tasks.is_none() && code_actions.is_none() {
 4809                        return None;
 4810                    }
 4811
 4812                    editor.completion_tasks.clear();
 4813                    editor.discard_inline_completion(false, cx);
 4814                    let task_context =
 4815                        tasks
 4816                            .as_ref()
 4817                            .zip(editor.project.clone())
 4818                            .map(|(tasks, project)| {
 4819                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4820                            });
 4821
 4822                    let debugger_flag = cx.has_flag::<Debugger>();
 4823
 4824                    Some(cx.spawn_in(window, async move |editor, cx| {
 4825                        let task_context = match task_context {
 4826                            Some(task_context) => task_context.await,
 4827                            None => None,
 4828                        };
 4829                        let resolved_tasks =
 4830                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4831                                Rc::new(ResolvedTasks {
 4832                                    templates: tasks.resolve(&task_context).collect(),
 4833                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4834                                        multibuffer_point.row,
 4835                                        tasks.column,
 4836                                    )),
 4837                                })
 4838                            });
 4839                        let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
 4840                            tasks
 4841                                .templates
 4842                                .iter()
 4843                                .filter(|task| {
 4844                                    if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
 4845                                        debugger_flag
 4846                                    } else {
 4847                                        true
 4848                                    }
 4849                                })
 4850                                .count()
 4851                                == 1
 4852                        }) && code_actions
 4853                            .as_ref()
 4854                            .map_or(true, |actions| actions.is_empty());
 4855                        if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
 4856                            *editor.context_menu.borrow_mut() =
 4857                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4858                                    buffer,
 4859                                    actions: CodeActionContents {
 4860                                        tasks: resolved_tasks,
 4861                                        actions: code_actions,
 4862                                    },
 4863                                    selected_item: Default::default(),
 4864                                    scroll_handle: UniformListScrollHandle::default(),
 4865                                    deployed_from_indicator,
 4866                                }));
 4867                            if spawn_straight_away {
 4868                                if let Some(task) = editor.confirm_code_action(
 4869                                    &ConfirmCodeAction { item_ix: Some(0) },
 4870                                    window,
 4871                                    cx,
 4872                                ) {
 4873                                    cx.notify();
 4874                                    return task;
 4875                                }
 4876                            }
 4877                            cx.notify();
 4878                            Task::ready(Ok(()))
 4879                        }) {
 4880                            task.await
 4881                        } else {
 4882                            Ok(())
 4883                        }
 4884                    }))
 4885                } else {
 4886                    Some(Task::ready(Ok(())))
 4887                }
 4888            })?;
 4889            if let Some(task) = spawned_test_task {
 4890                task.await?;
 4891            }
 4892
 4893            Ok::<_, anyhow::Error>(())
 4894        })
 4895        .detach_and_log_err(cx);
 4896    }
 4897
 4898    pub fn confirm_code_action(
 4899        &mut self,
 4900        action: &ConfirmCodeAction,
 4901        window: &mut Window,
 4902        cx: &mut Context<Self>,
 4903    ) -> Option<Task<Result<()>>> {
 4904        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 4905
 4906        let actions_menu =
 4907            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4908                menu
 4909            } else {
 4910                return None;
 4911            };
 4912
 4913        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4914        let action = actions_menu.actions.get(action_ix)?;
 4915        let title = action.label();
 4916        let buffer = actions_menu.buffer;
 4917        let workspace = self.workspace()?;
 4918
 4919        match action {
 4920            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4921                match resolved_task.task_type() {
 4922                    task::TaskType::Script => workspace.update(cx, |workspace, cx| {
 4923                        workspace::tasks::schedule_resolved_task(
 4924                            workspace,
 4925                            task_source_kind,
 4926                            resolved_task,
 4927                            false,
 4928                            cx,
 4929                        );
 4930
 4931                        Some(Task::ready(Ok(())))
 4932                    }),
 4933                    task::TaskType::Debug(debug_args) => {
 4934                        if debug_args.locator.is_some() {
 4935                            workspace.update(cx, |workspace, cx| {
 4936                                workspace::tasks::schedule_resolved_task(
 4937                                    workspace,
 4938                                    task_source_kind,
 4939                                    resolved_task,
 4940                                    false,
 4941                                    cx,
 4942                                );
 4943                            });
 4944
 4945                            return Some(Task::ready(Ok(())));
 4946                        }
 4947
 4948                        if let Some(project) = self.project.as_ref() {
 4949                            project
 4950                                .update(cx, |project, cx| {
 4951                                    project.start_debug_session(
 4952                                        resolved_task.resolved_debug_adapter_config().unwrap(),
 4953                                        cx,
 4954                                    )
 4955                                })
 4956                                .detach_and_log_err(cx);
 4957                            Some(Task::ready(Ok(())))
 4958                        } else {
 4959                            Some(Task::ready(Ok(())))
 4960                        }
 4961                    }
 4962                }
 4963            }
 4964            CodeActionsItem::CodeAction {
 4965                excerpt_id,
 4966                action,
 4967                provider,
 4968            } => {
 4969                let apply_code_action =
 4970                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4971                let workspace = workspace.downgrade();
 4972                Some(cx.spawn_in(window, async move |editor, cx| {
 4973                    let project_transaction = apply_code_action.await?;
 4974                    Self::open_project_transaction(
 4975                        &editor,
 4976                        workspace,
 4977                        project_transaction,
 4978                        title,
 4979                        cx,
 4980                    )
 4981                    .await
 4982                }))
 4983            }
 4984        }
 4985    }
 4986
 4987    pub async fn open_project_transaction(
 4988        this: &WeakEntity<Editor>,
 4989        workspace: WeakEntity<Workspace>,
 4990        transaction: ProjectTransaction,
 4991        title: String,
 4992        cx: &mut AsyncWindowContext,
 4993    ) -> Result<()> {
 4994        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4995        cx.update(|_, cx| {
 4996            entries.sort_unstable_by_key(|(buffer, _)| {
 4997                buffer.read(cx).file().map(|f| f.path().clone())
 4998            });
 4999        })?;
 5000
 5001        // If the project transaction's edits are all contained within this editor, then
 5002        // avoid opening a new editor to display them.
 5003
 5004        if let Some((buffer, transaction)) = entries.first() {
 5005            if entries.len() == 1 {
 5006                let excerpt = this.update(cx, |editor, cx| {
 5007                    editor
 5008                        .buffer()
 5009                        .read(cx)
 5010                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 5011                })?;
 5012                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 5013                    if excerpted_buffer == *buffer {
 5014                        let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
 5015                            let excerpt_range = excerpt_range.to_offset(buffer);
 5016                            buffer
 5017                                .edited_ranges_for_transaction::<usize>(transaction)
 5018                                .all(|range| {
 5019                                    excerpt_range.start <= range.start
 5020                                        && excerpt_range.end >= range.end
 5021                                })
 5022                        })?;
 5023
 5024                        if all_edits_within_excerpt {
 5025                            return Ok(());
 5026                        }
 5027                    }
 5028                }
 5029            }
 5030        } else {
 5031            return Ok(());
 5032        }
 5033
 5034        let mut ranges_to_highlight = Vec::new();
 5035        let excerpt_buffer = cx.new(|cx| {
 5036            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 5037            for (buffer_handle, transaction) in &entries {
 5038                let buffer = buffer_handle.read(cx);
 5039                ranges_to_highlight.extend(
 5040                    multibuffer.push_excerpts_with_context_lines(
 5041                        buffer_handle.clone(),
 5042                        buffer
 5043                            .edited_ranges_for_transaction::<usize>(transaction)
 5044                            .collect(),
 5045                        DEFAULT_MULTIBUFFER_CONTEXT,
 5046                        cx,
 5047                    ),
 5048                );
 5049            }
 5050            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5051            multibuffer
 5052        })?;
 5053
 5054        workspace.update_in(cx, |workspace, window, cx| {
 5055            let project = workspace.project().clone();
 5056            let editor =
 5057                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5058            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5059            editor.update(cx, |editor, cx| {
 5060                editor.highlight_background::<Self>(
 5061                    &ranges_to_highlight,
 5062                    |theme| theme.editor_highlighted_line_background,
 5063                    cx,
 5064                );
 5065            });
 5066        })?;
 5067
 5068        Ok(())
 5069    }
 5070
 5071    pub fn clear_code_action_providers(&mut self) {
 5072        self.code_action_providers.clear();
 5073        self.available_code_actions.take();
 5074    }
 5075
 5076    pub fn add_code_action_provider(
 5077        &mut self,
 5078        provider: Rc<dyn CodeActionProvider>,
 5079        window: &mut Window,
 5080        cx: &mut Context<Self>,
 5081    ) {
 5082        if self
 5083            .code_action_providers
 5084            .iter()
 5085            .any(|existing_provider| existing_provider.id() == provider.id())
 5086        {
 5087            return;
 5088        }
 5089
 5090        self.code_action_providers.push(provider);
 5091        self.refresh_code_actions(window, cx);
 5092    }
 5093
 5094    pub fn remove_code_action_provider(
 5095        &mut self,
 5096        id: Arc<str>,
 5097        window: &mut Window,
 5098        cx: &mut Context<Self>,
 5099    ) {
 5100        self.code_action_providers
 5101            .retain(|provider| provider.id() != id);
 5102        self.refresh_code_actions(window, cx);
 5103    }
 5104
 5105    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5106        let buffer = self.buffer.read(cx);
 5107        let newest_selection = self.selections.newest_anchor().clone();
 5108        if newest_selection.head().diff_base_anchor.is_some() {
 5109            return None;
 5110        }
 5111        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5112        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5113        if start_buffer != end_buffer {
 5114            return None;
 5115        }
 5116
 5117        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5118            cx.background_executor()
 5119                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5120                .await;
 5121
 5122            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5123                let providers = this.code_action_providers.clone();
 5124                let tasks = this
 5125                    .code_action_providers
 5126                    .iter()
 5127                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5128                    .collect::<Vec<_>>();
 5129                (providers, tasks)
 5130            })?;
 5131
 5132            let mut actions = Vec::new();
 5133            for (provider, provider_actions) in
 5134                providers.into_iter().zip(future::join_all(tasks).await)
 5135            {
 5136                if let Some(provider_actions) = provider_actions.log_err() {
 5137                    actions.extend(provider_actions.into_iter().map(|action| {
 5138                        AvailableCodeAction {
 5139                            excerpt_id: newest_selection.start.excerpt_id,
 5140                            action,
 5141                            provider: provider.clone(),
 5142                        }
 5143                    }));
 5144                }
 5145            }
 5146
 5147            this.update(cx, |this, cx| {
 5148                this.available_code_actions = if actions.is_empty() {
 5149                    None
 5150                } else {
 5151                    Some((
 5152                        Location {
 5153                            buffer: start_buffer,
 5154                            range: start..end,
 5155                        },
 5156                        actions.into(),
 5157                    ))
 5158                };
 5159                cx.notify();
 5160            })
 5161        }));
 5162        None
 5163    }
 5164
 5165    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5166        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5167            self.show_git_blame_inline = false;
 5168
 5169            self.show_git_blame_inline_delay_task =
 5170                Some(cx.spawn_in(window, async move |this, cx| {
 5171                    cx.background_executor().timer(delay).await;
 5172
 5173                    this.update(cx, |this, cx| {
 5174                        this.show_git_blame_inline = true;
 5175                        cx.notify();
 5176                    })
 5177                    .log_err();
 5178                }));
 5179        }
 5180    }
 5181
 5182    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5183        if self.pending_rename.is_some() {
 5184            return None;
 5185        }
 5186
 5187        let provider = self.semantics_provider.clone()?;
 5188        let buffer = self.buffer.read(cx);
 5189        let newest_selection = self.selections.newest_anchor().clone();
 5190        let cursor_position = newest_selection.head();
 5191        let (cursor_buffer, cursor_buffer_position) =
 5192            buffer.text_anchor_for_position(cursor_position, cx)?;
 5193        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5194        if cursor_buffer != tail_buffer {
 5195            return None;
 5196        }
 5197        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5198        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5199            cx.background_executor()
 5200                .timer(Duration::from_millis(debounce))
 5201                .await;
 5202
 5203            let highlights = if let Some(highlights) = cx
 5204                .update(|cx| {
 5205                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5206                })
 5207                .ok()
 5208                .flatten()
 5209            {
 5210                highlights.await.log_err()
 5211            } else {
 5212                None
 5213            };
 5214
 5215            if let Some(highlights) = highlights {
 5216                this.update(cx, |this, cx| {
 5217                    if this.pending_rename.is_some() {
 5218                        return;
 5219                    }
 5220
 5221                    let buffer_id = cursor_position.buffer_id;
 5222                    let buffer = this.buffer.read(cx);
 5223                    if !buffer
 5224                        .text_anchor_for_position(cursor_position, cx)
 5225                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5226                    {
 5227                        return;
 5228                    }
 5229
 5230                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5231                    let mut write_ranges = Vec::new();
 5232                    let mut read_ranges = Vec::new();
 5233                    for highlight in highlights {
 5234                        for (excerpt_id, excerpt_range) in
 5235                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5236                        {
 5237                            let start = highlight
 5238                                .range
 5239                                .start
 5240                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5241                            let end = highlight
 5242                                .range
 5243                                .end
 5244                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5245                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5246                                continue;
 5247                            }
 5248
 5249                            let range = Anchor {
 5250                                buffer_id,
 5251                                excerpt_id,
 5252                                text_anchor: start,
 5253                                diff_base_anchor: None,
 5254                            }..Anchor {
 5255                                buffer_id,
 5256                                excerpt_id,
 5257                                text_anchor: end,
 5258                                diff_base_anchor: None,
 5259                            };
 5260                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5261                                write_ranges.push(range);
 5262                            } else {
 5263                                read_ranges.push(range);
 5264                            }
 5265                        }
 5266                    }
 5267
 5268                    this.highlight_background::<DocumentHighlightRead>(
 5269                        &read_ranges,
 5270                        |theme| theme.editor_document_highlight_read_background,
 5271                        cx,
 5272                    );
 5273                    this.highlight_background::<DocumentHighlightWrite>(
 5274                        &write_ranges,
 5275                        |theme| theme.editor_document_highlight_write_background,
 5276                        cx,
 5277                    );
 5278                    cx.notify();
 5279                })
 5280                .log_err();
 5281            }
 5282        }));
 5283        None
 5284    }
 5285
 5286    pub fn refresh_selected_text_highlights(
 5287        &mut self,
 5288        window: &mut Window,
 5289        cx: &mut Context<Editor>,
 5290    ) {
 5291        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5292            return;
 5293        }
 5294        self.selection_highlight_task.take();
 5295        if !EditorSettings::get_global(cx).selection_highlight {
 5296            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5297            return;
 5298        }
 5299        if self.selections.count() != 1 || self.selections.line_mode {
 5300            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5301            return;
 5302        }
 5303        let selection = self.selections.newest::<Point>(cx);
 5304        if selection.is_empty() || selection.start.row != selection.end.row {
 5305            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5306            return;
 5307        }
 5308        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5309        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5310            cx.background_executor()
 5311                .timer(Duration::from_millis(debounce))
 5312                .await;
 5313            let Some(Some(matches_task)) = editor
 5314                .update_in(cx, |editor, _, cx| {
 5315                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5316                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5317                        return None;
 5318                    }
 5319                    let selection = editor.selections.newest::<Point>(cx);
 5320                    if selection.is_empty() || selection.start.row != selection.end.row {
 5321                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5322                        return None;
 5323                    }
 5324                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5325                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5326                    if query.trim().is_empty() {
 5327                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5328                        return None;
 5329                    }
 5330                    Some(cx.background_spawn(async move {
 5331                        let mut ranges = Vec::new();
 5332                        let selection_anchors = selection.range().to_anchors(&buffer);
 5333                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5334                            for (search_buffer, search_range, excerpt_id) in
 5335                                buffer.range_to_buffer_ranges(range)
 5336                            {
 5337                                ranges.extend(
 5338                                    project::search::SearchQuery::text(
 5339                                        query.clone(),
 5340                                        false,
 5341                                        false,
 5342                                        false,
 5343                                        Default::default(),
 5344                                        Default::default(),
 5345                                        None,
 5346                                    )
 5347                                    .unwrap()
 5348                                    .search(search_buffer, Some(search_range.clone()))
 5349                                    .await
 5350                                    .into_iter()
 5351                                    .filter_map(
 5352                                        |match_range| {
 5353                                            let start = search_buffer.anchor_after(
 5354                                                search_range.start + match_range.start,
 5355                                            );
 5356                                            let end = search_buffer.anchor_before(
 5357                                                search_range.start + match_range.end,
 5358                                            );
 5359                                            let range = Anchor::range_in_buffer(
 5360                                                excerpt_id,
 5361                                                search_buffer.remote_id(),
 5362                                                start..end,
 5363                                            );
 5364                                            (range != selection_anchors).then_some(range)
 5365                                        },
 5366                                    ),
 5367                                );
 5368                            }
 5369                        }
 5370                        ranges
 5371                    }))
 5372                })
 5373                .log_err()
 5374            else {
 5375                return;
 5376            };
 5377            let matches = matches_task.await;
 5378            editor
 5379                .update_in(cx, |editor, _, cx| {
 5380                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5381                    if !matches.is_empty() {
 5382                        editor.highlight_background::<SelectedTextHighlight>(
 5383                            &matches,
 5384                            |theme| theme.editor_document_highlight_bracket_background,
 5385                            cx,
 5386                        )
 5387                    }
 5388                })
 5389                .log_err();
 5390        }));
 5391    }
 5392
 5393    pub fn refresh_inline_completion(
 5394        &mut self,
 5395        debounce: bool,
 5396        user_requested: bool,
 5397        window: &mut Window,
 5398        cx: &mut Context<Self>,
 5399    ) -> Option<()> {
 5400        let provider = self.edit_prediction_provider()?;
 5401        let cursor = self.selections.newest_anchor().head();
 5402        let (buffer, cursor_buffer_position) =
 5403            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5404
 5405        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5406            self.discard_inline_completion(false, cx);
 5407            return None;
 5408        }
 5409
 5410        if !user_requested
 5411            && (!self.should_show_edit_predictions()
 5412                || !self.is_focused(window)
 5413                || buffer.read(cx).is_empty())
 5414        {
 5415            self.discard_inline_completion(false, cx);
 5416            return None;
 5417        }
 5418
 5419        self.update_visible_inline_completion(window, cx);
 5420        provider.refresh(
 5421            self.project.clone(),
 5422            buffer,
 5423            cursor_buffer_position,
 5424            debounce,
 5425            cx,
 5426        );
 5427        Some(())
 5428    }
 5429
 5430    fn show_edit_predictions_in_menu(&self) -> bool {
 5431        match self.edit_prediction_settings {
 5432            EditPredictionSettings::Disabled => false,
 5433            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5434        }
 5435    }
 5436
 5437    pub fn edit_predictions_enabled(&self) -> bool {
 5438        match self.edit_prediction_settings {
 5439            EditPredictionSettings::Disabled => false,
 5440            EditPredictionSettings::Enabled { .. } => true,
 5441        }
 5442    }
 5443
 5444    fn edit_prediction_requires_modifier(&self) -> bool {
 5445        match self.edit_prediction_settings {
 5446            EditPredictionSettings::Disabled => false,
 5447            EditPredictionSettings::Enabled {
 5448                preview_requires_modifier,
 5449                ..
 5450            } => preview_requires_modifier,
 5451        }
 5452    }
 5453
 5454    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5455        if self.edit_prediction_provider.is_none() {
 5456            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5457        } else {
 5458            let selection = self.selections.newest_anchor();
 5459            let cursor = selection.head();
 5460
 5461            if let Some((buffer, cursor_buffer_position)) =
 5462                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5463            {
 5464                self.edit_prediction_settings =
 5465                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5466            }
 5467        }
 5468    }
 5469
 5470    fn edit_prediction_settings_at_position(
 5471        &self,
 5472        buffer: &Entity<Buffer>,
 5473        buffer_position: language::Anchor,
 5474        cx: &App,
 5475    ) -> EditPredictionSettings {
 5476        if self.mode != EditorMode::Full
 5477            || !self.show_inline_completions_override.unwrap_or(true)
 5478            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5479        {
 5480            return EditPredictionSettings::Disabled;
 5481        }
 5482
 5483        let buffer = buffer.read(cx);
 5484
 5485        let file = buffer.file();
 5486
 5487        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5488            return EditPredictionSettings::Disabled;
 5489        };
 5490
 5491        let by_provider = matches!(
 5492            self.menu_inline_completions_policy,
 5493            MenuInlineCompletionsPolicy::ByProvider
 5494        );
 5495
 5496        let show_in_menu = by_provider
 5497            && self
 5498                .edit_prediction_provider
 5499                .as_ref()
 5500                .map_or(false, |provider| {
 5501                    provider.provider.show_completions_in_menu()
 5502                });
 5503
 5504        let preview_requires_modifier =
 5505            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5506
 5507        EditPredictionSettings::Enabled {
 5508            show_in_menu,
 5509            preview_requires_modifier,
 5510        }
 5511    }
 5512
 5513    fn should_show_edit_predictions(&self) -> bool {
 5514        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5515    }
 5516
 5517    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5518        matches!(
 5519            self.edit_prediction_preview,
 5520            EditPredictionPreview::Active { .. }
 5521        )
 5522    }
 5523
 5524    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5525        let cursor = self.selections.newest_anchor().head();
 5526        if let Some((buffer, cursor_position)) =
 5527            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5528        {
 5529            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5530        } else {
 5531            false
 5532        }
 5533    }
 5534
 5535    fn edit_predictions_enabled_in_buffer(
 5536        &self,
 5537        buffer: &Entity<Buffer>,
 5538        buffer_position: language::Anchor,
 5539        cx: &App,
 5540    ) -> bool {
 5541        maybe!({
 5542            if self.read_only(cx) {
 5543                return Some(false);
 5544            }
 5545            let provider = self.edit_prediction_provider()?;
 5546            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5547                return Some(false);
 5548            }
 5549            let buffer = buffer.read(cx);
 5550            let Some(file) = buffer.file() else {
 5551                return Some(true);
 5552            };
 5553            let settings = all_language_settings(Some(file), cx);
 5554            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5555        })
 5556        .unwrap_or(false)
 5557    }
 5558
 5559    fn cycle_inline_completion(
 5560        &mut self,
 5561        direction: Direction,
 5562        window: &mut Window,
 5563        cx: &mut Context<Self>,
 5564    ) -> Option<()> {
 5565        let provider = self.edit_prediction_provider()?;
 5566        let cursor = self.selections.newest_anchor().head();
 5567        let (buffer, cursor_buffer_position) =
 5568            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5569        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5570            return None;
 5571        }
 5572
 5573        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5574        self.update_visible_inline_completion(window, cx);
 5575
 5576        Some(())
 5577    }
 5578
 5579    pub fn show_inline_completion(
 5580        &mut self,
 5581        _: &ShowEditPrediction,
 5582        window: &mut Window,
 5583        cx: &mut Context<Self>,
 5584    ) {
 5585        if !self.has_active_inline_completion() {
 5586            self.refresh_inline_completion(false, true, window, cx);
 5587            return;
 5588        }
 5589
 5590        self.update_visible_inline_completion(window, cx);
 5591    }
 5592
 5593    pub fn display_cursor_names(
 5594        &mut self,
 5595        _: &DisplayCursorNames,
 5596        window: &mut Window,
 5597        cx: &mut Context<Self>,
 5598    ) {
 5599        self.show_cursor_names(window, cx);
 5600    }
 5601
 5602    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5603        self.show_cursor_names = true;
 5604        cx.notify();
 5605        cx.spawn_in(window, async move |this, cx| {
 5606            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5607            this.update(cx, |this, cx| {
 5608                this.show_cursor_names = false;
 5609                cx.notify()
 5610            })
 5611            .ok()
 5612        })
 5613        .detach();
 5614    }
 5615
 5616    pub fn next_edit_prediction(
 5617        &mut self,
 5618        _: &NextEditPrediction,
 5619        window: &mut Window,
 5620        cx: &mut Context<Self>,
 5621    ) {
 5622        if self.has_active_inline_completion() {
 5623            self.cycle_inline_completion(Direction::Next, window, cx);
 5624        } else {
 5625            let is_copilot_disabled = self
 5626                .refresh_inline_completion(false, true, window, cx)
 5627                .is_none();
 5628            if is_copilot_disabled {
 5629                cx.propagate();
 5630            }
 5631        }
 5632    }
 5633
 5634    pub fn previous_edit_prediction(
 5635        &mut self,
 5636        _: &PreviousEditPrediction,
 5637        window: &mut Window,
 5638        cx: &mut Context<Self>,
 5639    ) {
 5640        if self.has_active_inline_completion() {
 5641            self.cycle_inline_completion(Direction::Prev, window, cx);
 5642        } else {
 5643            let is_copilot_disabled = self
 5644                .refresh_inline_completion(false, true, window, cx)
 5645                .is_none();
 5646            if is_copilot_disabled {
 5647                cx.propagate();
 5648            }
 5649        }
 5650    }
 5651
 5652    pub fn accept_edit_prediction(
 5653        &mut self,
 5654        _: &AcceptEditPrediction,
 5655        window: &mut Window,
 5656        cx: &mut Context<Self>,
 5657    ) {
 5658        if self.show_edit_predictions_in_menu() {
 5659            self.hide_context_menu(window, cx);
 5660        }
 5661
 5662        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5663            return;
 5664        };
 5665
 5666        self.report_inline_completion_event(
 5667            active_inline_completion.completion_id.clone(),
 5668            true,
 5669            cx,
 5670        );
 5671
 5672        match &active_inline_completion.completion {
 5673            InlineCompletion::Move { target, .. } => {
 5674                let target = *target;
 5675
 5676                if let Some(position_map) = &self.last_position_map {
 5677                    if position_map
 5678                        .visible_row_range
 5679                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5680                        || !self.edit_prediction_requires_modifier()
 5681                    {
 5682                        self.unfold_ranges(&[target..target], true, false, cx);
 5683                        // Note that this is also done in vim's handler of the Tab action.
 5684                        self.change_selections(
 5685                            Some(Autoscroll::newest()),
 5686                            window,
 5687                            cx,
 5688                            |selections| {
 5689                                selections.select_anchor_ranges([target..target]);
 5690                            },
 5691                        );
 5692                        self.clear_row_highlights::<EditPredictionPreview>();
 5693
 5694                        self.edit_prediction_preview
 5695                            .set_previous_scroll_position(None);
 5696                    } else {
 5697                        self.edit_prediction_preview
 5698                            .set_previous_scroll_position(Some(
 5699                                position_map.snapshot.scroll_anchor,
 5700                            ));
 5701
 5702                        self.highlight_rows::<EditPredictionPreview>(
 5703                            target..target,
 5704                            cx.theme().colors().editor_highlighted_line_background,
 5705                            true,
 5706                            cx,
 5707                        );
 5708                        self.request_autoscroll(Autoscroll::fit(), cx);
 5709                    }
 5710                }
 5711            }
 5712            InlineCompletion::Edit { edits, .. } => {
 5713                if let Some(provider) = self.edit_prediction_provider() {
 5714                    provider.accept(cx);
 5715                }
 5716
 5717                let snapshot = self.buffer.read(cx).snapshot(cx);
 5718                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5719
 5720                self.buffer.update(cx, |buffer, cx| {
 5721                    buffer.edit(edits.iter().cloned(), None, cx)
 5722                });
 5723
 5724                self.change_selections(None, window, cx, |s| {
 5725                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5726                });
 5727
 5728                self.update_visible_inline_completion(window, cx);
 5729                if self.active_inline_completion.is_none() {
 5730                    self.refresh_inline_completion(true, true, window, cx);
 5731                }
 5732
 5733                cx.notify();
 5734            }
 5735        }
 5736
 5737        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5738    }
 5739
 5740    pub fn accept_partial_inline_completion(
 5741        &mut self,
 5742        _: &AcceptPartialEditPrediction,
 5743        window: &mut Window,
 5744        cx: &mut Context<Self>,
 5745    ) {
 5746        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5747            return;
 5748        };
 5749        if self.selections.count() != 1 {
 5750            return;
 5751        }
 5752
 5753        self.report_inline_completion_event(
 5754            active_inline_completion.completion_id.clone(),
 5755            true,
 5756            cx,
 5757        );
 5758
 5759        match &active_inline_completion.completion {
 5760            InlineCompletion::Move { target, .. } => {
 5761                let target = *target;
 5762                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5763                    selections.select_anchor_ranges([target..target]);
 5764                });
 5765            }
 5766            InlineCompletion::Edit { edits, .. } => {
 5767                // Find an insertion that starts at the cursor position.
 5768                let snapshot = self.buffer.read(cx).snapshot(cx);
 5769                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5770                let insertion = edits.iter().find_map(|(range, text)| {
 5771                    let range = range.to_offset(&snapshot);
 5772                    if range.is_empty() && range.start == cursor_offset {
 5773                        Some(text)
 5774                    } else {
 5775                        None
 5776                    }
 5777                });
 5778
 5779                if let Some(text) = insertion {
 5780                    let mut partial_completion = text
 5781                        .chars()
 5782                        .by_ref()
 5783                        .take_while(|c| c.is_alphabetic())
 5784                        .collect::<String>();
 5785                    if partial_completion.is_empty() {
 5786                        partial_completion = text
 5787                            .chars()
 5788                            .by_ref()
 5789                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5790                            .collect::<String>();
 5791                    }
 5792
 5793                    cx.emit(EditorEvent::InputHandled {
 5794                        utf16_range_to_replace: None,
 5795                        text: partial_completion.clone().into(),
 5796                    });
 5797
 5798                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5799
 5800                    self.refresh_inline_completion(true, true, window, cx);
 5801                    cx.notify();
 5802                } else {
 5803                    self.accept_edit_prediction(&Default::default(), window, cx);
 5804                }
 5805            }
 5806        }
 5807    }
 5808
 5809    fn discard_inline_completion(
 5810        &mut self,
 5811        should_report_inline_completion_event: bool,
 5812        cx: &mut Context<Self>,
 5813    ) -> bool {
 5814        if should_report_inline_completion_event {
 5815            let completion_id = self
 5816                .active_inline_completion
 5817                .as_ref()
 5818                .and_then(|active_completion| active_completion.completion_id.clone());
 5819
 5820            self.report_inline_completion_event(completion_id, false, cx);
 5821        }
 5822
 5823        if let Some(provider) = self.edit_prediction_provider() {
 5824            provider.discard(cx);
 5825        }
 5826
 5827        self.take_active_inline_completion(cx)
 5828    }
 5829
 5830    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5831        let Some(provider) = self.edit_prediction_provider() else {
 5832            return;
 5833        };
 5834
 5835        let Some((_, buffer, _)) = self
 5836            .buffer
 5837            .read(cx)
 5838            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5839        else {
 5840            return;
 5841        };
 5842
 5843        let extension = buffer
 5844            .read(cx)
 5845            .file()
 5846            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5847
 5848        let event_type = match accepted {
 5849            true => "Edit Prediction Accepted",
 5850            false => "Edit Prediction Discarded",
 5851        };
 5852        telemetry::event!(
 5853            event_type,
 5854            provider = provider.name(),
 5855            prediction_id = id,
 5856            suggestion_accepted = accepted,
 5857            file_extension = extension,
 5858        );
 5859    }
 5860
 5861    pub fn has_active_inline_completion(&self) -> bool {
 5862        self.active_inline_completion.is_some()
 5863    }
 5864
 5865    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5866        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5867            return false;
 5868        };
 5869
 5870        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5871        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5872        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5873        true
 5874    }
 5875
 5876    /// Returns true when we're displaying the edit prediction popover below the cursor
 5877    /// like we are not previewing and the LSP autocomplete menu is visible
 5878    /// or we are in `when_holding_modifier` mode.
 5879    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5880        if self.edit_prediction_preview_is_active()
 5881            || !self.show_edit_predictions_in_menu()
 5882            || !self.edit_predictions_enabled()
 5883        {
 5884            return false;
 5885        }
 5886
 5887        if self.has_visible_completions_menu() {
 5888            return true;
 5889        }
 5890
 5891        has_completion && self.edit_prediction_requires_modifier()
 5892    }
 5893
 5894    fn handle_modifiers_changed(
 5895        &mut self,
 5896        modifiers: Modifiers,
 5897        position_map: &PositionMap,
 5898        window: &mut Window,
 5899        cx: &mut Context<Self>,
 5900    ) {
 5901        if self.show_edit_predictions_in_menu() {
 5902            self.update_edit_prediction_preview(&modifiers, window, cx);
 5903        }
 5904
 5905        self.update_selection_mode(&modifiers, position_map, window, cx);
 5906
 5907        let mouse_position = window.mouse_position();
 5908        if !position_map.text_hitbox.is_hovered(window) {
 5909            return;
 5910        }
 5911
 5912        self.update_hovered_link(
 5913            position_map.point_for_position(mouse_position),
 5914            &position_map.snapshot,
 5915            modifiers,
 5916            window,
 5917            cx,
 5918        )
 5919    }
 5920
 5921    fn update_selection_mode(
 5922        &mut self,
 5923        modifiers: &Modifiers,
 5924        position_map: &PositionMap,
 5925        window: &mut Window,
 5926        cx: &mut Context<Self>,
 5927    ) {
 5928        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5929            return;
 5930        }
 5931
 5932        let mouse_position = window.mouse_position();
 5933        let point_for_position = position_map.point_for_position(mouse_position);
 5934        let position = point_for_position.previous_valid;
 5935
 5936        self.select(
 5937            SelectPhase::BeginColumnar {
 5938                position,
 5939                reset: false,
 5940                goal_column: point_for_position.exact_unclipped.column(),
 5941            },
 5942            window,
 5943            cx,
 5944        );
 5945    }
 5946
 5947    fn update_edit_prediction_preview(
 5948        &mut self,
 5949        modifiers: &Modifiers,
 5950        window: &mut Window,
 5951        cx: &mut Context<Self>,
 5952    ) {
 5953        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5954        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5955            return;
 5956        };
 5957
 5958        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5959            if matches!(
 5960                self.edit_prediction_preview,
 5961                EditPredictionPreview::Inactive { .. }
 5962            ) {
 5963                self.edit_prediction_preview = EditPredictionPreview::Active {
 5964                    previous_scroll_position: None,
 5965                    since: Instant::now(),
 5966                };
 5967
 5968                self.update_visible_inline_completion(window, cx);
 5969                cx.notify();
 5970            }
 5971        } else if let EditPredictionPreview::Active {
 5972            previous_scroll_position,
 5973            since,
 5974        } = self.edit_prediction_preview
 5975        {
 5976            if let (Some(previous_scroll_position), Some(position_map)) =
 5977                (previous_scroll_position, self.last_position_map.as_ref())
 5978            {
 5979                self.set_scroll_position(
 5980                    previous_scroll_position
 5981                        .scroll_position(&position_map.snapshot.display_snapshot),
 5982                    window,
 5983                    cx,
 5984                );
 5985            }
 5986
 5987            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5988                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5989            };
 5990            self.clear_row_highlights::<EditPredictionPreview>();
 5991            self.update_visible_inline_completion(window, cx);
 5992            cx.notify();
 5993        }
 5994    }
 5995
 5996    fn update_visible_inline_completion(
 5997        &mut self,
 5998        _window: &mut Window,
 5999        cx: &mut Context<Self>,
 6000    ) -> Option<()> {
 6001        let selection = self.selections.newest_anchor();
 6002        let cursor = selection.head();
 6003        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6004        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6005        let excerpt_id = cursor.excerpt_id;
 6006
 6007        let show_in_menu = self.show_edit_predictions_in_menu();
 6008        let completions_menu_has_precedence = !show_in_menu
 6009            && (self.context_menu.borrow().is_some()
 6010                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6011
 6012        if completions_menu_has_precedence
 6013            || !offset_selection.is_empty()
 6014            || self
 6015                .active_inline_completion
 6016                .as_ref()
 6017                .map_or(false, |completion| {
 6018                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6019                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6020                    !invalidation_range.contains(&offset_selection.head())
 6021                })
 6022        {
 6023            self.discard_inline_completion(false, cx);
 6024            return None;
 6025        }
 6026
 6027        self.take_active_inline_completion(cx);
 6028        let Some(provider) = self.edit_prediction_provider() else {
 6029            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6030            return None;
 6031        };
 6032
 6033        let (buffer, cursor_buffer_position) =
 6034            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6035
 6036        self.edit_prediction_settings =
 6037            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6038
 6039        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6040
 6041        if self.edit_prediction_indent_conflict {
 6042            let cursor_point = cursor.to_point(&multibuffer);
 6043
 6044            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6045
 6046            if let Some((_, indent)) = indents.iter().next() {
 6047                if indent.len == cursor_point.column {
 6048                    self.edit_prediction_indent_conflict = false;
 6049                }
 6050            }
 6051        }
 6052
 6053        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6054        let edits = inline_completion
 6055            .edits
 6056            .into_iter()
 6057            .flat_map(|(range, new_text)| {
 6058                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6059                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6060                Some((start..end, new_text))
 6061            })
 6062            .collect::<Vec<_>>();
 6063        if edits.is_empty() {
 6064            return None;
 6065        }
 6066
 6067        let first_edit_start = edits.first().unwrap().0.start;
 6068        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6069        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6070
 6071        let last_edit_end = edits.last().unwrap().0.end;
 6072        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6073        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6074
 6075        let cursor_row = cursor.to_point(&multibuffer).row;
 6076
 6077        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6078
 6079        let mut inlay_ids = Vec::new();
 6080        let invalidation_row_range;
 6081        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6082            Some(cursor_row..edit_end_row)
 6083        } else if cursor_row > edit_end_row {
 6084            Some(edit_start_row..cursor_row)
 6085        } else {
 6086            None
 6087        };
 6088        let is_move =
 6089            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6090        let completion = if is_move {
 6091            invalidation_row_range =
 6092                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6093            let target = first_edit_start;
 6094            InlineCompletion::Move { target, snapshot }
 6095        } else {
 6096            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6097                && !self.inline_completions_hidden_for_vim_mode;
 6098
 6099            if show_completions_in_buffer {
 6100                if edits
 6101                    .iter()
 6102                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6103                {
 6104                    let mut inlays = Vec::new();
 6105                    for (range, new_text) in &edits {
 6106                        let inlay = Inlay::inline_completion(
 6107                            post_inc(&mut self.next_inlay_id),
 6108                            range.start,
 6109                            new_text.as_str(),
 6110                        );
 6111                        inlay_ids.push(inlay.id);
 6112                        inlays.push(inlay);
 6113                    }
 6114
 6115                    self.splice_inlays(&[], inlays, cx);
 6116                } else {
 6117                    let background_color = cx.theme().status().deleted_background;
 6118                    self.highlight_text::<InlineCompletionHighlight>(
 6119                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6120                        HighlightStyle {
 6121                            background_color: Some(background_color),
 6122                            ..Default::default()
 6123                        },
 6124                        cx,
 6125                    );
 6126                }
 6127            }
 6128
 6129            invalidation_row_range = edit_start_row..edit_end_row;
 6130
 6131            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6132                if provider.show_tab_accept_marker() {
 6133                    EditDisplayMode::TabAccept
 6134                } else {
 6135                    EditDisplayMode::Inline
 6136                }
 6137            } else {
 6138                EditDisplayMode::DiffPopover
 6139            };
 6140
 6141            InlineCompletion::Edit {
 6142                edits,
 6143                edit_preview: inline_completion.edit_preview,
 6144                display_mode,
 6145                snapshot,
 6146            }
 6147        };
 6148
 6149        let invalidation_range = multibuffer
 6150            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6151            ..multibuffer.anchor_after(Point::new(
 6152                invalidation_row_range.end,
 6153                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6154            ));
 6155
 6156        self.stale_inline_completion_in_menu = None;
 6157        self.active_inline_completion = Some(InlineCompletionState {
 6158            inlay_ids,
 6159            completion,
 6160            completion_id: inline_completion.id,
 6161            invalidation_range,
 6162        });
 6163
 6164        cx.notify();
 6165
 6166        Some(())
 6167    }
 6168
 6169    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6170        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6171    }
 6172
 6173    fn render_code_actions_indicator(
 6174        &self,
 6175        _style: &EditorStyle,
 6176        row: DisplayRow,
 6177        is_active: bool,
 6178        breakpoint: Option<&(Anchor, Breakpoint)>,
 6179        cx: &mut Context<Self>,
 6180    ) -> Option<IconButton> {
 6181        let color = Color::Muted;
 6182        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6183        let show_tooltip = !self.context_menu_visible();
 6184
 6185        if self.available_code_actions.is_some() {
 6186            Some(
 6187                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6188                    .shape(ui::IconButtonShape::Square)
 6189                    .icon_size(IconSize::XSmall)
 6190                    .icon_color(color)
 6191                    .toggle_state(is_active)
 6192                    .when(show_tooltip, |this| {
 6193                        this.tooltip({
 6194                            let focus_handle = self.focus_handle.clone();
 6195                            move |window, cx| {
 6196                                Tooltip::for_action_in(
 6197                                    "Toggle Code Actions",
 6198                                    &ToggleCodeActions {
 6199                                        deployed_from_indicator: None,
 6200                                    },
 6201                                    &focus_handle,
 6202                                    window,
 6203                                    cx,
 6204                                )
 6205                            }
 6206                        })
 6207                    })
 6208                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6209                        window.focus(&editor.focus_handle(cx));
 6210                        editor.toggle_code_actions(
 6211                            &ToggleCodeActions {
 6212                                deployed_from_indicator: Some(row),
 6213                            },
 6214                            window,
 6215                            cx,
 6216                        );
 6217                    }))
 6218                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6219                        editor.set_breakpoint_context_menu(
 6220                            row,
 6221                            position,
 6222                            event.down.position,
 6223                            window,
 6224                            cx,
 6225                        );
 6226                    })),
 6227            )
 6228        } else {
 6229            None
 6230        }
 6231    }
 6232
 6233    fn clear_tasks(&mut self) {
 6234        self.tasks.clear()
 6235    }
 6236
 6237    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6238        if self.tasks.insert(key, value).is_some() {
 6239            // This case should hopefully be rare, but just in case...
 6240            log::error!(
 6241                "multiple different run targets found on a single line, only the last target will be rendered"
 6242            )
 6243        }
 6244    }
 6245
 6246    /// Get all display points of breakpoints that will be rendered within editor
 6247    ///
 6248    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6249    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6250    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6251    fn active_breakpoints(
 6252        &self,
 6253        range: Range<DisplayRow>,
 6254        window: &mut Window,
 6255        cx: &mut Context<Self>,
 6256    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6257        let mut breakpoint_display_points = HashMap::default();
 6258
 6259        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6260            return breakpoint_display_points;
 6261        };
 6262
 6263        let snapshot = self.snapshot(window, cx);
 6264
 6265        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6266        let Some(project) = self.project.as_ref() else {
 6267            return breakpoint_display_points;
 6268        };
 6269
 6270        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6271            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6272
 6273        for (buffer_snapshot, range, excerpt_id) in
 6274            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6275        {
 6276            let Some(buffer) = project.read_with(cx, |this, cx| {
 6277                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6278            }) else {
 6279                continue;
 6280            };
 6281            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6282                &buffer,
 6283                Some(
 6284                    buffer_snapshot.anchor_before(range.start)
 6285                        ..buffer_snapshot.anchor_after(range.end),
 6286                ),
 6287                buffer_snapshot,
 6288                cx,
 6289            );
 6290            for (anchor, breakpoint) in breakpoints {
 6291                let multi_buffer_anchor =
 6292                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6293                let position = multi_buffer_anchor
 6294                    .to_point(&multi_buffer_snapshot)
 6295                    .to_display_point(&snapshot);
 6296
 6297                breakpoint_display_points
 6298                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6299            }
 6300        }
 6301
 6302        breakpoint_display_points
 6303    }
 6304
 6305    fn breakpoint_context_menu(
 6306        &self,
 6307        anchor: Anchor,
 6308        window: &mut Window,
 6309        cx: &mut Context<Self>,
 6310    ) -> Entity<ui::ContextMenu> {
 6311        let weak_editor = cx.weak_entity();
 6312        let focus_handle = self.focus_handle(cx);
 6313
 6314        let row = self
 6315            .buffer
 6316            .read(cx)
 6317            .snapshot(cx)
 6318            .summary_for_anchor::<Point>(&anchor)
 6319            .row;
 6320
 6321        let breakpoint = self
 6322            .breakpoint_at_row(row, window, cx)
 6323            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6324
 6325        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6326            "Edit Log Breakpoint"
 6327        } else {
 6328            "Set Log Breakpoint"
 6329        };
 6330
 6331        let condition_breakpoint_msg = if breakpoint
 6332            .as_ref()
 6333            .is_some_and(|bp| bp.1.condition.is_some())
 6334        {
 6335            "Edit Condition Breakpoint"
 6336        } else {
 6337            "Set Condition Breakpoint"
 6338        };
 6339
 6340        let hit_condition_breakpoint_msg = if breakpoint
 6341            .as_ref()
 6342            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6343        {
 6344            "Edit Hit Condition Breakpoint"
 6345        } else {
 6346            "Set Hit Condition Breakpoint"
 6347        };
 6348
 6349        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6350            "Unset Breakpoint"
 6351        } else {
 6352            "Set Breakpoint"
 6353        };
 6354
 6355        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6356            BreakpointState::Enabled => Some("Disable"),
 6357            BreakpointState::Disabled => Some("Enable"),
 6358        });
 6359
 6360        let (anchor, breakpoint) =
 6361            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6362
 6363        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6364            menu.on_blur_subscription(Subscription::new(|| {}))
 6365                .context(focus_handle)
 6366                .when_some(toggle_state_msg, |this, msg| {
 6367                    this.entry(msg, None, {
 6368                        let weak_editor = weak_editor.clone();
 6369                        let breakpoint = breakpoint.clone();
 6370                        move |_window, cx| {
 6371                            weak_editor
 6372                                .update(cx, |this, cx| {
 6373                                    this.edit_breakpoint_at_anchor(
 6374                                        anchor,
 6375                                        breakpoint.as_ref().clone(),
 6376                                        BreakpointEditAction::InvertState,
 6377                                        cx,
 6378                                    );
 6379                                })
 6380                                .log_err();
 6381                        }
 6382                    })
 6383                })
 6384                .entry(set_breakpoint_msg, None, {
 6385                    let weak_editor = weak_editor.clone();
 6386                    let breakpoint = breakpoint.clone();
 6387                    move |_window, cx| {
 6388                        weak_editor
 6389                            .update(cx, |this, cx| {
 6390                                this.edit_breakpoint_at_anchor(
 6391                                    anchor,
 6392                                    breakpoint.as_ref().clone(),
 6393                                    BreakpointEditAction::Toggle,
 6394                                    cx,
 6395                                );
 6396                            })
 6397                            .log_err();
 6398                    }
 6399                })
 6400                .entry(log_breakpoint_msg, None, {
 6401                    let breakpoint = breakpoint.clone();
 6402                    let weak_editor = weak_editor.clone();
 6403                    move |window, cx| {
 6404                        weak_editor
 6405                            .update(cx, |this, cx| {
 6406                                this.add_edit_breakpoint_block(
 6407                                    anchor,
 6408                                    breakpoint.as_ref(),
 6409                                    BreakpointPromptEditAction::Log,
 6410                                    window,
 6411                                    cx,
 6412                                );
 6413                            })
 6414                            .log_err();
 6415                    }
 6416                })
 6417                .entry(condition_breakpoint_msg, None, {
 6418                    let breakpoint = breakpoint.clone();
 6419                    let weak_editor = weak_editor.clone();
 6420                    move |window, cx| {
 6421                        weak_editor
 6422                            .update(cx, |this, cx| {
 6423                                this.add_edit_breakpoint_block(
 6424                                    anchor,
 6425                                    breakpoint.as_ref(),
 6426                                    BreakpointPromptEditAction::Condition,
 6427                                    window,
 6428                                    cx,
 6429                                );
 6430                            })
 6431                            .log_err();
 6432                    }
 6433                })
 6434                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6435                    weak_editor
 6436                        .update(cx, |this, cx| {
 6437                            this.add_edit_breakpoint_block(
 6438                                anchor,
 6439                                breakpoint.as_ref(),
 6440                                BreakpointPromptEditAction::HitCondition,
 6441                                window,
 6442                                cx,
 6443                            );
 6444                        })
 6445                        .log_err();
 6446                })
 6447        })
 6448    }
 6449
 6450    fn render_breakpoint(
 6451        &self,
 6452        position: Anchor,
 6453        row: DisplayRow,
 6454        breakpoint: &Breakpoint,
 6455        cx: &mut Context<Self>,
 6456    ) -> IconButton {
 6457        let (color, icon) = {
 6458            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6459                (false, false) => ui::IconName::DebugBreakpoint,
 6460                (true, false) => ui::IconName::DebugLogBreakpoint,
 6461                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6462                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6463            };
 6464
 6465            let color = if self
 6466                .gutter_breakpoint_indicator
 6467                .0
 6468                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6469            {
 6470                Color::Hint
 6471            } else {
 6472                Color::Debugger
 6473            };
 6474
 6475            (color, icon)
 6476        };
 6477
 6478        let breakpoint = Arc::from(breakpoint.clone());
 6479
 6480        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6481            .icon_size(IconSize::XSmall)
 6482            .size(ui::ButtonSize::None)
 6483            .icon_color(color)
 6484            .style(ButtonStyle::Transparent)
 6485            .on_click(cx.listener({
 6486                let breakpoint = breakpoint.clone();
 6487
 6488                move |editor, event: &ClickEvent, window, cx| {
 6489                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6490                        BreakpointEditAction::InvertState
 6491                    } else {
 6492                        BreakpointEditAction::Toggle
 6493                    };
 6494
 6495                    window.focus(&editor.focus_handle(cx));
 6496                    editor.edit_breakpoint_at_anchor(
 6497                        position,
 6498                        breakpoint.as_ref().clone(),
 6499                        edit_action,
 6500                        cx,
 6501                    );
 6502                }
 6503            }))
 6504            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6505                editor.set_breakpoint_context_menu(
 6506                    row,
 6507                    Some(position),
 6508                    event.down.position,
 6509                    window,
 6510                    cx,
 6511                );
 6512            }))
 6513    }
 6514
 6515    fn build_tasks_context(
 6516        project: &Entity<Project>,
 6517        buffer: &Entity<Buffer>,
 6518        buffer_row: u32,
 6519        tasks: &Arc<RunnableTasks>,
 6520        cx: &mut Context<Self>,
 6521    ) -> Task<Option<task::TaskContext>> {
 6522        let position = Point::new(buffer_row, tasks.column);
 6523        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6524        let location = Location {
 6525            buffer: buffer.clone(),
 6526            range: range_start..range_start,
 6527        };
 6528        // Fill in the environmental variables from the tree-sitter captures
 6529        let mut captured_task_variables = TaskVariables::default();
 6530        for (capture_name, value) in tasks.extra_variables.clone() {
 6531            captured_task_variables.insert(
 6532                task::VariableName::Custom(capture_name.into()),
 6533                value.clone(),
 6534            );
 6535        }
 6536        project.update(cx, |project, cx| {
 6537            project.task_store().update(cx, |task_store, cx| {
 6538                task_store.task_context_for_location(captured_task_variables, location, cx)
 6539            })
 6540        })
 6541    }
 6542
 6543    pub fn spawn_nearest_task(
 6544        &mut self,
 6545        action: &SpawnNearestTask,
 6546        window: &mut Window,
 6547        cx: &mut Context<Self>,
 6548    ) {
 6549        let Some((workspace, _)) = self.workspace.clone() else {
 6550            return;
 6551        };
 6552        let Some(project) = self.project.clone() else {
 6553            return;
 6554        };
 6555
 6556        // Try to find a closest, enclosing node using tree-sitter that has a
 6557        // task
 6558        let Some((buffer, buffer_row, tasks)) = self
 6559            .find_enclosing_node_task(cx)
 6560            // Or find the task that's closest in row-distance.
 6561            .or_else(|| self.find_closest_task(cx))
 6562        else {
 6563            return;
 6564        };
 6565
 6566        let reveal_strategy = action.reveal;
 6567        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6568        cx.spawn_in(window, async move |_, cx| {
 6569            let context = task_context.await?;
 6570            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6571
 6572            let resolved = resolved_task.resolved.as_mut()?;
 6573            resolved.reveal = reveal_strategy;
 6574
 6575            workspace
 6576                .update(cx, |workspace, cx| {
 6577                    workspace::tasks::schedule_resolved_task(
 6578                        workspace,
 6579                        task_source_kind,
 6580                        resolved_task,
 6581                        false,
 6582                        cx,
 6583                    );
 6584                })
 6585                .ok()
 6586        })
 6587        .detach();
 6588    }
 6589
 6590    fn find_closest_task(
 6591        &mut self,
 6592        cx: &mut Context<Self>,
 6593    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6594        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6595
 6596        let ((buffer_id, row), tasks) = self
 6597            .tasks
 6598            .iter()
 6599            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6600
 6601        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6602        let tasks = Arc::new(tasks.to_owned());
 6603        Some((buffer, *row, tasks))
 6604    }
 6605
 6606    fn find_enclosing_node_task(
 6607        &mut self,
 6608        cx: &mut Context<Self>,
 6609    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6610        let snapshot = self.buffer.read(cx).snapshot(cx);
 6611        let offset = self.selections.newest::<usize>(cx).head();
 6612        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6613        let buffer_id = excerpt.buffer().remote_id();
 6614
 6615        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6616        let mut cursor = layer.node().walk();
 6617
 6618        while cursor.goto_first_child_for_byte(offset).is_some() {
 6619            if cursor.node().end_byte() == offset {
 6620                cursor.goto_next_sibling();
 6621            }
 6622        }
 6623
 6624        // Ascend to the smallest ancestor that contains the range and has a task.
 6625        loop {
 6626            let node = cursor.node();
 6627            let node_range = node.byte_range();
 6628            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6629
 6630            // Check if this node contains our offset
 6631            if node_range.start <= offset && node_range.end >= offset {
 6632                // If it contains offset, check for task
 6633                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6634                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6635                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6636                }
 6637            }
 6638
 6639            if !cursor.goto_parent() {
 6640                break;
 6641            }
 6642        }
 6643        None
 6644    }
 6645
 6646    fn render_run_indicator(
 6647        &self,
 6648        _style: &EditorStyle,
 6649        is_active: bool,
 6650        row: DisplayRow,
 6651        breakpoint: Option<(Anchor, Breakpoint)>,
 6652        cx: &mut Context<Self>,
 6653    ) -> IconButton {
 6654        let color = Color::Muted;
 6655        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6656
 6657        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6658            .shape(ui::IconButtonShape::Square)
 6659            .icon_size(IconSize::XSmall)
 6660            .icon_color(color)
 6661            .toggle_state(is_active)
 6662            .on_click(cx.listener(move |editor, _e, window, cx| {
 6663                window.focus(&editor.focus_handle(cx));
 6664                editor.toggle_code_actions(
 6665                    &ToggleCodeActions {
 6666                        deployed_from_indicator: Some(row),
 6667                    },
 6668                    window,
 6669                    cx,
 6670                );
 6671            }))
 6672            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6673                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6674            }))
 6675    }
 6676
 6677    pub fn context_menu_visible(&self) -> bool {
 6678        !self.edit_prediction_preview_is_active()
 6679            && self
 6680                .context_menu
 6681                .borrow()
 6682                .as_ref()
 6683                .map_or(false, |menu| menu.visible())
 6684    }
 6685
 6686    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6687        self.context_menu
 6688            .borrow()
 6689            .as_ref()
 6690            .map(|menu| menu.origin())
 6691    }
 6692
 6693    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6694        self.context_menu_options = Some(options);
 6695    }
 6696
 6697    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6698    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6699
 6700    fn render_edit_prediction_popover(
 6701        &mut self,
 6702        text_bounds: &Bounds<Pixels>,
 6703        content_origin: gpui::Point<Pixels>,
 6704        editor_snapshot: &EditorSnapshot,
 6705        visible_row_range: Range<DisplayRow>,
 6706        scroll_top: f32,
 6707        scroll_bottom: f32,
 6708        line_layouts: &[LineWithInvisibles],
 6709        line_height: Pixels,
 6710        scroll_pixel_position: gpui::Point<Pixels>,
 6711        newest_selection_head: Option<DisplayPoint>,
 6712        editor_width: Pixels,
 6713        style: &EditorStyle,
 6714        window: &mut Window,
 6715        cx: &mut App,
 6716    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6717        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6718
 6719        if self.edit_prediction_visible_in_cursor_popover(true) {
 6720            return None;
 6721        }
 6722
 6723        match &active_inline_completion.completion {
 6724            InlineCompletion::Move { target, .. } => {
 6725                let target_display_point = target.to_display_point(editor_snapshot);
 6726
 6727                if self.edit_prediction_requires_modifier() {
 6728                    if !self.edit_prediction_preview_is_active() {
 6729                        return None;
 6730                    }
 6731
 6732                    self.render_edit_prediction_modifier_jump_popover(
 6733                        text_bounds,
 6734                        content_origin,
 6735                        visible_row_range,
 6736                        line_layouts,
 6737                        line_height,
 6738                        scroll_pixel_position,
 6739                        newest_selection_head,
 6740                        target_display_point,
 6741                        window,
 6742                        cx,
 6743                    )
 6744                } else {
 6745                    self.render_edit_prediction_eager_jump_popover(
 6746                        text_bounds,
 6747                        content_origin,
 6748                        editor_snapshot,
 6749                        visible_row_range,
 6750                        scroll_top,
 6751                        scroll_bottom,
 6752                        line_height,
 6753                        scroll_pixel_position,
 6754                        target_display_point,
 6755                        editor_width,
 6756                        window,
 6757                        cx,
 6758                    )
 6759                }
 6760            }
 6761            InlineCompletion::Edit {
 6762                display_mode: EditDisplayMode::Inline,
 6763                ..
 6764            } => None,
 6765            InlineCompletion::Edit {
 6766                display_mode: EditDisplayMode::TabAccept,
 6767                edits,
 6768                ..
 6769            } => {
 6770                let range = &edits.first()?.0;
 6771                let target_display_point = range.end.to_display_point(editor_snapshot);
 6772
 6773                self.render_edit_prediction_end_of_line_popover(
 6774                    "Accept",
 6775                    editor_snapshot,
 6776                    visible_row_range,
 6777                    target_display_point,
 6778                    line_height,
 6779                    scroll_pixel_position,
 6780                    content_origin,
 6781                    editor_width,
 6782                    window,
 6783                    cx,
 6784                )
 6785            }
 6786            InlineCompletion::Edit {
 6787                edits,
 6788                edit_preview,
 6789                display_mode: EditDisplayMode::DiffPopover,
 6790                snapshot,
 6791            } => self.render_edit_prediction_diff_popover(
 6792                text_bounds,
 6793                content_origin,
 6794                editor_snapshot,
 6795                visible_row_range,
 6796                line_layouts,
 6797                line_height,
 6798                scroll_pixel_position,
 6799                newest_selection_head,
 6800                editor_width,
 6801                style,
 6802                edits,
 6803                edit_preview,
 6804                snapshot,
 6805                window,
 6806                cx,
 6807            ),
 6808        }
 6809    }
 6810
 6811    fn render_edit_prediction_modifier_jump_popover(
 6812        &mut self,
 6813        text_bounds: &Bounds<Pixels>,
 6814        content_origin: gpui::Point<Pixels>,
 6815        visible_row_range: Range<DisplayRow>,
 6816        line_layouts: &[LineWithInvisibles],
 6817        line_height: Pixels,
 6818        scroll_pixel_position: gpui::Point<Pixels>,
 6819        newest_selection_head: Option<DisplayPoint>,
 6820        target_display_point: DisplayPoint,
 6821        window: &mut Window,
 6822        cx: &mut App,
 6823    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6824        let scrolled_content_origin =
 6825            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6826
 6827        const SCROLL_PADDING_Y: Pixels = px(12.);
 6828
 6829        if target_display_point.row() < visible_row_range.start {
 6830            return self.render_edit_prediction_scroll_popover(
 6831                |_| SCROLL_PADDING_Y,
 6832                IconName::ArrowUp,
 6833                visible_row_range,
 6834                line_layouts,
 6835                newest_selection_head,
 6836                scrolled_content_origin,
 6837                window,
 6838                cx,
 6839            );
 6840        } else if target_display_point.row() >= visible_row_range.end {
 6841            return self.render_edit_prediction_scroll_popover(
 6842                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6843                IconName::ArrowDown,
 6844                visible_row_range,
 6845                line_layouts,
 6846                newest_selection_head,
 6847                scrolled_content_origin,
 6848                window,
 6849                cx,
 6850            );
 6851        }
 6852
 6853        const POLE_WIDTH: Pixels = px(2.);
 6854
 6855        let line_layout =
 6856            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6857        let target_column = target_display_point.column() as usize;
 6858
 6859        let target_x = line_layout.x_for_index(target_column);
 6860        let target_y =
 6861            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6862
 6863        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6864
 6865        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6866        border_color.l += 0.001;
 6867
 6868        let mut element = v_flex()
 6869            .items_end()
 6870            .when(flag_on_right, |el| el.items_start())
 6871            .child(if flag_on_right {
 6872                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6873                    .rounded_bl(px(0.))
 6874                    .rounded_tl(px(0.))
 6875                    .border_l_2()
 6876                    .border_color(border_color)
 6877            } else {
 6878                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6879                    .rounded_br(px(0.))
 6880                    .rounded_tr(px(0.))
 6881                    .border_r_2()
 6882                    .border_color(border_color)
 6883            })
 6884            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6885            .into_any();
 6886
 6887        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6888
 6889        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6890            - point(
 6891                if flag_on_right {
 6892                    POLE_WIDTH
 6893                } else {
 6894                    size.width - POLE_WIDTH
 6895                },
 6896                size.height - line_height,
 6897            );
 6898
 6899        origin.x = origin.x.max(content_origin.x);
 6900
 6901        element.prepaint_at(origin, window, cx);
 6902
 6903        Some((element, origin))
 6904    }
 6905
 6906    fn render_edit_prediction_scroll_popover(
 6907        &mut self,
 6908        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6909        scroll_icon: IconName,
 6910        visible_row_range: Range<DisplayRow>,
 6911        line_layouts: &[LineWithInvisibles],
 6912        newest_selection_head: Option<DisplayPoint>,
 6913        scrolled_content_origin: gpui::Point<Pixels>,
 6914        window: &mut Window,
 6915        cx: &mut App,
 6916    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6917        let mut element = self
 6918            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6919            .into_any();
 6920
 6921        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6922
 6923        let cursor = newest_selection_head?;
 6924        let cursor_row_layout =
 6925            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6926        let cursor_column = cursor.column() as usize;
 6927
 6928        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6929
 6930        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6931
 6932        element.prepaint_at(origin, window, cx);
 6933        Some((element, origin))
 6934    }
 6935
 6936    fn render_edit_prediction_eager_jump_popover(
 6937        &mut self,
 6938        text_bounds: &Bounds<Pixels>,
 6939        content_origin: gpui::Point<Pixels>,
 6940        editor_snapshot: &EditorSnapshot,
 6941        visible_row_range: Range<DisplayRow>,
 6942        scroll_top: f32,
 6943        scroll_bottom: f32,
 6944        line_height: Pixels,
 6945        scroll_pixel_position: gpui::Point<Pixels>,
 6946        target_display_point: DisplayPoint,
 6947        editor_width: Pixels,
 6948        window: &mut Window,
 6949        cx: &mut App,
 6950    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6951        if target_display_point.row().as_f32() < scroll_top {
 6952            let mut element = self
 6953                .render_edit_prediction_line_popover(
 6954                    "Jump to Edit",
 6955                    Some(IconName::ArrowUp),
 6956                    window,
 6957                    cx,
 6958                )?
 6959                .into_any();
 6960
 6961            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6962            let offset = point(
 6963                (text_bounds.size.width - size.width) / 2.,
 6964                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6965            );
 6966
 6967            let origin = text_bounds.origin + offset;
 6968            element.prepaint_at(origin, window, cx);
 6969            Some((element, origin))
 6970        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6971            let mut element = self
 6972                .render_edit_prediction_line_popover(
 6973                    "Jump to Edit",
 6974                    Some(IconName::ArrowDown),
 6975                    window,
 6976                    cx,
 6977                )?
 6978                .into_any();
 6979
 6980            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6981            let offset = point(
 6982                (text_bounds.size.width - size.width) / 2.,
 6983                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6984            );
 6985
 6986            let origin = text_bounds.origin + offset;
 6987            element.prepaint_at(origin, window, cx);
 6988            Some((element, origin))
 6989        } else {
 6990            self.render_edit_prediction_end_of_line_popover(
 6991                "Jump to Edit",
 6992                editor_snapshot,
 6993                visible_row_range,
 6994                target_display_point,
 6995                line_height,
 6996                scroll_pixel_position,
 6997                content_origin,
 6998                editor_width,
 6999                window,
 7000                cx,
 7001            )
 7002        }
 7003    }
 7004
 7005    fn render_edit_prediction_end_of_line_popover(
 7006        self: &mut Editor,
 7007        label: &'static str,
 7008        editor_snapshot: &EditorSnapshot,
 7009        visible_row_range: Range<DisplayRow>,
 7010        target_display_point: DisplayPoint,
 7011        line_height: Pixels,
 7012        scroll_pixel_position: gpui::Point<Pixels>,
 7013        content_origin: gpui::Point<Pixels>,
 7014        editor_width: Pixels,
 7015        window: &mut Window,
 7016        cx: &mut App,
 7017    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7018        let target_line_end = DisplayPoint::new(
 7019            target_display_point.row(),
 7020            editor_snapshot.line_len(target_display_point.row()),
 7021        );
 7022
 7023        let mut element = self
 7024            .render_edit_prediction_line_popover(label, None, window, cx)?
 7025            .into_any();
 7026
 7027        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7028
 7029        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7030
 7031        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7032        let mut origin = start_point
 7033            + line_origin
 7034            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7035        origin.x = origin.x.max(content_origin.x);
 7036
 7037        let max_x = content_origin.x + editor_width - size.width;
 7038
 7039        if origin.x > max_x {
 7040            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7041
 7042            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7043                origin.y += offset;
 7044                IconName::ArrowUp
 7045            } else {
 7046                origin.y -= offset;
 7047                IconName::ArrowDown
 7048            };
 7049
 7050            element = self
 7051                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7052                .into_any();
 7053
 7054            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7055
 7056            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7057        }
 7058
 7059        element.prepaint_at(origin, window, cx);
 7060        Some((element, origin))
 7061    }
 7062
 7063    fn render_edit_prediction_diff_popover(
 7064        self: &Editor,
 7065        text_bounds: &Bounds<Pixels>,
 7066        content_origin: gpui::Point<Pixels>,
 7067        editor_snapshot: &EditorSnapshot,
 7068        visible_row_range: Range<DisplayRow>,
 7069        line_layouts: &[LineWithInvisibles],
 7070        line_height: Pixels,
 7071        scroll_pixel_position: gpui::Point<Pixels>,
 7072        newest_selection_head: Option<DisplayPoint>,
 7073        editor_width: Pixels,
 7074        style: &EditorStyle,
 7075        edits: &Vec<(Range<Anchor>, String)>,
 7076        edit_preview: &Option<language::EditPreview>,
 7077        snapshot: &language::BufferSnapshot,
 7078        window: &mut Window,
 7079        cx: &mut App,
 7080    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7081        let edit_start = edits
 7082            .first()
 7083            .unwrap()
 7084            .0
 7085            .start
 7086            .to_display_point(editor_snapshot);
 7087        let edit_end = edits
 7088            .last()
 7089            .unwrap()
 7090            .0
 7091            .end
 7092            .to_display_point(editor_snapshot);
 7093
 7094        let is_visible = visible_row_range.contains(&edit_start.row())
 7095            || visible_row_range.contains(&edit_end.row());
 7096        if !is_visible {
 7097            return None;
 7098        }
 7099
 7100        let highlighted_edits =
 7101            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7102
 7103        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7104        let line_count = highlighted_edits.text.lines().count();
 7105
 7106        const BORDER_WIDTH: Pixels = px(1.);
 7107
 7108        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7109        let has_keybind = keybind.is_some();
 7110
 7111        let mut element = h_flex()
 7112            .items_start()
 7113            .child(
 7114                h_flex()
 7115                    .bg(cx.theme().colors().editor_background)
 7116                    .border(BORDER_WIDTH)
 7117                    .shadow_sm()
 7118                    .border_color(cx.theme().colors().border)
 7119                    .rounded_l_lg()
 7120                    .when(line_count > 1, |el| el.rounded_br_lg())
 7121                    .pr_1()
 7122                    .child(styled_text),
 7123            )
 7124            .child(
 7125                h_flex()
 7126                    .h(line_height + BORDER_WIDTH * 2.)
 7127                    .px_1p5()
 7128                    .gap_1()
 7129                    // Workaround: For some reason, there's a gap if we don't do this
 7130                    .ml(-BORDER_WIDTH)
 7131                    .shadow(smallvec![gpui::BoxShadow {
 7132                        color: gpui::black().opacity(0.05),
 7133                        offset: point(px(1.), px(1.)),
 7134                        blur_radius: px(2.),
 7135                        spread_radius: px(0.),
 7136                    }])
 7137                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7138                    .border(BORDER_WIDTH)
 7139                    .border_color(cx.theme().colors().border)
 7140                    .rounded_r_lg()
 7141                    .id("edit_prediction_diff_popover_keybind")
 7142                    .when(!has_keybind, |el| {
 7143                        let status_colors = cx.theme().status();
 7144
 7145                        el.bg(status_colors.error_background)
 7146                            .border_color(status_colors.error.opacity(0.6))
 7147                            .child(Icon::new(IconName::Info).color(Color::Error))
 7148                            .cursor_default()
 7149                            .hoverable_tooltip(move |_window, cx| {
 7150                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7151                            })
 7152                    })
 7153                    .children(keybind),
 7154            )
 7155            .into_any();
 7156
 7157        let longest_row =
 7158            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7159        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7160            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7161        } else {
 7162            layout_line(
 7163                longest_row,
 7164                editor_snapshot,
 7165                style,
 7166                editor_width,
 7167                |_| false,
 7168                window,
 7169                cx,
 7170            )
 7171            .width
 7172        };
 7173
 7174        let viewport_bounds =
 7175            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7176                right: -EditorElement::SCROLLBAR_WIDTH,
 7177                ..Default::default()
 7178            });
 7179
 7180        let x_after_longest =
 7181            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7182                - scroll_pixel_position.x;
 7183
 7184        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7185
 7186        // Fully visible if it can be displayed within the window (allow overlapping other
 7187        // panes). However, this is only allowed if the popover starts within text_bounds.
 7188        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7189            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7190
 7191        let mut origin = if can_position_to_the_right {
 7192            point(
 7193                x_after_longest,
 7194                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7195                    - scroll_pixel_position.y,
 7196            )
 7197        } else {
 7198            let cursor_row = newest_selection_head.map(|head| head.row());
 7199            let above_edit = edit_start
 7200                .row()
 7201                .0
 7202                .checked_sub(line_count as u32)
 7203                .map(DisplayRow);
 7204            let below_edit = Some(edit_end.row() + 1);
 7205            let above_cursor =
 7206                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7207            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7208
 7209            // Place the edit popover adjacent to the edit if there is a location
 7210            // available that is onscreen and does not obscure the cursor. Otherwise,
 7211            // place it adjacent to the cursor.
 7212            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7213                .into_iter()
 7214                .flatten()
 7215                .find(|&start_row| {
 7216                    let end_row = start_row + line_count as u32;
 7217                    visible_row_range.contains(&start_row)
 7218                        && visible_row_range.contains(&end_row)
 7219                        && cursor_row.map_or(true, |cursor_row| {
 7220                            !((start_row..end_row).contains(&cursor_row))
 7221                        })
 7222                })?;
 7223
 7224            content_origin
 7225                + point(
 7226                    -scroll_pixel_position.x,
 7227                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7228                )
 7229        };
 7230
 7231        origin.x -= BORDER_WIDTH;
 7232
 7233        window.defer_draw(element, origin, 1);
 7234
 7235        // Do not return an element, since it will already be drawn due to defer_draw.
 7236        None
 7237    }
 7238
 7239    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7240        px(30.)
 7241    }
 7242
 7243    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7244        if self.read_only(cx) {
 7245            cx.theme().players().read_only()
 7246        } else {
 7247            self.style.as_ref().unwrap().local_player
 7248        }
 7249    }
 7250
 7251    fn render_edit_prediction_accept_keybind(
 7252        &self,
 7253        window: &mut Window,
 7254        cx: &App,
 7255    ) -> Option<AnyElement> {
 7256        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7257        let accept_keystroke = accept_binding.keystroke()?;
 7258
 7259        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7260
 7261        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7262            Color::Accent
 7263        } else {
 7264            Color::Muted
 7265        };
 7266
 7267        h_flex()
 7268            .px_0p5()
 7269            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7270            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7271            .text_size(TextSize::XSmall.rems(cx))
 7272            .child(h_flex().children(ui::render_modifiers(
 7273                &accept_keystroke.modifiers,
 7274                PlatformStyle::platform(),
 7275                Some(modifiers_color),
 7276                Some(IconSize::XSmall.rems().into()),
 7277                true,
 7278            )))
 7279            .when(is_platform_style_mac, |parent| {
 7280                parent.child(accept_keystroke.key.clone())
 7281            })
 7282            .when(!is_platform_style_mac, |parent| {
 7283                parent.child(
 7284                    Key::new(
 7285                        util::capitalize(&accept_keystroke.key),
 7286                        Some(Color::Default),
 7287                    )
 7288                    .size(Some(IconSize::XSmall.rems().into())),
 7289                )
 7290            })
 7291            .into_any()
 7292            .into()
 7293    }
 7294
 7295    fn render_edit_prediction_line_popover(
 7296        &self,
 7297        label: impl Into<SharedString>,
 7298        icon: Option<IconName>,
 7299        window: &mut Window,
 7300        cx: &App,
 7301    ) -> Option<Stateful<Div>> {
 7302        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7303
 7304        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7305        let has_keybind = keybind.is_some();
 7306
 7307        let result = h_flex()
 7308            .id("ep-line-popover")
 7309            .py_0p5()
 7310            .pl_1()
 7311            .pr(padding_right)
 7312            .gap_1()
 7313            .rounded_md()
 7314            .border_1()
 7315            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7316            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7317            .shadow_sm()
 7318            .when(!has_keybind, |el| {
 7319                let status_colors = cx.theme().status();
 7320
 7321                el.bg(status_colors.error_background)
 7322                    .border_color(status_colors.error.opacity(0.6))
 7323                    .pl_2()
 7324                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7325                    .cursor_default()
 7326                    .hoverable_tooltip(move |_window, cx| {
 7327                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7328                    })
 7329            })
 7330            .children(keybind)
 7331            .child(
 7332                Label::new(label)
 7333                    .size(LabelSize::Small)
 7334                    .when(!has_keybind, |el| {
 7335                        el.color(cx.theme().status().error.into()).strikethrough()
 7336                    }),
 7337            )
 7338            .when(!has_keybind, |el| {
 7339                el.child(
 7340                    h_flex().ml_1().child(
 7341                        Icon::new(IconName::Info)
 7342                            .size(IconSize::Small)
 7343                            .color(cx.theme().status().error.into()),
 7344                    ),
 7345                )
 7346            })
 7347            .when_some(icon, |element, icon| {
 7348                element.child(
 7349                    div()
 7350                        .mt(px(1.5))
 7351                        .child(Icon::new(icon).size(IconSize::Small)),
 7352                )
 7353            });
 7354
 7355        Some(result)
 7356    }
 7357
 7358    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7359        let accent_color = cx.theme().colors().text_accent;
 7360        let editor_bg_color = cx.theme().colors().editor_background;
 7361        editor_bg_color.blend(accent_color.opacity(0.1))
 7362    }
 7363
 7364    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7365        let accent_color = cx.theme().colors().text_accent;
 7366        let editor_bg_color = cx.theme().colors().editor_background;
 7367        editor_bg_color.blend(accent_color.opacity(0.6))
 7368    }
 7369
 7370    fn render_edit_prediction_cursor_popover(
 7371        &self,
 7372        min_width: Pixels,
 7373        max_width: Pixels,
 7374        cursor_point: Point,
 7375        style: &EditorStyle,
 7376        accept_keystroke: Option<&gpui::Keystroke>,
 7377        _window: &Window,
 7378        cx: &mut Context<Editor>,
 7379    ) -> Option<AnyElement> {
 7380        let provider = self.edit_prediction_provider.as_ref()?;
 7381
 7382        if provider.provider.needs_terms_acceptance(cx) {
 7383            return Some(
 7384                h_flex()
 7385                    .min_w(min_width)
 7386                    .flex_1()
 7387                    .px_2()
 7388                    .py_1()
 7389                    .gap_3()
 7390                    .elevation_2(cx)
 7391                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7392                    .id("accept-terms")
 7393                    .cursor_pointer()
 7394                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7395                    .on_click(cx.listener(|this, _event, window, cx| {
 7396                        cx.stop_propagation();
 7397                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7398                        window.dispatch_action(
 7399                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7400                            cx,
 7401                        );
 7402                    }))
 7403                    .child(
 7404                        h_flex()
 7405                            .flex_1()
 7406                            .gap_2()
 7407                            .child(Icon::new(IconName::ZedPredict))
 7408                            .child(Label::new("Accept Terms of Service"))
 7409                            .child(div().w_full())
 7410                            .child(
 7411                                Icon::new(IconName::ArrowUpRight)
 7412                                    .color(Color::Muted)
 7413                                    .size(IconSize::Small),
 7414                            )
 7415                            .into_any_element(),
 7416                    )
 7417                    .into_any(),
 7418            );
 7419        }
 7420
 7421        let is_refreshing = provider.provider.is_refreshing(cx);
 7422
 7423        fn pending_completion_container() -> Div {
 7424            h_flex()
 7425                .h_full()
 7426                .flex_1()
 7427                .gap_2()
 7428                .child(Icon::new(IconName::ZedPredict))
 7429        }
 7430
 7431        let completion = match &self.active_inline_completion {
 7432            Some(prediction) => {
 7433                if !self.has_visible_completions_menu() {
 7434                    const RADIUS: Pixels = px(6.);
 7435                    const BORDER_WIDTH: Pixels = px(1.);
 7436
 7437                    return Some(
 7438                        h_flex()
 7439                            .elevation_2(cx)
 7440                            .border(BORDER_WIDTH)
 7441                            .border_color(cx.theme().colors().border)
 7442                            .when(accept_keystroke.is_none(), |el| {
 7443                                el.border_color(cx.theme().status().error)
 7444                            })
 7445                            .rounded(RADIUS)
 7446                            .rounded_tl(px(0.))
 7447                            .overflow_hidden()
 7448                            .child(div().px_1p5().child(match &prediction.completion {
 7449                                InlineCompletion::Move { target, snapshot } => {
 7450                                    use text::ToPoint as _;
 7451                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7452                                    {
 7453                                        Icon::new(IconName::ZedPredictDown)
 7454                                    } else {
 7455                                        Icon::new(IconName::ZedPredictUp)
 7456                                    }
 7457                                }
 7458                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7459                            }))
 7460                            .child(
 7461                                h_flex()
 7462                                    .gap_1()
 7463                                    .py_1()
 7464                                    .px_2()
 7465                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7466                                    .border_l_1()
 7467                                    .border_color(cx.theme().colors().border)
 7468                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7469                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7470                                        el.child(
 7471                                            Label::new("Hold")
 7472                                                .size(LabelSize::Small)
 7473                                                .when(accept_keystroke.is_none(), |el| {
 7474                                                    el.strikethrough()
 7475                                                })
 7476                                                .line_height_style(LineHeightStyle::UiLabel),
 7477                                        )
 7478                                    })
 7479                                    .id("edit_prediction_cursor_popover_keybind")
 7480                                    .when(accept_keystroke.is_none(), |el| {
 7481                                        let status_colors = cx.theme().status();
 7482
 7483                                        el.bg(status_colors.error_background)
 7484                                            .border_color(status_colors.error.opacity(0.6))
 7485                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7486                                            .cursor_default()
 7487                                            .hoverable_tooltip(move |_window, cx| {
 7488                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7489                                                    .into()
 7490                                            })
 7491                                    })
 7492                                    .when_some(
 7493                                        accept_keystroke.as_ref(),
 7494                                        |el, accept_keystroke| {
 7495                                            el.child(h_flex().children(ui::render_modifiers(
 7496                                                &accept_keystroke.modifiers,
 7497                                                PlatformStyle::platform(),
 7498                                                Some(Color::Default),
 7499                                                Some(IconSize::XSmall.rems().into()),
 7500                                                false,
 7501                                            )))
 7502                                        },
 7503                                    ),
 7504                            )
 7505                            .into_any(),
 7506                    );
 7507                }
 7508
 7509                self.render_edit_prediction_cursor_popover_preview(
 7510                    prediction,
 7511                    cursor_point,
 7512                    style,
 7513                    cx,
 7514                )?
 7515            }
 7516
 7517            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7518                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7519                    stale_completion,
 7520                    cursor_point,
 7521                    style,
 7522                    cx,
 7523                )?,
 7524
 7525                None => {
 7526                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7527                }
 7528            },
 7529
 7530            None => pending_completion_container().child(Label::new("No Prediction")),
 7531        };
 7532
 7533        let completion = if is_refreshing {
 7534            completion
 7535                .with_animation(
 7536                    "loading-completion",
 7537                    Animation::new(Duration::from_secs(2))
 7538                        .repeat()
 7539                        .with_easing(pulsating_between(0.4, 0.8)),
 7540                    |label, delta| label.opacity(delta),
 7541                )
 7542                .into_any_element()
 7543        } else {
 7544            completion.into_any_element()
 7545        };
 7546
 7547        let has_completion = self.active_inline_completion.is_some();
 7548
 7549        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7550        Some(
 7551            h_flex()
 7552                .min_w(min_width)
 7553                .max_w(max_width)
 7554                .flex_1()
 7555                .elevation_2(cx)
 7556                .border_color(cx.theme().colors().border)
 7557                .child(
 7558                    div()
 7559                        .flex_1()
 7560                        .py_1()
 7561                        .px_2()
 7562                        .overflow_hidden()
 7563                        .child(completion),
 7564                )
 7565                .when_some(accept_keystroke, |el, accept_keystroke| {
 7566                    if !accept_keystroke.modifiers.modified() {
 7567                        return el;
 7568                    }
 7569
 7570                    el.child(
 7571                        h_flex()
 7572                            .h_full()
 7573                            .border_l_1()
 7574                            .rounded_r_lg()
 7575                            .border_color(cx.theme().colors().border)
 7576                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7577                            .gap_1()
 7578                            .py_1()
 7579                            .px_2()
 7580                            .child(
 7581                                h_flex()
 7582                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7583                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7584                                    .child(h_flex().children(ui::render_modifiers(
 7585                                        &accept_keystroke.modifiers,
 7586                                        PlatformStyle::platform(),
 7587                                        Some(if !has_completion {
 7588                                            Color::Muted
 7589                                        } else {
 7590                                            Color::Default
 7591                                        }),
 7592                                        None,
 7593                                        false,
 7594                                    ))),
 7595                            )
 7596                            .child(Label::new("Preview").into_any_element())
 7597                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7598                    )
 7599                })
 7600                .into_any(),
 7601        )
 7602    }
 7603
 7604    fn render_edit_prediction_cursor_popover_preview(
 7605        &self,
 7606        completion: &InlineCompletionState,
 7607        cursor_point: Point,
 7608        style: &EditorStyle,
 7609        cx: &mut Context<Editor>,
 7610    ) -> Option<Div> {
 7611        use text::ToPoint as _;
 7612
 7613        fn render_relative_row_jump(
 7614            prefix: impl Into<String>,
 7615            current_row: u32,
 7616            target_row: u32,
 7617        ) -> Div {
 7618            let (row_diff, arrow) = if target_row < current_row {
 7619                (current_row - target_row, IconName::ArrowUp)
 7620            } else {
 7621                (target_row - current_row, IconName::ArrowDown)
 7622            };
 7623
 7624            h_flex()
 7625                .child(
 7626                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7627                        .color(Color::Muted)
 7628                        .size(LabelSize::Small),
 7629                )
 7630                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7631        }
 7632
 7633        match &completion.completion {
 7634            InlineCompletion::Move {
 7635                target, snapshot, ..
 7636            } => Some(
 7637                h_flex()
 7638                    .px_2()
 7639                    .gap_2()
 7640                    .flex_1()
 7641                    .child(
 7642                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7643                            Icon::new(IconName::ZedPredictDown)
 7644                        } else {
 7645                            Icon::new(IconName::ZedPredictUp)
 7646                        },
 7647                    )
 7648                    .child(Label::new("Jump to Edit")),
 7649            ),
 7650
 7651            InlineCompletion::Edit {
 7652                edits,
 7653                edit_preview,
 7654                snapshot,
 7655                display_mode: _,
 7656            } => {
 7657                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7658
 7659                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7660                    &snapshot,
 7661                    &edits,
 7662                    edit_preview.as_ref()?,
 7663                    true,
 7664                    cx,
 7665                )
 7666                .first_line_preview();
 7667
 7668                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7669                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7670
 7671                let preview = h_flex()
 7672                    .gap_1()
 7673                    .min_w_16()
 7674                    .child(styled_text)
 7675                    .when(has_more_lines, |parent| parent.child(""));
 7676
 7677                let left = if first_edit_row != cursor_point.row {
 7678                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7679                        .into_any_element()
 7680                } else {
 7681                    Icon::new(IconName::ZedPredict).into_any_element()
 7682                };
 7683
 7684                Some(
 7685                    h_flex()
 7686                        .h_full()
 7687                        .flex_1()
 7688                        .gap_2()
 7689                        .pr_1()
 7690                        .overflow_x_hidden()
 7691                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7692                        .child(left)
 7693                        .child(preview),
 7694                )
 7695            }
 7696        }
 7697    }
 7698
 7699    fn render_context_menu(
 7700        &self,
 7701        style: &EditorStyle,
 7702        max_height_in_lines: u32,
 7703        y_flipped: bool,
 7704        window: &mut Window,
 7705        cx: &mut Context<Editor>,
 7706    ) -> Option<AnyElement> {
 7707        let menu = self.context_menu.borrow();
 7708        let menu = menu.as_ref()?;
 7709        if !menu.visible() {
 7710            return None;
 7711        };
 7712        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 7713    }
 7714
 7715    fn render_context_menu_aside(
 7716        &mut self,
 7717        max_size: Size<Pixels>,
 7718        window: &mut Window,
 7719        cx: &mut Context<Editor>,
 7720    ) -> Option<AnyElement> {
 7721        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7722            if menu.visible() {
 7723                menu.render_aside(self, max_size, window, cx)
 7724            } else {
 7725                None
 7726            }
 7727        })
 7728    }
 7729
 7730    fn hide_context_menu(
 7731        &mut self,
 7732        window: &mut Window,
 7733        cx: &mut Context<Self>,
 7734    ) -> Option<CodeContextMenu> {
 7735        cx.notify();
 7736        self.completion_tasks.clear();
 7737        let context_menu = self.context_menu.borrow_mut().take();
 7738        self.stale_inline_completion_in_menu.take();
 7739        self.update_visible_inline_completion(window, cx);
 7740        context_menu
 7741    }
 7742
 7743    fn show_snippet_choices(
 7744        &mut self,
 7745        choices: &Vec<String>,
 7746        selection: Range<Anchor>,
 7747        cx: &mut Context<Self>,
 7748    ) {
 7749        if selection.start.buffer_id.is_none() {
 7750            return;
 7751        }
 7752        let buffer_id = selection.start.buffer_id.unwrap();
 7753        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7754        let id = post_inc(&mut self.next_completion_id);
 7755
 7756        if let Some(buffer) = buffer {
 7757            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7758                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7759            ));
 7760        }
 7761    }
 7762
 7763    pub fn insert_snippet(
 7764        &mut self,
 7765        insertion_ranges: &[Range<usize>],
 7766        snippet: Snippet,
 7767        window: &mut Window,
 7768        cx: &mut Context<Self>,
 7769    ) -> Result<()> {
 7770        struct Tabstop<T> {
 7771            is_end_tabstop: bool,
 7772            ranges: Vec<Range<T>>,
 7773            choices: Option<Vec<String>>,
 7774        }
 7775
 7776        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7777            let snippet_text: Arc<str> = snippet.text.clone().into();
 7778            let edits = insertion_ranges
 7779                .iter()
 7780                .cloned()
 7781                .map(|range| (range, snippet_text.clone()));
 7782            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 7783
 7784            let snapshot = &*buffer.read(cx);
 7785            let snippet = &snippet;
 7786            snippet
 7787                .tabstops
 7788                .iter()
 7789                .map(|tabstop| {
 7790                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7791                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7792                    });
 7793                    let mut tabstop_ranges = tabstop
 7794                        .ranges
 7795                        .iter()
 7796                        .flat_map(|tabstop_range| {
 7797                            let mut delta = 0_isize;
 7798                            insertion_ranges.iter().map(move |insertion_range| {
 7799                                let insertion_start = insertion_range.start as isize + delta;
 7800                                delta +=
 7801                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7802
 7803                                let start = ((insertion_start + tabstop_range.start) as usize)
 7804                                    .min(snapshot.len());
 7805                                let end = ((insertion_start + tabstop_range.end) as usize)
 7806                                    .min(snapshot.len());
 7807                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7808                            })
 7809                        })
 7810                        .collect::<Vec<_>>();
 7811                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7812
 7813                    Tabstop {
 7814                        is_end_tabstop,
 7815                        ranges: tabstop_ranges,
 7816                        choices: tabstop.choices.clone(),
 7817                    }
 7818                })
 7819                .collect::<Vec<_>>()
 7820        });
 7821        if let Some(tabstop) = tabstops.first() {
 7822            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7823                s.select_ranges(tabstop.ranges.iter().cloned());
 7824            });
 7825
 7826            if let Some(choices) = &tabstop.choices {
 7827                if let Some(selection) = tabstop.ranges.first() {
 7828                    self.show_snippet_choices(choices, selection.clone(), cx)
 7829                }
 7830            }
 7831
 7832            // If we're already at the last tabstop and it's at the end of the snippet,
 7833            // we're done, we don't need to keep the state around.
 7834            if !tabstop.is_end_tabstop {
 7835                let choices = tabstops
 7836                    .iter()
 7837                    .map(|tabstop| tabstop.choices.clone())
 7838                    .collect();
 7839
 7840                let ranges = tabstops
 7841                    .into_iter()
 7842                    .map(|tabstop| tabstop.ranges)
 7843                    .collect::<Vec<_>>();
 7844
 7845                self.snippet_stack.push(SnippetState {
 7846                    active_index: 0,
 7847                    ranges,
 7848                    choices,
 7849                });
 7850            }
 7851
 7852            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7853            if self.autoclose_regions.is_empty() {
 7854                let snapshot = self.buffer.read(cx).snapshot(cx);
 7855                for selection in &mut self.selections.all::<Point>(cx) {
 7856                    let selection_head = selection.head();
 7857                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7858                        continue;
 7859                    };
 7860
 7861                    let mut bracket_pair = None;
 7862                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7863                    let prev_chars = snapshot
 7864                        .reversed_chars_at(selection_head)
 7865                        .collect::<String>();
 7866                    for (pair, enabled) in scope.brackets() {
 7867                        if enabled
 7868                            && pair.close
 7869                            && prev_chars.starts_with(pair.start.as_str())
 7870                            && next_chars.starts_with(pair.end.as_str())
 7871                        {
 7872                            bracket_pair = Some(pair.clone());
 7873                            break;
 7874                        }
 7875                    }
 7876                    if let Some(pair) = bracket_pair {
 7877                        let start = snapshot.anchor_after(selection_head);
 7878                        let end = snapshot.anchor_after(selection_head);
 7879                        self.autoclose_regions.push(AutocloseRegion {
 7880                            selection_id: selection.id,
 7881                            range: start..end,
 7882                            pair,
 7883                        });
 7884                    }
 7885                }
 7886            }
 7887        }
 7888        Ok(())
 7889    }
 7890
 7891    pub fn move_to_next_snippet_tabstop(
 7892        &mut self,
 7893        window: &mut Window,
 7894        cx: &mut Context<Self>,
 7895    ) -> bool {
 7896        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7897    }
 7898
 7899    pub fn move_to_prev_snippet_tabstop(
 7900        &mut self,
 7901        window: &mut Window,
 7902        cx: &mut Context<Self>,
 7903    ) -> bool {
 7904        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7905    }
 7906
 7907    pub fn move_to_snippet_tabstop(
 7908        &mut self,
 7909        bias: Bias,
 7910        window: &mut Window,
 7911        cx: &mut Context<Self>,
 7912    ) -> bool {
 7913        if let Some(mut snippet) = self.snippet_stack.pop() {
 7914            match bias {
 7915                Bias::Left => {
 7916                    if snippet.active_index > 0 {
 7917                        snippet.active_index -= 1;
 7918                    } else {
 7919                        self.snippet_stack.push(snippet);
 7920                        return false;
 7921                    }
 7922                }
 7923                Bias::Right => {
 7924                    if snippet.active_index + 1 < snippet.ranges.len() {
 7925                        snippet.active_index += 1;
 7926                    } else {
 7927                        self.snippet_stack.push(snippet);
 7928                        return false;
 7929                    }
 7930                }
 7931            }
 7932            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7933                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7934                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7935                });
 7936
 7937                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7938                    if let Some(selection) = current_ranges.first() {
 7939                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7940                    }
 7941                }
 7942
 7943                // If snippet state is not at the last tabstop, push it back on the stack
 7944                if snippet.active_index + 1 < snippet.ranges.len() {
 7945                    self.snippet_stack.push(snippet);
 7946                }
 7947                return true;
 7948            }
 7949        }
 7950
 7951        false
 7952    }
 7953
 7954    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7955        self.transact(window, cx, |this, window, cx| {
 7956            this.select_all(&SelectAll, window, cx);
 7957            this.insert("", window, cx);
 7958        });
 7959    }
 7960
 7961    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7962        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 7963        self.transact(window, cx, |this, window, cx| {
 7964            this.select_autoclose_pair(window, cx);
 7965            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7966            if !this.linked_edit_ranges.is_empty() {
 7967                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7968                let snapshot = this.buffer.read(cx).snapshot(cx);
 7969
 7970                for selection in selections.iter() {
 7971                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7972                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7973                    if selection_start.buffer_id != selection_end.buffer_id {
 7974                        continue;
 7975                    }
 7976                    if let Some(ranges) =
 7977                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7978                    {
 7979                        for (buffer, entries) in ranges {
 7980                            linked_ranges.entry(buffer).or_default().extend(entries);
 7981                        }
 7982                    }
 7983                }
 7984            }
 7985
 7986            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7987            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7988            for selection in &mut selections {
 7989                if selection.is_empty() {
 7990                    let old_head = selection.head();
 7991                    let mut new_head =
 7992                        movement::left(&display_map, old_head.to_display_point(&display_map))
 7993                            .to_point(&display_map);
 7994                    if let Some((buffer, line_buffer_range)) = display_map
 7995                        .buffer_snapshot
 7996                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 7997                    {
 7998                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 7999                        let indent_len = match indent_size.kind {
 8000                            IndentKind::Space => {
 8001                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8002                            }
 8003                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8004                        };
 8005                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8006                            let indent_len = indent_len.get();
 8007                            new_head = cmp::min(
 8008                                new_head,
 8009                                MultiBufferPoint::new(
 8010                                    old_head.row,
 8011                                    ((old_head.column - 1) / indent_len) * indent_len,
 8012                                ),
 8013                            );
 8014                        }
 8015                    }
 8016
 8017                    selection.set_head(new_head, SelectionGoal::None);
 8018                }
 8019            }
 8020
 8021            this.signature_help_state.set_backspace_pressed(true);
 8022            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8023                s.select(selections)
 8024            });
 8025            this.insert("", window, cx);
 8026            let empty_str: Arc<str> = Arc::from("");
 8027            for (buffer, edits) in linked_ranges {
 8028                let snapshot = buffer.read(cx).snapshot();
 8029                use text::ToPoint as TP;
 8030
 8031                let edits = edits
 8032                    .into_iter()
 8033                    .map(|range| {
 8034                        let end_point = TP::to_point(&range.end, &snapshot);
 8035                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8036
 8037                        if end_point == start_point {
 8038                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8039                                .saturating_sub(1);
 8040                            start_point =
 8041                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8042                        };
 8043
 8044                        (start_point..end_point, empty_str.clone())
 8045                    })
 8046                    .sorted_by_key(|(range, _)| range.start)
 8047                    .collect::<Vec<_>>();
 8048                buffer.update(cx, |this, cx| {
 8049                    this.edit(edits, None, cx);
 8050                })
 8051            }
 8052            this.refresh_inline_completion(true, false, window, cx);
 8053            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8054        });
 8055    }
 8056
 8057    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8058        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8059        self.transact(window, cx, |this, window, cx| {
 8060            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8061                s.move_with(|map, selection| {
 8062                    if selection.is_empty() {
 8063                        let cursor = movement::right(map, selection.head());
 8064                        selection.end = cursor;
 8065                        selection.reversed = true;
 8066                        selection.goal = SelectionGoal::None;
 8067                    }
 8068                })
 8069            });
 8070            this.insert("", window, cx);
 8071            this.refresh_inline_completion(true, false, window, cx);
 8072        });
 8073    }
 8074
 8075    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8076        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8077        if self.move_to_prev_snippet_tabstop(window, cx) {
 8078            return;
 8079        }
 8080        self.outdent(&Outdent, window, cx);
 8081    }
 8082
 8083    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8084        if self.move_to_next_snippet_tabstop(window, cx) {
 8085            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8086            return;
 8087        }
 8088        if self.read_only(cx) {
 8089            return;
 8090        }
 8091        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8092        let mut selections = self.selections.all_adjusted(cx);
 8093        let buffer = self.buffer.read(cx);
 8094        let snapshot = buffer.snapshot(cx);
 8095        let rows_iter = selections.iter().map(|s| s.head().row);
 8096        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8097
 8098        let mut edits = Vec::new();
 8099        let mut prev_edited_row = 0;
 8100        let mut row_delta = 0;
 8101        for selection in &mut selections {
 8102            if selection.start.row != prev_edited_row {
 8103                row_delta = 0;
 8104            }
 8105            prev_edited_row = selection.end.row;
 8106
 8107            // If the selection is non-empty, then increase the indentation of the selected lines.
 8108            if !selection.is_empty() {
 8109                row_delta =
 8110                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8111                continue;
 8112            }
 8113
 8114            // If the selection is empty and the cursor is in the leading whitespace before the
 8115            // suggested indentation, then auto-indent the line.
 8116            let cursor = selection.head();
 8117            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8118            if let Some(suggested_indent) =
 8119                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8120            {
 8121                if cursor.column < suggested_indent.len
 8122                    && cursor.column <= current_indent.len
 8123                    && current_indent.len <= suggested_indent.len
 8124                {
 8125                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8126                    selection.end = selection.start;
 8127                    if row_delta == 0 {
 8128                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8129                            cursor.row,
 8130                            current_indent,
 8131                            suggested_indent,
 8132                        ));
 8133                        row_delta = suggested_indent.len - current_indent.len;
 8134                    }
 8135                    continue;
 8136                }
 8137            }
 8138
 8139            // Otherwise, insert a hard or soft tab.
 8140            let settings = buffer.language_settings_at(cursor, cx);
 8141            let tab_size = if settings.hard_tabs {
 8142                IndentSize::tab()
 8143            } else {
 8144                let tab_size = settings.tab_size.get();
 8145                let char_column = snapshot
 8146                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8147                    .flat_map(str::chars)
 8148                    .count()
 8149                    + row_delta as usize;
 8150                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 8151                IndentSize::spaces(chars_to_next_tab_stop)
 8152            };
 8153            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8154            selection.end = selection.start;
 8155            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8156            row_delta += tab_size.len;
 8157        }
 8158
 8159        self.transact(window, cx, |this, window, cx| {
 8160            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8161            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8162                s.select(selections)
 8163            });
 8164            this.refresh_inline_completion(true, false, window, cx);
 8165        });
 8166    }
 8167
 8168    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8169        if self.read_only(cx) {
 8170            return;
 8171        }
 8172        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8173        let mut selections = self.selections.all::<Point>(cx);
 8174        let mut prev_edited_row = 0;
 8175        let mut row_delta = 0;
 8176        let mut edits = Vec::new();
 8177        let buffer = self.buffer.read(cx);
 8178        let snapshot = buffer.snapshot(cx);
 8179        for selection in &mut selections {
 8180            if selection.start.row != prev_edited_row {
 8181                row_delta = 0;
 8182            }
 8183            prev_edited_row = selection.end.row;
 8184
 8185            row_delta =
 8186                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8187        }
 8188
 8189        self.transact(window, cx, |this, window, cx| {
 8190            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8191            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8192                s.select(selections)
 8193            });
 8194        });
 8195    }
 8196
 8197    fn indent_selection(
 8198        buffer: &MultiBuffer,
 8199        snapshot: &MultiBufferSnapshot,
 8200        selection: &mut Selection<Point>,
 8201        edits: &mut Vec<(Range<Point>, String)>,
 8202        delta_for_start_row: u32,
 8203        cx: &App,
 8204    ) -> u32 {
 8205        let settings = buffer.language_settings_at(selection.start, cx);
 8206        let tab_size = settings.tab_size.get();
 8207        let indent_kind = if settings.hard_tabs {
 8208            IndentKind::Tab
 8209        } else {
 8210            IndentKind::Space
 8211        };
 8212        let mut start_row = selection.start.row;
 8213        let mut end_row = selection.end.row + 1;
 8214
 8215        // If a selection ends at the beginning of a line, don't indent
 8216        // that last line.
 8217        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8218            end_row -= 1;
 8219        }
 8220
 8221        // Avoid re-indenting a row that has already been indented by a
 8222        // previous selection, but still update this selection's column
 8223        // to reflect that indentation.
 8224        if delta_for_start_row > 0 {
 8225            start_row += 1;
 8226            selection.start.column += delta_for_start_row;
 8227            if selection.end.row == selection.start.row {
 8228                selection.end.column += delta_for_start_row;
 8229            }
 8230        }
 8231
 8232        let mut delta_for_end_row = 0;
 8233        let has_multiple_rows = start_row + 1 != end_row;
 8234        for row in start_row..end_row {
 8235            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8236            let indent_delta = match (current_indent.kind, indent_kind) {
 8237                (IndentKind::Space, IndentKind::Space) => {
 8238                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8239                    IndentSize::spaces(columns_to_next_tab_stop)
 8240                }
 8241                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8242                (_, IndentKind::Tab) => IndentSize::tab(),
 8243            };
 8244
 8245            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8246                0
 8247            } else {
 8248                selection.start.column
 8249            };
 8250            let row_start = Point::new(row, start);
 8251            edits.push((
 8252                row_start..row_start,
 8253                indent_delta.chars().collect::<String>(),
 8254            ));
 8255
 8256            // Update this selection's endpoints to reflect the indentation.
 8257            if row == selection.start.row {
 8258                selection.start.column += indent_delta.len;
 8259            }
 8260            if row == selection.end.row {
 8261                selection.end.column += indent_delta.len;
 8262                delta_for_end_row = indent_delta.len;
 8263            }
 8264        }
 8265
 8266        if selection.start.row == selection.end.row {
 8267            delta_for_start_row + delta_for_end_row
 8268        } else {
 8269            delta_for_end_row
 8270        }
 8271    }
 8272
 8273    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8274        if self.read_only(cx) {
 8275            return;
 8276        }
 8277        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8278        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8279        let selections = self.selections.all::<Point>(cx);
 8280        let mut deletion_ranges = Vec::new();
 8281        let mut last_outdent = None;
 8282        {
 8283            let buffer = self.buffer.read(cx);
 8284            let snapshot = buffer.snapshot(cx);
 8285            for selection in &selections {
 8286                let settings = buffer.language_settings_at(selection.start, cx);
 8287                let tab_size = settings.tab_size.get();
 8288                let mut rows = selection.spanned_rows(false, &display_map);
 8289
 8290                // Avoid re-outdenting a row that has already been outdented by a
 8291                // previous selection.
 8292                if let Some(last_row) = last_outdent {
 8293                    if last_row == rows.start {
 8294                        rows.start = rows.start.next_row();
 8295                    }
 8296                }
 8297                let has_multiple_rows = rows.len() > 1;
 8298                for row in rows.iter_rows() {
 8299                    let indent_size = snapshot.indent_size_for_line(row);
 8300                    if indent_size.len > 0 {
 8301                        let deletion_len = match indent_size.kind {
 8302                            IndentKind::Space => {
 8303                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8304                                if columns_to_prev_tab_stop == 0 {
 8305                                    tab_size
 8306                                } else {
 8307                                    columns_to_prev_tab_stop
 8308                                }
 8309                            }
 8310                            IndentKind::Tab => 1,
 8311                        };
 8312                        let start = if has_multiple_rows
 8313                            || deletion_len > selection.start.column
 8314                            || indent_size.len < selection.start.column
 8315                        {
 8316                            0
 8317                        } else {
 8318                            selection.start.column - deletion_len
 8319                        };
 8320                        deletion_ranges.push(
 8321                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8322                        );
 8323                        last_outdent = Some(row);
 8324                    }
 8325                }
 8326            }
 8327        }
 8328
 8329        self.transact(window, cx, |this, window, cx| {
 8330            this.buffer.update(cx, |buffer, cx| {
 8331                let empty_str: Arc<str> = Arc::default();
 8332                buffer.edit(
 8333                    deletion_ranges
 8334                        .into_iter()
 8335                        .map(|range| (range, empty_str.clone())),
 8336                    None,
 8337                    cx,
 8338                );
 8339            });
 8340            let selections = this.selections.all::<usize>(cx);
 8341            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8342                s.select(selections)
 8343            });
 8344        });
 8345    }
 8346
 8347    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8348        if self.read_only(cx) {
 8349            return;
 8350        }
 8351        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8352        let selections = self
 8353            .selections
 8354            .all::<usize>(cx)
 8355            .into_iter()
 8356            .map(|s| s.range());
 8357
 8358        self.transact(window, cx, |this, window, cx| {
 8359            this.buffer.update(cx, |buffer, cx| {
 8360                buffer.autoindent_ranges(selections, cx);
 8361            });
 8362            let selections = this.selections.all::<usize>(cx);
 8363            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8364                s.select(selections)
 8365            });
 8366        });
 8367    }
 8368
 8369    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8370        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8371        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8372        let selections = self.selections.all::<Point>(cx);
 8373
 8374        let mut new_cursors = Vec::new();
 8375        let mut edit_ranges = Vec::new();
 8376        let mut selections = selections.iter().peekable();
 8377        while let Some(selection) = selections.next() {
 8378            let mut rows = selection.spanned_rows(false, &display_map);
 8379            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8380
 8381            // Accumulate contiguous regions of rows that we want to delete.
 8382            while let Some(next_selection) = selections.peek() {
 8383                let next_rows = next_selection.spanned_rows(false, &display_map);
 8384                if next_rows.start <= rows.end {
 8385                    rows.end = next_rows.end;
 8386                    selections.next().unwrap();
 8387                } else {
 8388                    break;
 8389                }
 8390            }
 8391
 8392            let buffer = &display_map.buffer_snapshot;
 8393            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8394            let edit_end;
 8395            let cursor_buffer_row;
 8396            if buffer.max_point().row >= rows.end.0 {
 8397                // If there's a line after the range, delete the \n from the end of the row range
 8398                // and position the cursor on the next line.
 8399                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8400                cursor_buffer_row = rows.end;
 8401            } else {
 8402                // If there isn't a line after the range, delete the \n from the line before the
 8403                // start of the row range and position the cursor there.
 8404                edit_start = edit_start.saturating_sub(1);
 8405                edit_end = buffer.len();
 8406                cursor_buffer_row = rows.start.previous_row();
 8407            }
 8408
 8409            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8410            *cursor.column_mut() =
 8411                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8412
 8413            new_cursors.push((
 8414                selection.id,
 8415                buffer.anchor_after(cursor.to_point(&display_map)),
 8416            ));
 8417            edit_ranges.push(edit_start..edit_end);
 8418        }
 8419
 8420        self.transact(window, cx, |this, window, cx| {
 8421            let buffer = this.buffer.update(cx, |buffer, cx| {
 8422                let empty_str: Arc<str> = Arc::default();
 8423                buffer.edit(
 8424                    edit_ranges
 8425                        .into_iter()
 8426                        .map(|range| (range, empty_str.clone())),
 8427                    None,
 8428                    cx,
 8429                );
 8430                buffer.snapshot(cx)
 8431            });
 8432            let new_selections = new_cursors
 8433                .into_iter()
 8434                .map(|(id, cursor)| {
 8435                    let cursor = cursor.to_point(&buffer);
 8436                    Selection {
 8437                        id,
 8438                        start: cursor,
 8439                        end: cursor,
 8440                        reversed: false,
 8441                        goal: SelectionGoal::None,
 8442                    }
 8443                })
 8444                .collect();
 8445
 8446            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8447                s.select(new_selections);
 8448            });
 8449        });
 8450    }
 8451
 8452    pub fn join_lines_impl(
 8453        &mut self,
 8454        insert_whitespace: bool,
 8455        window: &mut Window,
 8456        cx: &mut Context<Self>,
 8457    ) {
 8458        if self.read_only(cx) {
 8459            return;
 8460        }
 8461        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8462        for selection in self.selections.all::<Point>(cx) {
 8463            let start = MultiBufferRow(selection.start.row);
 8464            // Treat single line selections as if they include the next line. Otherwise this action
 8465            // would do nothing for single line selections individual cursors.
 8466            let end = if selection.start.row == selection.end.row {
 8467                MultiBufferRow(selection.start.row + 1)
 8468            } else {
 8469                MultiBufferRow(selection.end.row)
 8470            };
 8471
 8472            if let Some(last_row_range) = row_ranges.last_mut() {
 8473                if start <= last_row_range.end {
 8474                    last_row_range.end = end;
 8475                    continue;
 8476                }
 8477            }
 8478            row_ranges.push(start..end);
 8479        }
 8480
 8481        let snapshot = self.buffer.read(cx).snapshot(cx);
 8482        let mut cursor_positions = Vec::new();
 8483        for row_range in &row_ranges {
 8484            let anchor = snapshot.anchor_before(Point::new(
 8485                row_range.end.previous_row().0,
 8486                snapshot.line_len(row_range.end.previous_row()),
 8487            ));
 8488            cursor_positions.push(anchor..anchor);
 8489        }
 8490
 8491        self.transact(window, cx, |this, window, cx| {
 8492            for row_range in row_ranges.into_iter().rev() {
 8493                for row in row_range.iter_rows().rev() {
 8494                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8495                    let next_line_row = row.next_row();
 8496                    let indent = snapshot.indent_size_for_line(next_line_row);
 8497                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8498
 8499                    let replace =
 8500                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8501                            " "
 8502                        } else {
 8503                            ""
 8504                        };
 8505
 8506                    this.buffer.update(cx, |buffer, cx| {
 8507                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8508                    });
 8509                }
 8510            }
 8511
 8512            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8513                s.select_anchor_ranges(cursor_positions)
 8514            });
 8515        });
 8516    }
 8517
 8518    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8519        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8520        self.join_lines_impl(true, window, cx);
 8521    }
 8522
 8523    pub fn sort_lines_case_sensitive(
 8524        &mut self,
 8525        _: &SortLinesCaseSensitive,
 8526        window: &mut Window,
 8527        cx: &mut Context<Self>,
 8528    ) {
 8529        self.manipulate_lines(window, cx, |lines| lines.sort())
 8530    }
 8531
 8532    pub fn sort_lines_case_insensitive(
 8533        &mut self,
 8534        _: &SortLinesCaseInsensitive,
 8535        window: &mut Window,
 8536        cx: &mut Context<Self>,
 8537    ) {
 8538        self.manipulate_lines(window, cx, |lines| {
 8539            lines.sort_by_key(|line| line.to_lowercase())
 8540        })
 8541    }
 8542
 8543    pub fn unique_lines_case_insensitive(
 8544        &mut self,
 8545        _: &UniqueLinesCaseInsensitive,
 8546        window: &mut Window,
 8547        cx: &mut Context<Self>,
 8548    ) {
 8549        self.manipulate_lines(window, cx, |lines| {
 8550            let mut seen = HashSet::default();
 8551            lines.retain(|line| seen.insert(line.to_lowercase()));
 8552        })
 8553    }
 8554
 8555    pub fn unique_lines_case_sensitive(
 8556        &mut self,
 8557        _: &UniqueLinesCaseSensitive,
 8558        window: &mut Window,
 8559        cx: &mut Context<Self>,
 8560    ) {
 8561        self.manipulate_lines(window, cx, |lines| {
 8562            let mut seen = HashSet::default();
 8563            lines.retain(|line| seen.insert(*line));
 8564        })
 8565    }
 8566
 8567    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8568        let Some(project) = self.project.clone() else {
 8569            return;
 8570        };
 8571        self.reload(project, window, cx)
 8572            .detach_and_notify_err(window, cx);
 8573    }
 8574
 8575    pub fn restore_file(
 8576        &mut self,
 8577        _: &::git::RestoreFile,
 8578        window: &mut Window,
 8579        cx: &mut Context<Self>,
 8580    ) {
 8581        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8582        let mut buffer_ids = HashSet::default();
 8583        let snapshot = self.buffer().read(cx).snapshot(cx);
 8584        for selection in self.selections.all::<usize>(cx) {
 8585            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8586        }
 8587
 8588        let buffer = self.buffer().read(cx);
 8589        let ranges = buffer_ids
 8590            .into_iter()
 8591            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8592            .collect::<Vec<_>>();
 8593
 8594        self.restore_hunks_in_ranges(ranges, window, cx);
 8595    }
 8596
 8597    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8598        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8599        let selections = self
 8600            .selections
 8601            .all(cx)
 8602            .into_iter()
 8603            .map(|s| s.range())
 8604            .collect();
 8605        self.restore_hunks_in_ranges(selections, window, cx);
 8606    }
 8607
 8608    pub fn restore_hunks_in_ranges(
 8609        &mut self,
 8610        ranges: Vec<Range<Point>>,
 8611        window: &mut Window,
 8612        cx: &mut Context<Editor>,
 8613    ) {
 8614        let mut revert_changes = HashMap::default();
 8615        let chunk_by = self
 8616            .snapshot(window, cx)
 8617            .hunks_for_ranges(ranges)
 8618            .into_iter()
 8619            .chunk_by(|hunk| hunk.buffer_id);
 8620        for (buffer_id, hunks) in &chunk_by {
 8621            let hunks = hunks.collect::<Vec<_>>();
 8622            for hunk in &hunks {
 8623                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8624            }
 8625            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8626        }
 8627        drop(chunk_by);
 8628        if !revert_changes.is_empty() {
 8629            self.transact(window, cx, |editor, window, cx| {
 8630                editor.restore(revert_changes, window, cx);
 8631            });
 8632        }
 8633    }
 8634
 8635    pub fn open_active_item_in_terminal(
 8636        &mut self,
 8637        _: &OpenInTerminal,
 8638        window: &mut Window,
 8639        cx: &mut Context<Self>,
 8640    ) {
 8641        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8642            let project_path = buffer.read(cx).project_path(cx)?;
 8643            let project = self.project.as_ref()?.read(cx);
 8644            let entry = project.entry_for_path(&project_path, cx)?;
 8645            let parent = match &entry.canonical_path {
 8646                Some(canonical_path) => canonical_path.to_path_buf(),
 8647                None => project.absolute_path(&project_path, cx)?,
 8648            }
 8649            .parent()?
 8650            .to_path_buf();
 8651            Some(parent)
 8652        }) {
 8653            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8654        }
 8655    }
 8656
 8657    fn set_breakpoint_context_menu(
 8658        &mut self,
 8659        display_row: DisplayRow,
 8660        position: Option<Anchor>,
 8661        clicked_point: gpui::Point<Pixels>,
 8662        window: &mut Window,
 8663        cx: &mut Context<Self>,
 8664    ) {
 8665        if !cx.has_flag::<Debugger>() {
 8666            return;
 8667        }
 8668        let source = self
 8669            .buffer
 8670            .read(cx)
 8671            .snapshot(cx)
 8672            .anchor_before(Point::new(display_row.0, 0u32));
 8673
 8674        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8675
 8676        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8677            self,
 8678            source,
 8679            clicked_point,
 8680            context_menu,
 8681            window,
 8682            cx,
 8683        );
 8684    }
 8685
 8686    fn add_edit_breakpoint_block(
 8687        &mut self,
 8688        anchor: Anchor,
 8689        breakpoint: &Breakpoint,
 8690        edit_action: BreakpointPromptEditAction,
 8691        window: &mut Window,
 8692        cx: &mut Context<Self>,
 8693    ) {
 8694        let weak_editor = cx.weak_entity();
 8695        let bp_prompt = cx.new(|cx| {
 8696            BreakpointPromptEditor::new(
 8697                weak_editor,
 8698                anchor,
 8699                breakpoint.clone(),
 8700                edit_action,
 8701                window,
 8702                cx,
 8703            )
 8704        });
 8705
 8706        let height = bp_prompt.update(cx, |this, cx| {
 8707            this.prompt
 8708                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8709        });
 8710        let cloned_prompt = bp_prompt.clone();
 8711        let blocks = vec![BlockProperties {
 8712            style: BlockStyle::Sticky,
 8713            placement: BlockPlacement::Above(anchor),
 8714            height,
 8715            render: Arc::new(move |cx| {
 8716                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8717                cloned_prompt.clone().into_any_element()
 8718            }),
 8719            priority: 0,
 8720        }];
 8721
 8722        let focus_handle = bp_prompt.focus_handle(cx);
 8723        window.focus(&focus_handle);
 8724
 8725        let block_ids = self.insert_blocks(blocks, None, cx);
 8726        bp_prompt.update(cx, |prompt, _| {
 8727            prompt.add_block_ids(block_ids);
 8728        });
 8729    }
 8730
 8731    fn breakpoint_at_cursor_head(
 8732        &self,
 8733        window: &mut Window,
 8734        cx: &mut Context<Self>,
 8735    ) -> Option<(Anchor, Breakpoint)> {
 8736        let cursor_position: Point = self.selections.newest(cx).head();
 8737        self.breakpoint_at_row(cursor_position.row, window, cx)
 8738    }
 8739
 8740    pub(crate) fn breakpoint_at_row(
 8741        &self,
 8742        row: u32,
 8743        window: &mut Window,
 8744        cx: &mut Context<Self>,
 8745    ) -> Option<(Anchor, Breakpoint)> {
 8746        let snapshot = self.snapshot(window, cx);
 8747        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8748
 8749        let project = self.project.clone()?;
 8750
 8751        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 8752            snapshot
 8753                .buffer_snapshot
 8754                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 8755        })?;
 8756
 8757        let enclosing_excerpt = breakpoint_position.excerpt_id;
 8758        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8759        let buffer_snapshot = buffer.read(cx).snapshot();
 8760
 8761        let row = buffer_snapshot
 8762            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 8763            .row;
 8764
 8765        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 8766        let anchor_end = snapshot
 8767            .buffer_snapshot
 8768            .anchor_after(Point::new(row, line_len));
 8769
 8770        let bp = self
 8771            .breakpoint_store
 8772            .as_ref()?
 8773            .read_with(cx, |breakpoint_store, cx| {
 8774                breakpoint_store
 8775                    .breakpoints(
 8776                        &buffer,
 8777                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 8778                        &buffer_snapshot,
 8779                        cx,
 8780                    )
 8781                    .next()
 8782                    .and_then(|(anchor, bp)| {
 8783                        let breakpoint_row = buffer_snapshot
 8784                            .summary_for_anchor::<text::PointUtf16>(anchor)
 8785                            .row;
 8786
 8787                        if breakpoint_row == row {
 8788                            snapshot
 8789                                .buffer_snapshot
 8790                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 8791                                .map(|anchor| (anchor, bp.clone()))
 8792                        } else {
 8793                            None
 8794                        }
 8795                    })
 8796            });
 8797        bp
 8798    }
 8799
 8800    pub fn edit_log_breakpoint(
 8801        &mut self,
 8802        _: &EditLogBreakpoint,
 8803        window: &mut Window,
 8804        cx: &mut Context<Self>,
 8805    ) {
 8806        let (anchor, bp) = self
 8807            .breakpoint_at_cursor_head(window, cx)
 8808            .unwrap_or_else(|| {
 8809                let cursor_position: Point = self.selections.newest(cx).head();
 8810
 8811                let breakpoint_position = self
 8812                    .snapshot(window, cx)
 8813                    .display_snapshot
 8814                    .buffer_snapshot
 8815                    .anchor_after(Point::new(cursor_position.row, 0));
 8816
 8817                (
 8818                    breakpoint_position,
 8819                    Breakpoint {
 8820                        message: None,
 8821                        state: BreakpointState::Enabled,
 8822                        condition: None,
 8823                        hit_condition: None,
 8824                    },
 8825                )
 8826            });
 8827
 8828        self.add_edit_breakpoint_block(anchor, &bp, BreakpointPromptEditAction::Log, window, cx);
 8829    }
 8830
 8831    pub fn enable_breakpoint(
 8832        &mut self,
 8833        _: &crate::actions::EnableBreakpoint,
 8834        window: &mut Window,
 8835        cx: &mut Context<Self>,
 8836    ) {
 8837        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8838            if breakpoint.is_disabled() {
 8839                self.edit_breakpoint_at_anchor(
 8840                    anchor,
 8841                    breakpoint,
 8842                    BreakpointEditAction::InvertState,
 8843                    cx,
 8844                );
 8845            }
 8846        }
 8847    }
 8848
 8849    pub fn disable_breakpoint(
 8850        &mut self,
 8851        _: &crate::actions::DisableBreakpoint,
 8852        window: &mut Window,
 8853        cx: &mut Context<Self>,
 8854    ) {
 8855        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8856            if breakpoint.is_enabled() {
 8857                self.edit_breakpoint_at_anchor(
 8858                    anchor,
 8859                    breakpoint,
 8860                    BreakpointEditAction::InvertState,
 8861                    cx,
 8862                );
 8863            }
 8864        }
 8865    }
 8866
 8867    pub fn toggle_breakpoint(
 8868        &mut self,
 8869        _: &crate::actions::ToggleBreakpoint,
 8870        window: &mut Window,
 8871        cx: &mut Context<Self>,
 8872    ) {
 8873        let edit_action = BreakpointEditAction::Toggle;
 8874
 8875        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8876            self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
 8877        } else {
 8878            let cursor_position: Point = self.selections.newest(cx).head();
 8879
 8880            let breakpoint_position = self
 8881                .snapshot(window, cx)
 8882                .display_snapshot
 8883                .buffer_snapshot
 8884                .anchor_after(Point::new(cursor_position.row, 0));
 8885
 8886            self.edit_breakpoint_at_anchor(
 8887                breakpoint_position,
 8888                Breakpoint::new_standard(),
 8889                edit_action,
 8890                cx,
 8891            );
 8892        }
 8893    }
 8894
 8895    pub fn edit_breakpoint_at_anchor(
 8896        &mut self,
 8897        breakpoint_position: Anchor,
 8898        breakpoint: Breakpoint,
 8899        edit_action: BreakpointEditAction,
 8900        cx: &mut Context<Self>,
 8901    ) {
 8902        let Some(breakpoint_store) = &self.breakpoint_store else {
 8903            return;
 8904        };
 8905
 8906        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 8907            if breakpoint_position == Anchor::min() {
 8908                self.buffer()
 8909                    .read(cx)
 8910                    .excerpt_buffer_ids()
 8911                    .into_iter()
 8912                    .next()
 8913            } else {
 8914                None
 8915            }
 8916        }) else {
 8917            return;
 8918        };
 8919
 8920        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 8921            return;
 8922        };
 8923
 8924        breakpoint_store.update(cx, |breakpoint_store, cx| {
 8925            breakpoint_store.toggle_breakpoint(
 8926                buffer,
 8927                (breakpoint_position.text_anchor, breakpoint),
 8928                edit_action,
 8929                cx,
 8930            );
 8931        });
 8932
 8933        cx.notify();
 8934    }
 8935
 8936    #[cfg(any(test, feature = "test-support"))]
 8937    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 8938        self.breakpoint_store.clone()
 8939    }
 8940
 8941    pub fn prepare_restore_change(
 8942        &self,
 8943        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 8944        hunk: &MultiBufferDiffHunk,
 8945        cx: &mut App,
 8946    ) -> Option<()> {
 8947        if hunk.is_created_file() {
 8948            return None;
 8949        }
 8950        let buffer = self.buffer.read(cx);
 8951        let diff = buffer.diff_for(hunk.buffer_id)?;
 8952        let buffer = buffer.buffer(hunk.buffer_id)?;
 8953        let buffer = buffer.read(cx);
 8954        let original_text = diff
 8955            .read(cx)
 8956            .base_text()
 8957            .as_rope()
 8958            .slice(hunk.diff_base_byte_range.clone());
 8959        let buffer_snapshot = buffer.snapshot();
 8960        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 8961        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 8962            probe
 8963                .0
 8964                .start
 8965                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 8966                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 8967        }) {
 8968            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 8969            Some(())
 8970        } else {
 8971            None
 8972        }
 8973    }
 8974
 8975    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 8976        self.manipulate_lines(window, cx, |lines| lines.reverse())
 8977    }
 8978
 8979    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 8980        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 8981    }
 8982
 8983    fn manipulate_lines<Fn>(
 8984        &mut self,
 8985        window: &mut Window,
 8986        cx: &mut Context<Self>,
 8987        mut callback: Fn,
 8988    ) where
 8989        Fn: FnMut(&mut Vec<&str>),
 8990    {
 8991        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8992
 8993        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8994        let buffer = self.buffer.read(cx).snapshot(cx);
 8995
 8996        let mut edits = Vec::new();
 8997
 8998        let selections = self.selections.all::<Point>(cx);
 8999        let mut selections = selections.iter().peekable();
 9000        let mut contiguous_row_selections = Vec::new();
 9001        let mut new_selections = Vec::new();
 9002        let mut added_lines = 0;
 9003        let mut removed_lines = 0;
 9004
 9005        while let Some(selection) = selections.next() {
 9006            let (start_row, end_row) = consume_contiguous_rows(
 9007                &mut contiguous_row_selections,
 9008                selection,
 9009                &display_map,
 9010                &mut selections,
 9011            );
 9012
 9013            let start_point = Point::new(start_row.0, 0);
 9014            let end_point = Point::new(
 9015                end_row.previous_row().0,
 9016                buffer.line_len(end_row.previous_row()),
 9017            );
 9018            let text = buffer
 9019                .text_for_range(start_point..end_point)
 9020                .collect::<String>();
 9021
 9022            let mut lines = text.split('\n').collect_vec();
 9023
 9024            let lines_before = lines.len();
 9025            callback(&mut lines);
 9026            let lines_after = lines.len();
 9027
 9028            edits.push((start_point..end_point, lines.join("\n")));
 9029
 9030            // Selections must change based on added and removed line count
 9031            let start_row =
 9032                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9033            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9034            new_selections.push(Selection {
 9035                id: selection.id,
 9036                start: start_row,
 9037                end: end_row,
 9038                goal: SelectionGoal::None,
 9039                reversed: selection.reversed,
 9040            });
 9041
 9042            if lines_after > lines_before {
 9043                added_lines += lines_after - lines_before;
 9044            } else if lines_before > lines_after {
 9045                removed_lines += lines_before - lines_after;
 9046            }
 9047        }
 9048
 9049        self.transact(window, cx, |this, window, cx| {
 9050            let buffer = this.buffer.update(cx, |buffer, cx| {
 9051                buffer.edit(edits, None, cx);
 9052                buffer.snapshot(cx)
 9053            });
 9054
 9055            // Recalculate offsets on newly edited buffer
 9056            let new_selections = new_selections
 9057                .iter()
 9058                .map(|s| {
 9059                    let start_point = Point::new(s.start.0, 0);
 9060                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9061                    Selection {
 9062                        id: s.id,
 9063                        start: buffer.point_to_offset(start_point),
 9064                        end: buffer.point_to_offset(end_point),
 9065                        goal: s.goal,
 9066                        reversed: s.reversed,
 9067                    }
 9068                })
 9069                .collect();
 9070
 9071            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9072                s.select(new_selections);
 9073            });
 9074
 9075            this.request_autoscroll(Autoscroll::fit(), cx);
 9076        });
 9077    }
 9078
 9079    pub fn convert_to_upper_case(
 9080        &mut self,
 9081        _: &ConvertToUpperCase,
 9082        window: &mut Window,
 9083        cx: &mut Context<Self>,
 9084    ) {
 9085        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9086    }
 9087
 9088    pub fn convert_to_lower_case(
 9089        &mut self,
 9090        _: &ConvertToLowerCase,
 9091        window: &mut Window,
 9092        cx: &mut Context<Self>,
 9093    ) {
 9094        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9095    }
 9096
 9097    pub fn convert_to_title_case(
 9098        &mut self,
 9099        _: &ConvertToTitleCase,
 9100        window: &mut Window,
 9101        cx: &mut Context<Self>,
 9102    ) {
 9103        self.manipulate_text(window, cx, |text| {
 9104            text.split('\n')
 9105                .map(|line| line.to_case(Case::Title))
 9106                .join("\n")
 9107        })
 9108    }
 9109
 9110    pub fn convert_to_snake_case(
 9111        &mut self,
 9112        _: &ConvertToSnakeCase,
 9113        window: &mut Window,
 9114        cx: &mut Context<Self>,
 9115    ) {
 9116        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9117    }
 9118
 9119    pub fn convert_to_kebab_case(
 9120        &mut self,
 9121        _: &ConvertToKebabCase,
 9122        window: &mut Window,
 9123        cx: &mut Context<Self>,
 9124    ) {
 9125        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9126    }
 9127
 9128    pub fn convert_to_upper_camel_case(
 9129        &mut self,
 9130        _: &ConvertToUpperCamelCase,
 9131        window: &mut Window,
 9132        cx: &mut Context<Self>,
 9133    ) {
 9134        self.manipulate_text(window, cx, |text| {
 9135            text.split('\n')
 9136                .map(|line| line.to_case(Case::UpperCamel))
 9137                .join("\n")
 9138        })
 9139    }
 9140
 9141    pub fn convert_to_lower_camel_case(
 9142        &mut self,
 9143        _: &ConvertToLowerCamelCase,
 9144        window: &mut Window,
 9145        cx: &mut Context<Self>,
 9146    ) {
 9147        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9148    }
 9149
 9150    pub fn convert_to_opposite_case(
 9151        &mut self,
 9152        _: &ConvertToOppositeCase,
 9153        window: &mut Window,
 9154        cx: &mut Context<Self>,
 9155    ) {
 9156        self.manipulate_text(window, cx, |text| {
 9157            text.chars()
 9158                .fold(String::with_capacity(text.len()), |mut t, c| {
 9159                    if c.is_uppercase() {
 9160                        t.extend(c.to_lowercase());
 9161                    } else {
 9162                        t.extend(c.to_uppercase());
 9163                    }
 9164                    t
 9165                })
 9166        })
 9167    }
 9168
 9169    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9170    where
 9171        Fn: FnMut(&str) -> String,
 9172    {
 9173        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9174        let buffer = self.buffer.read(cx).snapshot(cx);
 9175
 9176        let mut new_selections = Vec::new();
 9177        let mut edits = Vec::new();
 9178        let mut selection_adjustment = 0i32;
 9179
 9180        for selection in self.selections.all::<usize>(cx) {
 9181            let selection_is_empty = selection.is_empty();
 9182
 9183            let (start, end) = if selection_is_empty {
 9184                let word_range = movement::surrounding_word(
 9185                    &display_map,
 9186                    selection.start.to_display_point(&display_map),
 9187                );
 9188                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9189                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9190                (start, end)
 9191            } else {
 9192                (selection.start, selection.end)
 9193            };
 9194
 9195            let text = buffer.text_for_range(start..end).collect::<String>();
 9196            let old_length = text.len() as i32;
 9197            let text = callback(&text);
 9198
 9199            new_selections.push(Selection {
 9200                start: (start as i32 - selection_adjustment) as usize,
 9201                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9202                goal: SelectionGoal::None,
 9203                ..selection
 9204            });
 9205
 9206            selection_adjustment += old_length - text.len() as i32;
 9207
 9208            edits.push((start..end, text));
 9209        }
 9210
 9211        self.transact(window, cx, |this, window, cx| {
 9212            this.buffer.update(cx, |buffer, cx| {
 9213                buffer.edit(edits, None, cx);
 9214            });
 9215
 9216            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9217                s.select(new_selections);
 9218            });
 9219
 9220            this.request_autoscroll(Autoscroll::fit(), cx);
 9221        });
 9222    }
 9223
 9224    pub fn duplicate(
 9225        &mut self,
 9226        upwards: bool,
 9227        whole_lines: bool,
 9228        window: &mut Window,
 9229        cx: &mut Context<Self>,
 9230    ) {
 9231        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9232
 9233        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9234        let buffer = &display_map.buffer_snapshot;
 9235        let selections = self.selections.all::<Point>(cx);
 9236
 9237        let mut edits = Vec::new();
 9238        let mut selections_iter = selections.iter().peekable();
 9239        while let Some(selection) = selections_iter.next() {
 9240            let mut rows = selection.spanned_rows(false, &display_map);
 9241            // duplicate line-wise
 9242            if whole_lines || selection.start == selection.end {
 9243                // Avoid duplicating the same lines twice.
 9244                while let Some(next_selection) = selections_iter.peek() {
 9245                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9246                    if next_rows.start < rows.end {
 9247                        rows.end = next_rows.end;
 9248                        selections_iter.next().unwrap();
 9249                    } else {
 9250                        break;
 9251                    }
 9252                }
 9253
 9254                // Copy the text from the selected row region and splice it either at the start
 9255                // or end of the region.
 9256                let start = Point::new(rows.start.0, 0);
 9257                let end = Point::new(
 9258                    rows.end.previous_row().0,
 9259                    buffer.line_len(rows.end.previous_row()),
 9260                );
 9261                let text = buffer
 9262                    .text_for_range(start..end)
 9263                    .chain(Some("\n"))
 9264                    .collect::<String>();
 9265                let insert_location = if upwards {
 9266                    Point::new(rows.end.0, 0)
 9267                } else {
 9268                    start
 9269                };
 9270                edits.push((insert_location..insert_location, text));
 9271            } else {
 9272                // duplicate character-wise
 9273                let start = selection.start;
 9274                let end = selection.end;
 9275                let text = buffer.text_for_range(start..end).collect::<String>();
 9276                edits.push((selection.end..selection.end, text));
 9277            }
 9278        }
 9279
 9280        self.transact(window, cx, |this, _, cx| {
 9281            this.buffer.update(cx, |buffer, cx| {
 9282                buffer.edit(edits, None, cx);
 9283            });
 9284
 9285            this.request_autoscroll(Autoscroll::fit(), cx);
 9286        });
 9287    }
 9288
 9289    pub fn duplicate_line_up(
 9290        &mut self,
 9291        _: &DuplicateLineUp,
 9292        window: &mut Window,
 9293        cx: &mut Context<Self>,
 9294    ) {
 9295        self.duplicate(true, true, window, cx);
 9296    }
 9297
 9298    pub fn duplicate_line_down(
 9299        &mut self,
 9300        _: &DuplicateLineDown,
 9301        window: &mut Window,
 9302        cx: &mut Context<Self>,
 9303    ) {
 9304        self.duplicate(false, true, window, cx);
 9305    }
 9306
 9307    pub fn duplicate_selection(
 9308        &mut self,
 9309        _: &DuplicateSelection,
 9310        window: &mut Window,
 9311        cx: &mut Context<Self>,
 9312    ) {
 9313        self.duplicate(false, false, window, cx);
 9314    }
 9315
 9316    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9317        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9318
 9319        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9320        let buffer = self.buffer.read(cx).snapshot(cx);
 9321
 9322        let mut edits = Vec::new();
 9323        let mut unfold_ranges = Vec::new();
 9324        let mut refold_creases = Vec::new();
 9325
 9326        let selections = self.selections.all::<Point>(cx);
 9327        let mut selections = selections.iter().peekable();
 9328        let mut contiguous_row_selections = Vec::new();
 9329        let mut new_selections = Vec::new();
 9330
 9331        while let Some(selection) = selections.next() {
 9332            // Find all the selections that span a contiguous row range
 9333            let (start_row, end_row) = consume_contiguous_rows(
 9334                &mut contiguous_row_selections,
 9335                selection,
 9336                &display_map,
 9337                &mut selections,
 9338            );
 9339
 9340            // Move the text spanned by the row range to be before the line preceding the row range
 9341            if start_row.0 > 0 {
 9342                let range_to_move = Point::new(
 9343                    start_row.previous_row().0,
 9344                    buffer.line_len(start_row.previous_row()),
 9345                )
 9346                    ..Point::new(
 9347                        end_row.previous_row().0,
 9348                        buffer.line_len(end_row.previous_row()),
 9349                    );
 9350                let insertion_point = display_map
 9351                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9352                    .0;
 9353
 9354                // Don't move lines across excerpts
 9355                if buffer
 9356                    .excerpt_containing(insertion_point..range_to_move.end)
 9357                    .is_some()
 9358                {
 9359                    let text = buffer
 9360                        .text_for_range(range_to_move.clone())
 9361                        .flat_map(|s| s.chars())
 9362                        .skip(1)
 9363                        .chain(['\n'])
 9364                        .collect::<String>();
 9365
 9366                    edits.push((
 9367                        buffer.anchor_after(range_to_move.start)
 9368                            ..buffer.anchor_before(range_to_move.end),
 9369                        String::new(),
 9370                    ));
 9371                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9372                    edits.push((insertion_anchor..insertion_anchor, text));
 9373
 9374                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9375
 9376                    // Move selections up
 9377                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9378                        |mut selection| {
 9379                            selection.start.row -= row_delta;
 9380                            selection.end.row -= row_delta;
 9381                            selection
 9382                        },
 9383                    ));
 9384
 9385                    // Move folds up
 9386                    unfold_ranges.push(range_to_move.clone());
 9387                    for fold in display_map.folds_in_range(
 9388                        buffer.anchor_before(range_to_move.start)
 9389                            ..buffer.anchor_after(range_to_move.end),
 9390                    ) {
 9391                        let mut start = fold.range.start.to_point(&buffer);
 9392                        let mut end = fold.range.end.to_point(&buffer);
 9393                        start.row -= row_delta;
 9394                        end.row -= row_delta;
 9395                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9396                    }
 9397                }
 9398            }
 9399
 9400            // If we didn't move line(s), preserve the existing selections
 9401            new_selections.append(&mut contiguous_row_selections);
 9402        }
 9403
 9404        self.transact(window, cx, |this, window, cx| {
 9405            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9406            this.buffer.update(cx, |buffer, cx| {
 9407                for (range, text) in edits {
 9408                    buffer.edit([(range, text)], None, cx);
 9409                }
 9410            });
 9411            this.fold_creases(refold_creases, true, window, cx);
 9412            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9413                s.select(new_selections);
 9414            })
 9415        });
 9416    }
 9417
 9418    pub fn move_line_down(
 9419        &mut self,
 9420        _: &MoveLineDown,
 9421        window: &mut Window,
 9422        cx: &mut Context<Self>,
 9423    ) {
 9424        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9425
 9426        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9427        let buffer = self.buffer.read(cx).snapshot(cx);
 9428
 9429        let mut edits = Vec::new();
 9430        let mut unfold_ranges = Vec::new();
 9431        let mut refold_creases = Vec::new();
 9432
 9433        let selections = self.selections.all::<Point>(cx);
 9434        let mut selections = selections.iter().peekable();
 9435        let mut contiguous_row_selections = Vec::new();
 9436        let mut new_selections = Vec::new();
 9437
 9438        while let Some(selection) = selections.next() {
 9439            // Find all the selections that span a contiguous row range
 9440            let (start_row, end_row) = consume_contiguous_rows(
 9441                &mut contiguous_row_selections,
 9442                selection,
 9443                &display_map,
 9444                &mut selections,
 9445            );
 9446
 9447            // Move the text spanned by the row range to be after the last line of the row range
 9448            if end_row.0 <= buffer.max_point().row {
 9449                let range_to_move =
 9450                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9451                let insertion_point = display_map
 9452                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9453                    .0;
 9454
 9455                // Don't move lines across excerpt boundaries
 9456                if buffer
 9457                    .excerpt_containing(range_to_move.start..insertion_point)
 9458                    .is_some()
 9459                {
 9460                    let mut text = String::from("\n");
 9461                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9462                    text.pop(); // Drop trailing newline
 9463                    edits.push((
 9464                        buffer.anchor_after(range_to_move.start)
 9465                            ..buffer.anchor_before(range_to_move.end),
 9466                        String::new(),
 9467                    ));
 9468                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9469                    edits.push((insertion_anchor..insertion_anchor, text));
 9470
 9471                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9472
 9473                    // Move selections down
 9474                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9475                        |mut selection| {
 9476                            selection.start.row += row_delta;
 9477                            selection.end.row += row_delta;
 9478                            selection
 9479                        },
 9480                    ));
 9481
 9482                    // Move folds down
 9483                    unfold_ranges.push(range_to_move.clone());
 9484                    for fold in display_map.folds_in_range(
 9485                        buffer.anchor_before(range_to_move.start)
 9486                            ..buffer.anchor_after(range_to_move.end),
 9487                    ) {
 9488                        let mut start = fold.range.start.to_point(&buffer);
 9489                        let mut end = fold.range.end.to_point(&buffer);
 9490                        start.row += row_delta;
 9491                        end.row += row_delta;
 9492                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9493                    }
 9494                }
 9495            }
 9496
 9497            // If we didn't move line(s), preserve the existing selections
 9498            new_selections.append(&mut contiguous_row_selections);
 9499        }
 9500
 9501        self.transact(window, cx, |this, window, cx| {
 9502            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9503            this.buffer.update(cx, |buffer, cx| {
 9504                for (range, text) in edits {
 9505                    buffer.edit([(range, text)], None, cx);
 9506                }
 9507            });
 9508            this.fold_creases(refold_creases, true, window, cx);
 9509            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9510                s.select(new_selections)
 9511            });
 9512        });
 9513    }
 9514
 9515    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9516        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9517        let text_layout_details = &self.text_layout_details(window);
 9518        self.transact(window, cx, |this, window, cx| {
 9519            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9520                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9521                s.move_with(|display_map, selection| {
 9522                    if !selection.is_empty() {
 9523                        return;
 9524                    }
 9525
 9526                    let mut head = selection.head();
 9527                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9528                    if head.column() == display_map.line_len(head.row()) {
 9529                        transpose_offset = display_map
 9530                            .buffer_snapshot
 9531                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9532                    }
 9533
 9534                    if transpose_offset == 0 {
 9535                        return;
 9536                    }
 9537
 9538                    *head.column_mut() += 1;
 9539                    head = display_map.clip_point(head, Bias::Right);
 9540                    let goal = SelectionGoal::HorizontalPosition(
 9541                        display_map
 9542                            .x_for_display_point(head, text_layout_details)
 9543                            .into(),
 9544                    );
 9545                    selection.collapse_to(head, goal);
 9546
 9547                    let transpose_start = display_map
 9548                        .buffer_snapshot
 9549                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9550                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9551                        let transpose_end = display_map
 9552                            .buffer_snapshot
 9553                            .clip_offset(transpose_offset + 1, Bias::Right);
 9554                        if let Some(ch) =
 9555                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9556                        {
 9557                            edits.push((transpose_start..transpose_offset, String::new()));
 9558                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9559                        }
 9560                    }
 9561                });
 9562                edits
 9563            });
 9564            this.buffer
 9565                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9566            let selections = this.selections.all::<usize>(cx);
 9567            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9568                s.select(selections);
 9569            });
 9570        });
 9571    }
 9572
 9573    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9574        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9575        self.rewrap_impl(RewrapOptions::default(), cx)
 9576    }
 9577
 9578    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9579        let buffer = self.buffer.read(cx).snapshot(cx);
 9580        let selections = self.selections.all::<Point>(cx);
 9581        let mut selections = selections.iter().peekable();
 9582
 9583        let mut edits = Vec::new();
 9584        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9585
 9586        while let Some(selection) = selections.next() {
 9587            let mut start_row = selection.start.row;
 9588            let mut end_row = selection.end.row;
 9589
 9590            // Skip selections that overlap with a range that has already been rewrapped.
 9591            let selection_range = start_row..end_row;
 9592            if rewrapped_row_ranges
 9593                .iter()
 9594                .any(|range| range.overlaps(&selection_range))
 9595            {
 9596                continue;
 9597            }
 9598
 9599            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9600
 9601            // Since not all lines in the selection may be at the same indent
 9602            // level, choose the indent size that is the most common between all
 9603            // of the lines.
 9604            //
 9605            // If there is a tie, we use the deepest indent.
 9606            let (indent_size, indent_end) = {
 9607                let mut indent_size_occurrences = HashMap::default();
 9608                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9609
 9610                for row in start_row..=end_row {
 9611                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9612                    rows_by_indent_size.entry(indent).or_default().push(row);
 9613                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9614                }
 9615
 9616                let indent_size = indent_size_occurrences
 9617                    .into_iter()
 9618                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9619                    .map(|(indent, _)| indent)
 9620                    .unwrap_or_default();
 9621                let row = rows_by_indent_size[&indent_size][0];
 9622                let indent_end = Point::new(row, indent_size.len);
 9623
 9624                (indent_size, indent_end)
 9625            };
 9626
 9627            let mut line_prefix = indent_size.chars().collect::<String>();
 9628
 9629            let mut inside_comment = false;
 9630            if let Some(comment_prefix) =
 9631                buffer
 9632                    .language_scope_at(selection.head())
 9633                    .and_then(|language| {
 9634                        language
 9635                            .line_comment_prefixes()
 9636                            .iter()
 9637                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9638                            .cloned()
 9639                    })
 9640            {
 9641                line_prefix.push_str(&comment_prefix);
 9642                inside_comment = true;
 9643            }
 9644
 9645            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9646            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9647                RewrapBehavior::InComments => inside_comment,
 9648                RewrapBehavior::InSelections => !selection.is_empty(),
 9649                RewrapBehavior::Anywhere => true,
 9650            };
 9651
 9652            let should_rewrap = options.override_language_settings
 9653                || allow_rewrap_based_on_language
 9654                || self.hard_wrap.is_some();
 9655            if !should_rewrap {
 9656                continue;
 9657            }
 9658
 9659            if selection.is_empty() {
 9660                'expand_upwards: while start_row > 0 {
 9661                    let prev_row = start_row - 1;
 9662                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9663                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9664                    {
 9665                        start_row = prev_row;
 9666                    } else {
 9667                        break 'expand_upwards;
 9668                    }
 9669                }
 9670
 9671                'expand_downwards: while end_row < buffer.max_point().row {
 9672                    let next_row = end_row + 1;
 9673                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9674                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9675                    {
 9676                        end_row = next_row;
 9677                    } else {
 9678                        break 'expand_downwards;
 9679                    }
 9680                }
 9681            }
 9682
 9683            let start = Point::new(start_row, 0);
 9684            let start_offset = start.to_offset(&buffer);
 9685            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9686            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9687            let Some(lines_without_prefixes) = selection_text
 9688                .lines()
 9689                .map(|line| {
 9690                    line.strip_prefix(&line_prefix)
 9691                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9692                        .ok_or_else(|| {
 9693                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9694                        })
 9695                })
 9696                .collect::<Result<Vec<_>, _>>()
 9697                .log_err()
 9698            else {
 9699                continue;
 9700            };
 9701
 9702            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9703                buffer
 9704                    .language_settings_at(Point::new(start_row, 0), cx)
 9705                    .preferred_line_length as usize
 9706            });
 9707            let wrapped_text = wrap_with_prefix(
 9708                line_prefix,
 9709                lines_without_prefixes.join("\n"),
 9710                wrap_column,
 9711                tab_size,
 9712                options.preserve_existing_whitespace,
 9713            );
 9714
 9715            // TODO: should always use char-based diff while still supporting cursor behavior that
 9716            // matches vim.
 9717            let mut diff_options = DiffOptions::default();
 9718            if options.override_language_settings {
 9719                diff_options.max_word_diff_len = 0;
 9720                diff_options.max_word_diff_line_count = 0;
 9721            } else {
 9722                diff_options.max_word_diff_len = usize::MAX;
 9723                diff_options.max_word_diff_line_count = usize::MAX;
 9724            }
 9725
 9726            for (old_range, new_text) in
 9727                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 9728            {
 9729                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 9730                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 9731                edits.push((edit_start..edit_end, new_text));
 9732            }
 9733
 9734            rewrapped_row_ranges.push(start_row..=end_row);
 9735        }
 9736
 9737        self.buffer
 9738            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9739    }
 9740
 9741    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 9742        let mut text = String::new();
 9743        let buffer = self.buffer.read(cx).snapshot(cx);
 9744        let mut selections = self.selections.all::<Point>(cx);
 9745        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9746        {
 9747            let max_point = buffer.max_point();
 9748            let mut is_first = true;
 9749            for selection in &mut selections {
 9750                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9751                if is_entire_line {
 9752                    selection.start = Point::new(selection.start.row, 0);
 9753                    if !selection.is_empty() && selection.end.column == 0 {
 9754                        selection.end = cmp::min(max_point, selection.end);
 9755                    } else {
 9756                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 9757                    }
 9758                    selection.goal = SelectionGoal::None;
 9759                }
 9760                if is_first {
 9761                    is_first = false;
 9762                } else {
 9763                    text += "\n";
 9764                }
 9765                let mut len = 0;
 9766                for chunk in buffer.text_for_range(selection.start..selection.end) {
 9767                    text.push_str(chunk);
 9768                    len += chunk.len();
 9769                }
 9770                clipboard_selections.push(ClipboardSelection {
 9771                    len,
 9772                    is_entire_line,
 9773                    first_line_indent: buffer
 9774                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 9775                        .len,
 9776                });
 9777            }
 9778        }
 9779
 9780        self.transact(window, cx, |this, window, cx| {
 9781            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9782                s.select(selections);
 9783            });
 9784            this.insert("", window, cx);
 9785        });
 9786        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 9787    }
 9788
 9789    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 9790        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9791        let item = self.cut_common(window, cx);
 9792        cx.write_to_clipboard(item);
 9793    }
 9794
 9795    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 9796        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9797        self.change_selections(None, window, cx, |s| {
 9798            s.move_with(|snapshot, sel| {
 9799                if sel.is_empty() {
 9800                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 9801                }
 9802            });
 9803        });
 9804        let item = self.cut_common(window, cx);
 9805        cx.set_global(KillRing(item))
 9806    }
 9807
 9808    pub fn kill_ring_yank(
 9809        &mut self,
 9810        _: &KillRingYank,
 9811        window: &mut Window,
 9812        cx: &mut Context<Self>,
 9813    ) {
 9814        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9815        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 9816            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 9817                (kill_ring.text().to_string(), kill_ring.metadata_json())
 9818            } else {
 9819                return;
 9820            }
 9821        } else {
 9822            return;
 9823        };
 9824        self.do_paste(&text, metadata, false, window, cx);
 9825    }
 9826
 9827    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
 9828        self.do_copy(true, cx);
 9829    }
 9830
 9831    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 9832        self.do_copy(false, cx);
 9833    }
 9834
 9835    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
 9836        let selections = self.selections.all::<Point>(cx);
 9837        let buffer = self.buffer.read(cx).read(cx);
 9838        let mut text = String::new();
 9839
 9840        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9841        {
 9842            let max_point = buffer.max_point();
 9843            let mut is_first = true;
 9844            for selection in &selections {
 9845                let mut start = selection.start;
 9846                let mut end = selection.end;
 9847                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9848                if is_entire_line {
 9849                    start = Point::new(start.row, 0);
 9850                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 9851                }
 9852
 9853                let mut trimmed_selections = Vec::new();
 9854                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
 9855                    let row = MultiBufferRow(start.row);
 9856                    let first_indent = buffer.indent_size_for_line(row);
 9857                    if first_indent.len == 0 || start.column > first_indent.len {
 9858                        trimmed_selections.push(start..end);
 9859                    } else {
 9860                        trimmed_selections.push(
 9861                            Point::new(row.0, first_indent.len)
 9862                                ..Point::new(row.0, buffer.line_len(row)),
 9863                        );
 9864                        for row in start.row + 1..=end.row {
 9865                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
 9866                            if row_indent_size.len >= first_indent.len {
 9867                                trimmed_selections.push(
 9868                                    Point::new(row, first_indent.len)
 9869                                        ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
 9870                                );
 9871                            } else {
 9872                                trimmed_selections.clear();
 9873                                trimmed_selections.push(start..end);
 9874                                break;
 9875                            }
 9876                        }
 9877                    }
 9878                } else {
 9879                    trimmed_selections.push(start..end);
 9880                }
 9881
 9882                for trimmed_range in trimmed_selections {
 9883                    if is_first {
 9884                        is_first = false;
 9885                    } else {
 9886                        text += "\n";
 9887                    }
 9888                    let mut len = 0;
 9889                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
 9890                        text.push_str(chunk);
 9891                        len += chunk.len();
 9892                    }
 9893                    clipboard_selections.push(ClipboardSelection {
 9894                        len,
 9895                        is_entire_line,
 9896                        first_line_indent: buffer
 9897                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
 9898                            .len,
 9899                    });
 9900                }
 9901            }
 9902        }
 9903
 9904        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 9905            text,
 9906            clipboard_selections,
 9907        ));
 9908    }
 9909
 9910    pub fn do_paste(
 9911        &mut self,
 9912        text: &String,
 9913        clipboard_selections: Option<Vec<ClipboardSelection>>,
 9914        handle_entire_lines: bool,
 9915        window: &mut Window,
 9916        cx: &mut Context<Self>,
 9917    ) {
 9918        if self.read_only(cx) {
 9919            return;
 9920        }
 9921
 9922        let clipboard_text = Cow::Borrowed(text);
 9923
 9924        self.transact(window, cx, |this, window, cx| {
 9925            if let Some(mut clipboard_selections) = clipboard_selections {
 9926                let old_selections = this.selections.all::<usize>(cx);
 9927                let all_selections_were_entire_line =
 9928                    clipboard_selections.iter().all(|s| s.is_entire_line);
 9929                let first_selection_indent_column =
 9930                    clipboard_selections.first().map(|s| s.first_line_indent);
 9931                if clipboard_selections.len() != old_selections.len() {
 9932                    clipboard_selections.drain(..);
 9933                }
 9934                let cursor_offset = this.selections.last::<usize>(cx).head();
 9935                let mut auto_indent_on_paste = true;
 9936
 9937                this.buffer.update(cx, |buffer, cx| {
 9938                    let snapshot = buffer.read(cx);
 9939                    auto_indent_on_paste = snapshot
 9940                        .language_settings_at(cursor_offset, cx)
 9941                        .auto_indent_on_paste;
 9942
 9943                    let mut start_offset = 0;
 9944                    let mut edits = Vec::new();
 9945                    let mut original_indent_columns = Vec::new();
 9946                    for (ix, selection) in old_selections.iter().enumerate() {
 9947                        let to_insert;
 9948                        let entire_line;
 9949                        let original_indent_column;
 9950                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 9951                            let end_offset = start_offset + clipboard_selection.len;
 9952                            to_insert = &clipboard_text[start_offset..end_offset];
 9953                            entire_line = clipboard_selection.is_entire_line;
 9954                            start_offset = end_offset + 1;
 9955                            original_indent_column = Some(clipboard_selection.first_line_indent);
 9956                        } else {
 9957                            to_insert = clipboard_text.as_str();
 9958                            entire_line = all_selections_were_entire_line;
 9959                            original_indent_column = first_selection_indent_column
 9960                        }
 9961
 9962                        // If the corresponding selection was empty when this slice of the
 9963                        // clipboard text was written, then the entire line containing the
 9964                        // selection was copied. If this selection is also currently empty,
 9965                        // then paste the line before the current line of the buffer.
 9966                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 9967                            let column = selection.start.to_point(&snapshot).column as usize;
 9968                            let line_start = selection.start - column;
 9969                            line_start..line_start
 9970                        } else {
 9971                            selection.range()
 9972                        };
 9973
 9974                        edits.push((range, to_insert));
 9975                        original_indent_columns.push(original_indent_column);
 9976                    }
 9977                    drop(snapshot);
 9978
 9979                    buffer.edit(
 9980                        edits,
 9981                        if auto_indent_on_paste {
 9982                            Some(AutoindentMode::Block {
 9983                                original_indent_columns,
 9984                            })
 9985                        } else {
 9986                            None
 9987                        },
 9988                        cx,
 9989                    );
 9990                });
 9991
 9992                let selections = this.selections.all::<usize>(cx);
 9993                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9994                    s.select(selections)
 9995                });
 9996            } else {
 9997                this.insert(&clipboard_text, window, cx);
 9998            }
 9999        });
10000    }
10001
10002    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10003        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10004        if let Some(item) = cx.read_from_clipboard() {
10005            let entries = item.entries();
10006
10007            match entries.first() {
10008                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10009                // of all the pasted entries.
10010                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10011                    .do_paste(
10012                        clipboard_string.text(),
10013                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10014                        true,
10015                        window,
10016                        cx,
10017                    ),
10018                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10019            }
10020        }
10021    }
10022
10023    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10024        if self.read_only(cx) {
10025            return;
10026        }
10027
10028        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10029
10030        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10031            if let Some((selections, _)) =
10032                self.selection_history.transaction(transaction_id).cloned()
10033            {
10034                self.change_selections(None, window, cx, |s| {
10035                    s.select_anchors(selections.to_vec());
10036                });
10037            } else {
10038                log::error!(
10039                    "No entry in selection_history found for undo. \
10040                     This may correspond to a bug where undo does not update the selection. \
10041                     If this is occurring, please add details to \
10042                     https://github.com/zed-industries/zed/issues/22692"
10043                );
10044            }
10045            self.request_autoscroll(Autoscroll::fit(), cx);
10046            self.unmark_text(window, cx);
10047            self.refresh_inline_completion(true, false, window, cx);
10048            cx.emit(EditorEvent::Edited { transaction_id });
10049            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10050        }
10051    }
10052
10053    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10054        if self.read_only(cx) {
10055            return;
10056        }
10057
10058        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10059
10060        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10061            if let Some((_, Some(selections))) =
10062                self.selection_history.transaction(transaction_id).cloned()
10063            {
10064                self.change_selections(None, window, cx, |s| {
10065                    s.select_anchors(selections.to_vec());
10066                });
10067            } else {
10068                log::error!(
10069                    "No entry in selection_history found for redo. \
10070                     This may correspond to a bug where undo does not update the selection. \
10071                     If this is occurring, please add details to \
10072                     https://github.com/zed-industries/zed/issues/22692"
10073                );
10074            }
10075            self.request_autoscroll(Autoscroll::fit(), cx);
10076            self.unmark_text(window, cx);
10077            self.refresh_inline_completion(true, false, window, cx);
10078            cx.emit(EditorEvent::Edited { transaction_id });
10079        }
10080    }
10081
10082    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10083        self.buffer
10084            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10085    }
10086
10087    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10088        self.buffer
10089            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10090    }
10091
10092    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10093        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10094        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10095            s.move_with(|map, selection| {
10096                let cursor = if selection.is_empty() {
10097                    movement::left(map, selection.start)
10098                } else {
10099                    selection.start
10100                };
10101                selection.collapse_to(cursor, SelectionGoal::None);
10102            });
10103        })
10104    }
10105
10106    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10107        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10108        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10109            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10110        })
10111    }
10112
10113    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10114        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10115        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10116            s.move_with(|map, selection| {
10117                let cursor = if selection.is_empty() {
10118                    movement::right(map, selection.end)
10119                } else {
10120                    selection.end
10121                };
10122                selection.collapse_to(cursor, SelectionGoal::None)
10123            });
10124        })
10125    }
10126
10127    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10128        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10129        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10130            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10131        })
10132    }
10133
10134    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10135        if self.take_rename(true, window, cx).is_some() {
10136            return;
10137        }
10138
10139        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10140            cx.propagate();
10141            return;
10142        }
10143
10144        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10145
10146        let text_layout_details = &self.text_layout_details(window);
10147        let selection_count = self.selections.count();
10148        let first_selection = self.selections.first_anchor();
10149
10150        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10151            s.move_with(|map, selection| {
10152                if !selection.is_empty() {
10153                    selection.goal = SelectionGoal::None;
10154                }
10155                let (cursor, goal) = movement::up(
10156                    map,
10157                    selection.start,
10158                    selection.goal,
10159                    false,
10160                    text_layout_details,
10161                );
10162                selection.collapse_to(cursor, goal);
10163            });
10164        });
10165
10166        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10167        {
10168            cx.propagate();
10169        }
10170    }
10171
10172    pub fn move_up_by_lines(
10173        &mut self,
10174        action: &MoveUpByLines,
10175        window: &mut Window,
10176        cx: &mut Context<Self>,
10177    ) {
10178        if self.take_rename(true, window, cx).is_some() {
10179            return;
10180        }
10181
10182        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10183            cx.propagate();
10184            return;
10185        }
10186
10187        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10188
10189        let text_layout_details = &self.text_layout_details(window);
10190
10191        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10192            s.move_with(|map, selection| {
10193                if !selection.is_empty() {
10194                    selection.goal = SelectionGoal::None;
10195                }
10196                let (cursor, goal) = movement::up_by_rows(
10197                    map,
10198                    selection.start,
10199                    action.lines,
10200                    selection.goal,
10201                    false,
10202                    text_layout_details,
10203                );
10204                selection.collapse_to(cursor, goal);
10205            });
10206        })
10207    }
10208
10209    pub fn move_down_by_lines(
10210        &mut self,
10211        action: &MoveDownByLines,
10212        window: &mut Window,
10213        cx: &mut Context<Self>,
10214    ) {
10215        if self.take_rename(true, window, cx).is_some() {
10216            return;
10217        }
10218
10219        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10220            cx.propagate();
10221            return;
10222        }
10223
10224        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10225
10226        let text_layout_details = &self.text_layout_details(window);
10227
10228        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10229            s.move_with(|map, selection| {
10230                if !selection.is_empty() {
10231                    selection.goal = SelectionGoal::None;
10232                }
10233                let (cursor, goal) = movement::down_by_rows(
10234                    map,
10235                    selection.start,
10236                    action.lines,
10237                    selection.goal,
10238                    false,
10239                    text_layout_details,
10240                );
10241                selection.collapse_to(cursor, goal);
10242            });
10243        })
10244    }
10245
10246    pub fn select_down_by_lines(
10247        &mut self,
10248        action: &SelectDownByLines,
10249        window: &mut Window,
10250        cx: &mut Context<Self>,
10251    ) {
10252        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10253        let text_layout_details = &self.text_layout_details(window);
10254        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10255            s.move_heads_with(|map, head, goal| {
10256                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10257            })
10258        })
10259    }
10260
10261    pub fn select_up_by_lines(
10262        &mut self,
10263        action: &SelectUpByLines,
10264        window: &mut Window,
10265        cx: &mut Context<Self>,
10266    ) {
10267        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10268        let text_layout_details = &self.text_layout_details(window);
10269        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10270            s.move_heads_with(|map, head, goal| {
10271                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10272            })
10273        })
10274    }
10275
10276    pub fn select_page_up(
10277        &mut self,
10278        _: &SelectPageUp,
10279        window: &mut Window,
10280        cx: &mut Context<Self>,
10281    ) {
10282        let Some(row_count) = self.visible_row_count() else {
10283            return;
10284        };
10285
10286        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10287
10288        let text_layout_details = &self.text_layout_details(window);
10289
10290        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10291            s.move_heads_with(|map, head, goal| {
10292                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10293            })
10294        })
10295    }
10296
10297    pub fn move_page_up(
10298        &mut self,
10299        action: &MovePageUp,
10300        window: &mut Window,
10301        cx: &mut Context<Self>,
10302    ) {
10303        if self.take_rename(true, window, cx).is_some() {
10304            return;
10305        }
10306
10307        if self
10308            .context_menu
10309            .borrow_mut()
10310            .as_mut()
10311            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10312            .unwrap_or(false)
10313        {
10314            return;
10315        }
10316
10317        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10318            cx.propagate();
10319            return;
10320        }
10321
10322        let Some(row_count) = self.visible_row_count() else {
10323            return;
10324        };
10325
10326        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10327
10328        let autoscroll = if action.center_cursor {
10329            Autoscroll::center()
10330        } else {
10331            Autoscroll::fit()
10332        };
10333
10334        let text_layout_details = &self.text_layout_details(window);
10335
10336        self.change_selections(Some(autoscroll), window, cx, |s| {
10337            s.move_with(|map, selection| {
10338                if !selection.is_empty() {
10339                    selection.goal = SelectionGoal::None;
10340                }
10341                let (cursor, goal) = movement::up_by_rows(
10342                    map,
10343                    selection.end,
10344                    row_count,
10345                    selection.goal,
10346                    false,
10347                    text_layout_details,
10348                );
10349                selection.collapse_to(cursor, goal);
10350            });
10351        });
10352    }
10353
10354    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10355        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10356        let text_layout_details = &self.text_layout_details(window);
10357        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10358            s.move_heads_with(|map, head, goal| {
10359                movement::up(map, head, goal, false, text_layout_details)
10360            })
10361        })
10362    }
10363
10364    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10365        self.take_rename(true, window, cx);
10366
10367        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10368            cx.propagate();
10369            return;
10370        }
10371
10372        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10373
10374        let text_layout_details = &self.text_layout_details(window);
10375        let selection_count = self.selections.count();
10376        let first_selection = self.selections.first_anchor();
10377
10378        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10379            s.move_with(|map, selection| {
10380                if !selection.is_empty() {
10381                    selection.goal = SelectionGoal::None;
10382                }
10383                let (cursor, goal) = movement::down(
10384                    map,
10385                    selection.end,
10386                    selection.goal,
10387                    false,
10388                    text_layout_details,
10389                );
10390                selection.collapse_to(cursor, goal);
10391            });
10392        });
10393
10394        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10395        {
10396            cx.propagate();
10397        }
10398    }
10399
10400    pub fn select_page_down(
10401        &mut self,
10402        _: &SelectPageDown,
10403        window: &mut Window,
10404        cx: &mut Context<Self>,
10405    ) {
10406        let Some(row_count) = self.visible_row_count() else {
10407            return;
10408        };
10409
10410        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10411
10412        let text_layout_details = &self.text_layout_details(window);
10413
10414        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10415            s.move_heads_with(|map, head, goal| {
10416                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10417            })
10418        })
10419    }
10420
10421    pub fn move_page_down(
10422        &mut self,
10423        action: &MovePageDown,
10424        window: &mut Window,
10425        cx: &mut Context<Self>,
10426    ) {
10427        if self.take_rename(true, window, cx).is_some() {
10428            return;
10429        }
10430
10431        if self
10432            .context_menu
10433            .borrow_mut()
10434            .as_mut()
10435            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10436            .unwrap_or(false)
10437        {
10438            return;
10439        }
10440
10441        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10442            cx.propagate();
10443            return;
10444        }
10445
10446        let Some(row_count) = self.visible_row_count() else {
10447            return;
10448        };
10449
10450        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10451
10452        let autoscroll = if action.center_cursor {
10453            Autoscroll::center()
10454        } else {
10455            Autoscroll::fit()
10456        };
10457
10458        let text_layout_details = &self.text_layout_details(window);
10459        self.change_selections(Some(autoscroll), window, cx, |s| {
10460            s.move_with(|map, selection| {
10461                if !selection.is_empty() {
10462                    selection.goal = SelectionGoal::None;
10463                }
10464                let (cursor, goal) = movement::down_by_rows(
10465                    map,
10466                    selection.end,
10467                    row_count,
10468                    selection.goal,
10469                    false,
10470                    text_layout_details,
10471                );
10472                selection.collapse_to(cursor, goal);
10473            });
10474        });
10475    }
10476
10477    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10478        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10479        let text_layout_details = &self.text_layout_details(window);
10480        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10481            s.move_heads_with(|map, head, goal| {
10482                movement::down(map, head, goal, false, text_layout_details)
10483            })
10484        });
10485    }
10486
10487    pub fn context_menu_first(
10488        &mut self,
10489        _: &ContextMenuFirst,
10490        _window: &mut Window,
10491        cx: &mut Context<Self>,
10492    ) {
10493        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10494            context_menu.select_first(self.completion_provider.as_deref(), cx);
10495        }
10496    }
10497
10498    pub fn context_menu_prev(
10499        &mut self,
10500        _: &ContextMenuPrevious,
10501        _window: &mut Window,
10502        cx: &mut Context<Self>,
10503    ) {
10504        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10505            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10506        }
10507    }
10508
10509    pub fn context_menu_next(
10510        &mut self,
10511        _: &ContextMenuNext,
10512        _window: &mut Window,
10513        cx: &mut Context<Self>,
10514    ) {
10515        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10516            context_menu.select_next(self.completion_provider.as_deref(), cx);
10517        }
10518    }
10519
10520    pub fn context_menu_last(
10521        &mut self,
10522        _: &ContextMenuLast,
10523        _window: &mut Window,
10524        cx: &mut Context<Self>,
10525    ) {
10526        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10527            context_menu.select_last(self.completion_provider.as_deref(), cx);
10528        }
10529    }
10530
10531    pub fn move_to_previous_word_start(
10532        &mut self,
10533        _: &MoveToPreviousWordStart,
10534        window: &mut Window,
10535        cx: &mut Context<Self>,
10536    ) {
10537        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10538        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10539            s.move_cursors_with(|map, head, _| {
10540                (
10541                    movement::previous_word_start(map, head),
10542                    SelectionGoal::None,
10543                )
10544            });
10545        })
10546    }
10547
10548    pub fn move_to_previous_subword_start(
10549        &mut self,
10550        _: &MoveToPreviousSubwordStart,
10551        window: &mut Window,
10552        cx: &mut Context<Self>,
10553    ) {
10554        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10555        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10556            s.move_cursors_with(|map, head, _| {
10557                (
10558                    movement::previous_subword_start(map, head),
10559                    SelectionGoal::None,
10560                )
10561            });
10562        })
10563    }
10564
10565    pub fn select_to_previous_word_start(
10566        &mut self,
10567        _: &SelectToPreviousWordStart,
10568        window: &mut Window,
10569        cx: &mut Context<Self>,
10570    ) {
10571        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10572        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10573            s.move_heads_with(|map, head, _| {
10574                (
10575                    movement::previous_word_start(map, head),
10576                    SelectionGoal::None,
10577                )
10578            });
10579        })
10580    }
10581
10582    pub fn select_to_previous_subword_start(
10583        &mut self,
10584        _: &SelectToPreviousSubwordStart,
10585        window: &mut Window,
10586        cx: &mut Context<Self>,
10587    ) {
10588        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10589        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10590            s.move_heads_with(|map, head, _| {
10591                (
10592                    movement::previous_subword_start(map, head),
10593                    SelectionGoal::None,
10594                )
10595            });
10596        })
10597    }
10598
10599    pub fn delete_to_previous_word_start(
10600        &mut self,
10601        action: &DeleteToPreviousWordStart,
10602        window: &mut Window,
10603        cx: &mut Context<Self>,
10604    ) {
10605        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10606        self.transact(window, cx, |this, window, cx| {
10607            this.select_autoclose_pair(window, cx);
10608            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10609                s.move_with(|map, selection| {
10610                    if selection.is_empty() {
10611                        let cursor = if action.ignore_newlines {
10612                            movement::previous_word_start(map, selection.head())
10613                        } else {
10614                            movement::previous_word_start_or_newline(map, selection.head())
10615                        };
10616                        selection.set_head(cursor, SelectionGoal::None);
10617                    }
10618                });
10619            });
10620            this.insert("", window, cx);
10621        });
10622    }
10623
10624    pub fn delete_to_previous_subword_start(
10625        &mut self,
10626        _: &DeleteToPreviousSubwordStart,
10627        window: &mut Window,
10628        cx: &mut Context<Self>,
10629    ) {
10630        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10631        self.transact(window, cx, |this, window, cx| {
10632            this.select_autoclose_pair(window, cx);
10633            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10634                s.move_with(|map, selection| {
10635                    if selection.is_empty() {
10636                        let cursor = movement::previous_subword_start(map, selection.head());
10637                        selection.set_head(cursor, SelectionGoal::None);
10638                    }
10639                });
10640            });
10641            this.insert("", window, cx);
10642        });
10643    }
10644
10645    pub fn move_to_next_word_end(
10646        &mut self,
10647        _: &MoveToNextWordEnd,
10648        window: &mut Window,
10649        cx: &mut Context<Self>,
10650    ) {
10651        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10652        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10653            s.move_cursors_with(|map, head, _| {
10654                (movement::next_word_end(map, head), SelectionGoal::None)
10655            });
10656        })
10657    }
10658
10659    pub fn move_to_next_subword_end(
10660        &mut self,
10661        _: &MoveToNextSubwordEnd,
10662        window: &mut Window,
10663        cx: &mut Context<Self>,
10664    ) {
10665        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10666        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10667            s.move_cursors_with(|map, head, _| {
10668                (movement::next_subword_end(map, head), SelectionGoal::None)
10669            });
10670        })
10671    }
10672
10673    pub fn select_to_next_word_end(
10674        &mut self,
10675        _: &SelectToNextWordEnd,
10676        window: &mut Window,
10677        cx: &mut Context<Self>,
10678    ) {
10679        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10680        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10681            s.move_heads_with(|map, head, _| {
10682                (movement::next_word_end(map, head), SelectionGoal::None)
10683            });
10684        })
10685    }
10686
10687    pub fn select_to_next_subword_end(
10688        &mut self,
10689        _: &SelectToNextSubwordEnd,
10690        window: &mut Window,
10691        cx: &mut Context<Self>,
10692    ) {
10693        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10694        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10695            s.move_heads_with(|map, head, _| {
10696                (movement::next_subword_end(map, head), SelectionGoal::None)
10697            });
10698        })
10699    }
10700
10701    pub fn delete_to_next_word_end(
10702        &mut self,
10703        action: &DeleteToNextWordEnd,
10704        window: &mut Window,
10705        cx: &mut Context<Self>,
10706    ) {
10707        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10708        self.transact(window, cx, |this, window, cx| {
10709            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10710                s.move_with(|map, selection| {
10711                    if selection.is_empty() {
10712                        let cursor = if action.ignore_newlines {
10713                            movement::next_word_end(map, selection.head())
10714                        } else {
10715                            movement::next_word_end_or_newline(map, selection.head())
10716                        };
10717                        selection.set_head(cursor, SelectionGoal::None);
10718                    }
10719                });
10720            });
10721            this.insert("", window, cx);
10722        });
10723    }
10724
10725    pub fn delete_to_next_subword_end(
10726        &mut self,
10727        _: &DeleteToNextSubwordEnd,
10728        window: &mut Window,
10729        cx: &mut Context<Self>,
10730    ) {
10731        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10732        self.transact(window, cx, |this, window, cx| {
10733            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10734                s.move_with(|map, selection| {
10735                    if selection.is_empty() {
10736                        let cursor = movement::next_subword_end(map, selection.head());
10737                        selection.set_head(cursor, SelectionGoal::None);
10738                    }
10739                });
10740            });
10741            this.insert("", window, cx);
10742        });
10743    }
10744
10745    pub fn move_to_beginning_of_line(
10746        &mut self,
10747        action: &MoveToBeginningOfLine,
10748        window: &mut Window,
10749        cx: &mut Context<Self>,
10750    ) {
10751        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10752        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10753            s.move_cursors_with(|map, head, _| {
10754                (
10755                    movement::indented_line_beginning(
10756                        map,
10757                        head,
10758                        action.stop_at_soft_wraps,
10759                        action.stop_at_indent,
10760                    ),
10761                    SelectionGoal::None,
10762                )
10763            });
10764        })
10765    }
10766
10767    pub fn select_to_beginning_of_line(
10768        &mut self,
10769        action: &SelectToBeginningOfLine,
10770        window: &mut Window,
10771        cx: &mut Context<Self>,
10772    ) {
10773        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10774        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10775            s.move_heads_with(|map, head, _| {
10776                (
10777                    movement::indented_line_beginning(
10778                        map,
10779                        head,
10780                        action.stop_at_soft_wraps,
10781                        action.stop_at_indent,
10782                    ),
10783                    SelectionGoal::None,
10784                )
10785            });
10786        });
10787    }
10788
10789    pub fn delete_to_beginning_of_line(
10790        &mut self,
10791        action: &DeleteToBeginningOfLine,
10792        window: &mut Window,
10793        cx: &mut Context<Self>,
10794    ) {
10795        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10796        self.transact(window, cx, |this, window, cx| {
10797            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10798                s.move_with(|_, selection| {
10799                    selection.reversed = true;
10800                });
10801            });
10802
10803            this.select_to_beginning_of_line(
10804                &SelectToBeginningOfLine {
10805                    stop_at_soft_wraps: false,
10806                    stop_at_indent: action.stop_at_indent,
10807                },
10808                window,
10809                cx,
10810            );
10811            this.backspace(&Backspace, window, cx);
10812        });
10813    }
10814
10815    pub fn move_to_end_of_line(
10816        &mut self,
10817        action: &MoveToEndOfLine,
10818        window: &mut Window,
10819        cx: &mut Context<Self>,
10820    ) {
10821        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10822        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10823            s.move_cursors_with(|map, head, _| {
10824                (
10825                    movement::line_end(map, head, action.stop_at_soft_wraps),
10826                    SelectionGoal::None,
10827                )
10828            });
10829        })
10830    }
10831
10832    pub fn select_to_end_of_line(
10833        &mut self,
10834        action: &SelectToEndOfLine,
10835        window: &mut Window,
10836        cx: &mut Context<Self>,
10837    ) {
10838        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10839        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10840            s.move_heads_with(|map, head, _| {
10841                (
10842                    movement::line_end(map, head, action.stop_at_soft_wraps),
10843                    SelectionGoal::None,
10844                )
10845            });
10846        })
10847    }
10848
10849    pub fn delete_to_end_of_line(
10850        &mut self,
10851        _: &DeleteToEndOfLine,
10852        window: &mut Window,
10853        cx: &mut Context<Self>,
10854    ) {
10855        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10856        self.transact(window, cx, |this, window, cx| {
10857            this.select_to_end_of_line(
10858                &SelectToEndOfLine {
10859                    stop_at_soft_wraps: false,
10860                },
10861                window,
10862                cx,
10863            );
10864            this.delete(&Delete, window, cx);
10865        });
10866    }
10867
10868    pub fn cut_to_end_of_line(
10869        &mut self,
10870        _: &CutToEndOfLine,
10871        window: &mut Window,
10872        cx: &mut Context<Self>,
10873    ) {
10874        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10875        self.transact(window, cx, |this, window, cx| {
10876            this.select_to_end_of_line(
10877                &SelectToEndOfLine {
10878                    stop_at_soft_wraps: false,
10879                },
10880                window,
10881                cx,
10882            );
10883            this.cut(&Cut, window, cx);
10884        });
10885    }
10886
10887    pub fn move_to_start_of_paragraph(
10888        &mut self,
10889        _: &MoveToStartOfParagraph,
10890        window: &mut Window,
10891        cx: &mut Context<Self>,
10892    ) {
10893        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10894            cx.propagate();
10895            return;
10896        }
10897        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10898        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10899            s.move_with(|map, selection| {
10900                selection.collapse_to(
10901                    movement::start_of_paragraph(map, selection.head(), 1),
10902                    SelectionGoal::None,
10903                )
10904            });
10905        })
10906    }
10907
10908    pub fn move_to_end_of_paragraph(
10909        &mut self,
10910        _: &MoveToEndOfParagraph,
10911        window: &mut Window,
10912        cx: &mut Context<Self>,
10913    ) {
10914        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10915            cx.propagate();
10916            return;
10917        }
10918        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10919        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10920            s.move_with(|map, selection| {
10921                selection.collapse_to(
10922                    movement::end_of_paragraph(map, selection.head(), 1),
10923                    SelectionGoal::None,
10924                )
10925            });
10926        })
10927    }
10928
10929    pub fn select_to_start_of_paragraph(
10930        &mut self,
10931        _: &SelectToStartOfParagraph,
10932        window: &mut Window,
10933        cx: &mut Context<Self>,
10934    ) {
10935        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10936            cx.propagate();
10937            return;
10938        }
10939        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10940        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10941            s.move_heads_with(|map, head, _| {
10942                (
10943                    movement::start_of_paragraph(map, head, 1),
10944                    SelectionGoal::None,
10945                )
10946            });
10947        })
10948    }
10949
10950    pub fn select_to_end_of_paragraph(
10951        &mut self,
10952        _: &SelectToEndOfParagraph,
10953        window: &mut Window,
10954        cx: &mut Context<Self>,
10955    ) {
10956        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10957            cx.propagate();
10958            return;
10959        }
10960        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10961        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10962            s.move_heads_with(|map, head, _| {
10963                (
10964                    movement::end_of_paragraph(map, head, 1),
10965                    SelectionGoal::None,
10966                )
10967            });
10968        })
10969    }
10970
10971    pub fn move_to_start_of_excerpt(
10972        &mut self,
10973        _: &MoveToStartOfExcerpt,
10974        window: &mut Window,
10975        cx: &mut Context<Self>,
10976    ) {
10977        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10978            cx.propagate();
10979            return;
10980        }
10981        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10982        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10983            s.move_with(|map, selection| {
10984                selection.collapse_to(
10985                    movement::start_of_excerpt(
10986                        map,
10987                        selection.head(),
10988                        workspace::searchable::Direction::Prev,
10989                    ),
10990                    SelectionGoal::None,
10991                )
10992            });
10993        })
10994    }
10995
10996    pub fn move_to_start_of_next_excerpt(
10997        &mut self,
10998        _: &MoveToStartOfNextExcerpt,
10999        window: &mut Window,
11000        cx: &mut Context<Self>,
11001    ) {
11002        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11003            cx.propagate();
11004            return;
11005        }
11006
11007        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11008            s.move_with(|map, selection| {
11009                selection.collapse_to(
11010                    movement::start_of_excerpt(
11011                        map,
11012                        selection.head(),
11013                        workspace::searchable::Direction::Next,
11014                    ),
11015                    SelectionGoal::None,
11016                )
11017            });
11018        })
11019    }
11020
11021    pub fn move_to_end_of_excerpt(
11022        &mut self,
11023        _: &MoveToEndOfExcerpt,
11024        window: &mut Window,
11025        cx: &mut Context<Self>,
11026    ) {
11027        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11028            cx.propagate();
11029            return;
11030        }
11031        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11032        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11033            s.move_with(|map, selection| {
11034                selection.collapse_to(
11035                    movement::end_of_excerpt(
11036                        map,
11037                        selection.head(),
11038                        workspace::searchable::Direction::Next,
11039                    ),
11040                    SelectionGoal::None,
11041                )
11042            });
11043        })
11044    }
11045
11046    pub fn move_to_end_of_previous_excerpt(
11047        &mut self,
11048        _: &MoveToEndOfPreviousExcerpt,
11049        window: &mut Window,
11050        cx: &mut Context<Self>,
11051    ) {
11052        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11053            cx.propagate();
11054            return;
11055        }
11056        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11057        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11058            s.move_with(|map, selection| {
11059                selection.collapse_to(
11060                    movement::end_of_excerpt(
11061                        map,
11062                        selection.head(),
11063                        workspace::searchable::Direction::Prev,
11064                    ),
11065                    SelectionGoal::None,
11066                )
11067            });
11068        })
11069    }
11070
11071    pub fn select_to_start_of_excerpt(
11072        &mut self,
11073        _: &SelectToStartOfExcerpt,
11074        window: &mut Window,
11075        cx: &mut Context<Self>,
11076    ) {
11077        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11078            cx.propagate();
11079            return;
11080        }
11081        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11082        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11083            s.move_heads_with(|map, head, _| {
11084                (
11085                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11086                    SelectionGoal::None,
11087                )
11088            });
11089        })
11090    }
11091
11092    pub fn select_to_start_of_next_excerpt(
11093        &mut self,
11094        _: &SelectToStartOfNextExcerpt,
11095        window: &mut Window,
11096        cx: &mut Context<Self>,
11097    ) {
11098        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11099            cx.propagate();
11100            return;
11101        }
11102        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11103        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11104            s.move_heads_with(|map, head, _| {
11105                (
11106                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11107                    SelectionGoal::None,
11108                )
11109            });
11110        })
11111    }
11112
11113    pub fn select_to_end_of_excerpt(
11114        &mut self,
11115        _: &SelectToEndOfExcerpt,
11116        window: &mut Window,
11117        cx: &mut Context<Self>,
11118    ) {
11119        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11120            cx.propagate();
11121            return;
11122        }
11123        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11124        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11125            s.move_heads_with(|map, head, _| {
11126                (
11127                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11128                    SelectionGoal::None,
11129                )
11130            });
11131        })
11132    }
11133
11134    pub fn select_to_end_of_previous_excerpt(
11135        &mut self,
11136        _: &SelectToEndOfPreviousExcerpt,
11137        window: &mut Window,
11138        cx: &mut Context<Self>,
11139    ) {
11140        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11141            cx.propagate();
11142            return;
11143        }
11144        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11145        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11146            s.move_heads_with(|map, head, _| {
11147                (
11148                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11149                    SelectionGoal::None,
11150                )
11151            });
11152        })
11153    }
11154
11155    pub fn move_to_beginning(
11156        &mut self,
11157        _: &MoveToBeginning,
11158        window: &mut Window,
11159        cx: &mut Context<Self>,
11160    ) {
11161        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11162            cx.propagate();
11163            return;
11164        }
11165        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11166        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11167            s.select_ranges(vec![0..0]);
11168        });
11169    }
11170
11171    pub fn select_to_beginning(
11172        &mut self,
11173        _: &SelectToBeginning,
11174        window: &mut Window,
11175        cx: &mut Context<Self>,
11176    ) {
11177        let mut selection = self.selections.last::<Point>(cx);
11178        selection.set_head(Point::zero(), SelectionGoal::None);
11179        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11180        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11181            s.select(vec![selection]);
11182        });
11183    }
11184
11185    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11186        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11187            cx.propagate();
11188            return;
11189        }
11190        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11191        let cursor = self.buffer.read(cx).read(cx).len();
11192        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11193            s.select_ranges(vec![cursor..cursor])
11194        });
11195    }
11196
11197    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11198        self.nav_history = nav_history;
11199    }
11200
11201    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11202        self.nav_history.as_ref()
11203    }
11204
11205    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11206        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11207    }
11208
11209    fn push_to_nav_history(
11210        &mut self,
11211        cursor_anchor: Anchor,
11212        new_position: Option<Point>,
11213        is_deactivate: bool,
11214        cx: &mut Context<Self>,
11215    ) {
11216        if let Some(nav_history) = self.nav_history.as_mut() {
11217            let buffer = self.buffer.read(cx).read(cx);
11218            let cursor_position = cursor_anchor.to_point(&buffer);
11219            let scroll_state = self.scroll_manager.anchor();
11220            let scroll_top_row = scroll_state.top_row(&buffer);
11221            drop(buffer);
11222
11223            if let Some(new_position) = new_position {
11224                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11225                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11226                    return;
11227                }
11228            }
11229
11230            nav_history.push(
11231                Some(NavigationData {
11232                    cursor_anchor,
11233                    cursor_position,
11234                    scroll_anchor: scroll_state,
11235                    scroll_top_row,
11236                }),
11237                cx,
11238            );
11239            cx.emit(EditorEvent::PushedToNavHistory {
11240                anchor: cursor_anchor,
11241                is_deactivate,
11242            })
11243        }
11244    }
11245
11246    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11247        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11248        let buffer = self.buffer.read(cx).snapshot(cx);
11249        let mut selection = self.selections.first::<usize>(cx);
11250        selection.set_head(buffer.len(), SelectionGoal::None);
11251        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11252            s.select(vec![selection]);
11253        });
11254    }
11255
11256    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11257        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11258        let end = self.buffer.read(cx).read(cx).len();
11259        self.change_selections(None, window, cx, |s| {
11260            s.select_ranges(vec![0..end]);
11261        });
11262    }
11263
11264    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11265        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11266        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11267        let mut selections = self.selections.all::<Point>(cx);
11268        let max_point = display_map.buffer_snapshot.max_point();
11269        for selection in &mut selections {
11270            let rows = selection.spanned_rows(true, &display_map);
11271            selection.start = Point::new(rows.start.0, 0);
11272            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11273            selection.reversed = false;
11274        }
11275        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11276            s.select(selections);
11277        });
11278    }
11279
11280    pub fn split_selection_into_lines(
11281        &mut self,
11282        _: &SplitSelectionIntoLines,
11283        window: &mut Window,
11284        cx: &mut Context<Self>,
11285    ) {
11286        let selections = self
11287            .selections
11288            .all::<Point>(cx)
11289            .into_iter()
11290            .map(|selection| selection.start..selection.end)
11291            .collect::<Vec<_>>();
11292        self.unfold_ranges(&selections, true, true, cx);
11293
11294        let mut new_selection_ranges = Vec::new();
11295        {
11296            let buffer = self.buffer.read(cx).read(cx);
11297            for selection in selections {
11298                for row in selection.start.row..selection.end.row {
11299                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11300                    new_selection_ranges.push(cursor..cursor);
11301                }
11302
11303                let is_multiline_selection = selection.start.row != selection.end.row;
11304                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11305                // so this action feels more ergonomic when paired with other selection operations
11306                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11307                if !should_skip_last {
11308                    new_selection_ranges.push(selection.end..selection.end);
11309                }
11310            }
11311        }
11312        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11313            s.select_ranges(new_selection_ranges);
11314        });
11315    }
11316
11317    pub fn add_selection_above(
11318        &mut self,
11319        _: &AddSelectionAbove,
11320        window: &mut Window,
11321        cx: &mut Context<Self>,
11322    ) {
11323        self.add_selection(true, window, cx);
11324    }
11325
11326    pub fn add_selection_below(
11327        &mut self,
11328        _: &AddSelectionBelow,
11329        window: &mut Window,
11330        cx: &mut Context<Self>,
11331    ) {
11332        self.add_selection(false, window, cx);
11333    }
11334
11335    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11336        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11337
11338        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11339        let mut selections = self.selections.all::<Point>(cx);
11340        let text_layout_details = self.text_layout_details(window);
11341        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11342            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11343            let range = oldest_selection.display_range(&display_map).sorted();
11344
11345            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11346            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11347            let positions = start_x.min(end_x)..start_x.max(end_x);
11348
11349            selections.clear();
11350            let mut stack = Vec::new();
11351            for row in range.start.row().0..=range.end.row().0 {
11352                if let Some(selection) = self.selections.build_columnar_selection(
11353                    &display_map,
11354                    DisplayRow(row),
11355                    &positions,
11356                    oldest_selection.reversed,
11357                    &text_layout_details,
11358                ) {
11359                    stack.push(selection.id);
11360                    selections.push(selection);
11361                }
11362            }
11363
11364            if above {
11365                stack.reverse();
11366            }
11367
11368            AddSelectionsState { above, stack }
11369        });
11370
11371        let last_added_selection = *state.stack.last().unwrap();
11372        let mut new_selections = Vec::new();
11373        if above == state.above {
11374            let end_row = if above {
11375                DisplayRow(0)
11376            } else {
11377                display_map.max_point().row()
11378            };
11379
11380            'outer: for selection in selections {
11381                if selection.id == last_added_selection {
11382                    let range = selection.display_range(&display_map).sorted();
11383                    debug_assert_eq!(range.start.row(), range.end.row());
11384                    let mut row = range.start.row();
11385                    let positions =
11386                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11387                            px(start)..px(end)
11388                        } else {
11389                            let start_x =
11390                                display_map.x_for_display_point(range.start, &text_layout_details);
11391                            let end_x =
11392                                display_map.x_for_display_point(range.end, &text_layout_details);
11393                            start_x.min(end_x)..start_x.max(end_x)
11394                        };
11395
11396                    while row != end_row {
11397                        if above {
11398                            row.0 -= 1;
11399                        } else {
11400                            row.0 += 1;
11401                        }
11402
11403                        if let Some(new_selection) = self.selections.build_columnar_selection(
11404                            &display_map,
11405                            row,
11406                            &positions,
11407                            selection.reversed,
11408                            &text_layout_details,
11409                        ) {
11410                            state.stack.push(new_selection.id);
11411                            if above {
11412                                new_selections.push(new_selection);
11413                                new_selections.push(selection);
11414                            } else {
11415                                new_selections.push(selection);
11416                                new_selections.push(new_selection);
11417                            }
11418
11419                            continue 'outer;
11420                        }
11421                    }
11422                }
11423
11424                new_selections.push(selection);
11425            }
11426        } else {
11427            new_selections = selections;
11428            new_selections.retain(|s| s.id != last_added_selection);
11429            state.stack.pop();
11430        }
11431
11432        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11433            s.select(new_selections);
11434        });
11435        if state.stack.len() > 1 {
11436            self.add_selections_state = Some(state);
11437        }
11438    }
11439
11440    pub fn select_next_match_internal(
11441        &mut self,
11442        display_map: &DisplaySnapshot,
11443        replace_newest: bool,
11444        autoscroll: Option<Autoscroll>,
11445        window: &mut Window,
11446        cx: &mut Context<Self>,
11447    ) -> Result<()> {
11448        fn select_next_match_ranges(
11449            this: &mut Editor,
11450            range: Range<usize>,
11451            replace_newest: bool,
11452            auto_scroll: Option<Autoscroll>,
11453            window: &mut Window,
11454            cx: &mut Context<Editor>,
11455        ) {
11456            this.unfold_ranges(&[range.clone()], false, true, cx);
11457            this.change_selections(auto_scroll, window, cx, |s| {
11458                if replace_newest {
11459                    s.delete(s.newest_anchor().id);
11460                }
11461                s.insert_range(range.clone());
11462            });
11463        }
11464
11465        let buffer = &display_map.buffer_snapshot;
11466        let mut selections = self.selections.all::<usize>(cx);
11467        if let Some(mut select_next_state) = self.select_next_state.take() {
11468            let query = &select_next_state.query;
11469            if !select_next_state.done {
11470                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11471                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11472                let mut next_selected_range = None;
11473
11474                let bytes_after_last_selection =
11475                    buffer.bytes_in_range(last_selection.end..buffer.len());
11476                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11477                let query_matches = query
11478                    .stream_find_iter(bytes_after_last_selection)
11479                    .map(|result| (last_selection.end, result))
11480                    .chain(
11481                        query
11482                            .stream_find_iter(bytes_before_first_selection)
11483                            .map(|result| (0, result)),
11484                    );
11485
11486                for (start_offset, query_match) in query_matches {
11487                    let query_match = query_match.unwrap(); // can only fail due to I/O
11488                    let offset_range =
11489                        start_offset + query_match.start()..start_offset + query_match.end();
11490                    let display_range = offset_range.start.to_display_point(display_map)
11491                        ..offset_range.end.to_display_point(display_map);
11492
11493                    if !select_next_state.wordwise
11494                        || (!movement::is_inside_word(display_map, display_range.start)
11495                            && !movement::is_inside_word(display_map, display_range.end))
11496                    {
11497                        // TODO: This is n^2, because we might check all the selections
11498                        if !selections
11499                            .iter()
11500                            .any(|selection| selection.range().overlaps(&offset_range))
11501                        {
11502                            next_selected_range = Some(offset_range);
11503                            break;
11504                        }
11505                    }
11506                }
11507
11508                if let Some(next_selected_range) = next_selected_range {
11509                    select_next_match_ranges(
11510                        self,
11511                        next_selected_range,
11512                        replace_newest,
11513                        autoscroll,
11514                        window,
11515                        cx,
11516                    );
11517                } else {
11518                    select_next_state.done = true;
11519                }
11520            }
11521
11522            self.select_next_state = Some(select_next_state);
11523        } else {
11524            let mut only_carets = true;
11525            let mut same_text_selected = true;
11526            let mut selected_text = None;
11527
11528            let mut selections_iter = selections.iter().peekable();
11529            while let Some(selection) = selections_iter.next() {
11530                if selection.start != selection.end {
11531                    only_carets = false;
11532                }
11533
11534                if same_text_selected {
11535                    if selected_text.is_none() {
11536                        selected_text =
11537                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11538                    }
11539
11540                    if let Some(next_selection) = selections_iter.peek() {
11541                        if next_selection.range().len() == selection.range().len() {
11542                            let next_selected_text = buffer
11543                                .text_for_range(next_selection.range())
11544                                .collect::<String>();
11545                            if Some(next_selected_text) != selected_text {
11546                                same_text_selected = false;
11547                                selected_text = None;
11548                            }
11549                        } else {
11550                            same_text_selected = false;
11551                            selected_text = None;
11552                        }
11553                    }
11554                }
11555            }
11556
11557            if only_carets {
11558                for selection in &mut selections {
11559                    let word_range = movement::surrounding_word(
11560                        display_map,
11561                        selection.start.to_display_point(display_map),
11562                    );
11563                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11564                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11565                    selection.goal = SelectionGoal::None;
11566                    selection.reversed = false;
11567                    select_next_match_ranges(
11568                        self,
11569                        selection.start..selection.end,
11570                        replace_newest,
11571                        autoscroll,
11572                        window,
11573                        cx,
11574                    );
11575                }
11576
11577                if selections.len() == 1 {
11578                    let selection = selections
11579                        .last()
11580                        .expect("ensured that there's only one selection");
11581                    let query = buffer
11582                        .text_for_range(selection.start..selection.end)
11583                        .collect::<String>();
11584                    let is_empty = query.is_empty();
11585                    let select_state = SelectNextState {
11586                        query: AhoCorasick::new(&[query])?,
11587                        wordwise: true,
11588                        done: is_empty,
11589                    };
11590                    self.select_next_state = Some(select_state);
11591                } else {
11592                    self.select_next_state = None;
11593                }
11594            } else if let Some(selected_text) = selected_text {
11595                self.select_next_state = Some(SelectNextState {
11596                    query: AhoCorasick::new(&[selected_text])?,
11597                    wordwise: false,
11598                    done: false,
11599                });
11600                self.select_next_match_internal(
11601                    display_map,
11602                    replace_newest,
11603                    autoscroll,
11604                    window,
11605                    cx,
11606                )?;
11607            }
11608        }
11609        Ok(())
11610    }
11611
11612    pub fn select_all_matches(
11613        &mut self,
11614        _action: &SelectAllMatches,
11615        window: &mut Window,
11616        cx: &mut Context<Self>,
11617    ) -> Result<()> {
11618        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11619
11620        self.push_to_selection_history();
11621        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11622
11623        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11624        let Some(select_next_state) = self.select_next_state.as_mut() else {
11625            return Ok(());
11626        };
11627        if select_next_state.done {
11628            return Ok(());
11629        }
11630
11631        let mut new_selections = self.selections.all::<usize>(cx);
11632
11633        let buffer = &display_map.buffer_snapshot;
11634        let query_matches = select_next_state
11635            .query
11636            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11637
11638        for query_match in query_matches {
11639            let query_match = query_match.unwrap(); // can only fail due to I/O
11640            let offset_range = query_match.start()..query_match.end();
11641            let display_range = offset_range.start.to_display_point(&display_map)
11642                ..offset_range.end.to_display_point(&display_map);
11643
11644            if !select_next_state.wordwise
11645                || (!movement::is_inside_word(&display_map, display_range.start)
11646                    && !movement::is_inside_word(&display_map, display_range.end))
11647            {
11648                self.selections.change_with(cx, |selections| {
11649                    new_selections.push(Selection {
11650                        id: selections.new_selection_id(),
11651                        start: offset_range.start,
11652                        end: offset_range.end,
11653                        reversed: false,
11654                        goal: SelectionGoal::None,
11655                    });
11656                });
11657            }
11658        }
11659
11660        new_selections.sort_by_key(|selection| selection.start);
11661        let mut ix = 0;
11662        while ix + 1 < new_selections.len() {
11663            let current_selection = &new_selections[ix];
11664            let next_selection = &new_selections[ix + 1];
11665            if current_selection.range().overlaps(&next_selection.range()) {
11666                if current_selection.id < next_selection.id {
11667                    new_selections.remove(ix + 1);
11668                } else {
11669                    new_selections.remove(ix);
11670                }
11671            } else {
11672                ix += 1;
11673            }
11674        }
11675
11676        let reversed = self.selections.oldest::<usize>(cx).reversed;
11677
11678        for selection in new_selections.iter_mut() {
11679            selection.reversed = reversed;
11680        }
11681
11682        select_next_state.done = true;
11683        self.unfold_ranges(
11684            &new_selections
11685                .iter()
11686                .map(|selection| selection.range())
11687                .collect::<Vec<_>>(),
11688            false,
11689            false,
11690            cx,
11691        );
11692        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11693            selections.select(new_selections)
11694        });
11695
11696        Ok(())
11697    }
11698
11699    pub fn select_next(
11700        &mut self,
11701        action: &SelectNext,
11702        window: &mut Window,
11703        cx: &mut Context<Self>,
11704    ) -> Result<()> {
11705        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11706        self.push_to_selection_history();
11707        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11708        self.select_next_match_internal(
11709            &display_map,
11710            action.replace_newest,
11711            Some(Autoscroll::newest()),
11712            window,
11713            cx,
11714        )?;
11715        Ok(())
11716    }
11717
11718    pub fn select_previous(
11719        &mut self,
11720        action: &SelectPrevious,
11721        window: &mut Window,
11722        cx: &mut Context<Self>,
11723    ) -> Result<()> {
11724        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11725        self.push_to_selection_history();
11726        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11727        let buffer = &display_map.buffer_snapshot;
11728        let mut selections = self.selections.all::<usize>(cx);
11729        if let Some(mut select_prev_state) = self.select_prev_state.take() {
11730            let query = &select_prev_state.query;
11731            if !select_prev_state.done {
11732                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11733                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11734                let mut next_selected_range = None;
11735                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11736                let bytes_before_last_selection =
11737                    buffer.reversed_bytes_in_range(0..last_selection.start);
11738                let bytes_after_first_selection =
11739                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11740                let query_matches = query
11741                    .stream_find_iter(bytes_before_last_selection)
11742                    .map(|result| (last_selection.start, result))
11743                    .chain(
11744                        query
11745                            .stream_find_iter(bytes_after_first_selection)
11746                            .map(|result| (buffer.len(), result)),
11747                    );
11748                for (end_offset, query_match) in query_matches {
11749                    let query_match = query_match.unwrap(); // can only fail due to I/O
11750                    let offset_range =
11751                        end_offset - query_match.end()..end_offset - query_match.start();
11752                    let display_range = offset_range.start.to_display_point(&display_map)
11753                        ..offset_range.end.to_display_point(&display_map);
11754
11755                    if !select_prev_state.wordwise
11756                        || (!movement::is_inside_word(&display_map, display_range.start)
11757                            && !movement::is_inside_word(&display_map, display_range.end))
11758                    {
11759                        next_selected_range = Some(offset_range);
11760                        break;
11761                    }
11762                }
11763
11764                if let Some(next_selected_range) = next_selected_range {
11765                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11766                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11767                        if action.replace_newest {
11768                            s.delete(s.newest_anchor().id);
11769                        }
11770                        s.insert_range(next_selected_range);
11771                    });
11772                } else {
11773                    select_prev_state.done = true;
11774                }
11775            }
11776
11777            self.select_prev_state = Some(select_prev_state);
11778        } else {
11779            let mut only_carets = true;
11780            let mut same_text_selected = true;
11781            let mut selected_text = None;
11782
11783            let mut selections_iter = selections.iter().peekable();
11784            while let Some(selection) = selections_iter.next() {
11785                if selection.start != selection.end {
11786                    only_carets = false;
11787                }
11788
11789                if same_text_selected {
11790                    if selected_text.is_none() {
11791                        selected_text =
11792                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11793                    }
11794
11795                    if let Some(next_selection) = selections_iter.peek() {
11796                        if next_selection.range().len() == selection.range().len() {
11797                            let next_selected_text = buffer
11798                                .text_for_range(next_selection.range())
11799                                .collect::<String>();
11800                            if Some(next_selected_text) != selected_text {
11801                                same_text_selected = false;
11802                                selected_text = None;
11803                            }
11804                        } else {
11805                            same_text_selected = false;
11806                            selected_text = None;
11807                        }
11808                    }
11809                }
11810            }
11811
11812            if only_carets {
11813                for selection in &mut selections {
11814                    let word_range = movement::surrounding_word(
11815                        &display_map,
11816                        selection.start.to_display_point(&display_map),
11817                    );
11818                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11819                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11820                    selection.goal = SelectionGoal::None;
11821                    selection.reversed = false;
11822                }
11823                if selections.len() == 1 {
11824                    let selection = selections
11825                        .last()
11826                        .expect("ensured that there's only one selection");
11827                    let query = buffer
11828                        .text_for_range(selection.start..selection.end)
11829                        .collect::<String>();
11830                    let is_empty = query.is_empty();
11831                    let select_state = SelectNextState {
11832                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11833                        wordwise: true,
11834                        done: is_empty,
11835                    };
11836                    self.select_prev_state = Some(select_state);
11837                } else {
11838                    self.select_prev_state = None;
11839                }
11840
11841                self.unfold_ranges(
11842                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11843                    false,
11844                    true,
11845                    cx,
11846                );
11847                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11848                    s.select(selections);
11849                });
11850            } else if let Some(selected_text) = selected_text {
11851                self.select_prev_state = Some(SelectNextState {
11852                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11853                    wordwise: false,
11854                    done: false,
11855                });
11856                self.select_previous(action, window, cx)?;
11857            }
11858        }
11859        Ok(())
11860    }
11861
11862    pub fn toggle_comments(
11863        &mut self,
11864        action: &ToggleComments,
11865        window: &mut Window,
11866        cx: &mut Context<Self>,
11867    ) {
11868        if self.read_only(cx) {
11869            return;
11870        }
11871        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11872        let text_layout_details = &self.text_layout_details(window);
11873        self.transact(window, cx, |this, window, cx| {
11874            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11875            let mut edits = Vec::new();
11876            let mut selection_edit_ranges = Vec::new();
11877            let mut last_toggled_row = None;
11878            let snapshot = this.buffer.read(cx).read(cx);
11879            let empty_str: Arc<str> = Arc::default();
11880            let mut suffixes_inserted = Vec::new();
11881            let ignore_indent = action.ignore_indent;
11882
11883            fn comment_prefix_range(
11884                snapshot: &MultiBufferSnapshot,
11885                row: MultiBufferRow,
11886                comment_prefix: &str,
11887                comment_prefix_whitespace: &str,
11888                ignore_indent: bool,
11889            ) -> Range<Point> {
11890                let indent_size = if ignore_indent {
11891                    0
11892                } else {
11893                    snapshot.indent_size_for_line(row).len
11894                };
11895
11896                let start = Point::new(row.0, indent_size);
11897
11898                let mut line_bytes = snapshot
11899                    .bytes_in_range(start..snapshot.max_point())
11900                    .flatten()
11901                    .copied();
11902
11903                // If this line currently begins with the line comment prefix, then record
11904                // the range containing the prefix.
11905                if line_bytes
11906                    .by_ref()
11907                    .take(comment_prefix.len())
11908                    .eq(comment_prefix.bytes())
11909                {
11910                    // Include any whitespace that matches the comment prefix.
11911                    let matching_whitespace_len = line_bytes
11912                        .zip(comment_prefix_whitespace.bytes())
11913                        .take_while(|(a, b)| a == b)
11914                        .count() as u32;
11915                    let end = Point::new(
11916                        start.row,
11917                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11918                    );
11919                    start..end
11920                } else {
11921                    start..start
11922                }
11923            }
11924
11925            fn comment_suffix_range(
11926                snapshot: &MultiBufferSnapshot,
11927                row: MultiBufferRow,
11928                comment_suffix: &str,
11929                comment_suffix_has_leading_space: bool,
11930            ) -> Range<Point> {
11931                let end = Point::new(row.0, snapshot.line_len(row));
11932                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11933
11934                let mut line_end_bytes = snapshot
11935                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11936                    .flatten()
11937                    .copied();
11938
11939                let leading_space_len = if suffix_start_column > 0
11940                    && line_end_bytes.next() == Some(b' ')
11941                    && comment_suffix_has_leading_space
11942                {
11943                    1
11944                } else {
11945                    0
11946                };
11947
11948                // If this line currently begins with the line comment prefix, then record
11949                // the range containing the prefix.
11950                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
11951                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
11952                    start..end
11953                } else {
11954                    end..end
11955                }
11956            }
11957
11958            // TODO: Handle selections that cross excerpts
11959            for selection in &mut selections {
11960                let start_column = snapshot
11961                    .indent_size_for_line(MultiBufferRow(selection.start.row))
11962                    .len;
11963                let language = if let Some(language) =
11964                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
11965                {
11966                    language
11967                } else {
11968                    continue;
11969                };
11970
11971                selection_edit_ranges.clear();
11972
11973                // If multiple selections contain a given row, avoid processing that
11974                // row more than once.
11975                let mut start_row = MultiBufferRow(selection.start.row);
11976                if last_toggled_row == Some(start_row) {
11977                    start_row = start_row.next_row();
11978                }
11979                let end_row =
11980                    if selection.end.row > selection.start.row && selection.end.column == 0 {
11981                        MultiBufferRow(selection.end.row - 1)
11982                    } else {
11983                        MultiBufferRow(selection.end.row)
11984                    };
11985                last_toggled_row = Some(end_row);
11986
11987                if start_row > end_row {
11988                    continue;
11989                }
11990
11991                // If the language has line comments, toggle those.
11992                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
11993
11994                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
11995                if ignore_indent {
11996                    full_comment_prefixes = full_comment_prefixes
11997                        .into_iter()
11998                        .map(|s| Arc::from(s.trim_end()))
11999                        .collect();
12000                }
12001
12002                if !full_comment_prefixes.is_empty() {
12003                    let first_prefix = full_comment_prefixes
12004                        .first()
12005                        .expect("prefixes is non-empty");
12006                    let prefix_trimmed_lengths = full_comment_prefixes
12007                        .iter()
12008                        .map(|p| p.trim_end_matches(' ').len())
12009                        .collect::<SmallVec<[usize; 4]>>();
12010
12011                    let mut all_selection_lines_are_comments = true;
12012
12013                    for row in start_row.0..=end_row.0 {
12014                        let row = MultiBufferRow(row);
12015                        if start_row < end_row && snapshot.is_line_blank(row) {
12016                            continue;
12017                        }
12018
12019                        let prefix_range = full_comment_prefixes
12020                            .iter()
12021                            .zip(prefix_trimmed_lengths.iter().copied())
12022                            .map(|(prefix, trimmed_prefix_len)| {
12023                                comment_prefix_range(
12024                                    snapshot.deref(),
12025                                    row,
12026                                    &prefix[..trimmed_prefix_len],
12027                                    &prefix[trimmed_prefix_len..],
12028                                    ignore_indent,
12029                                )
12030                            })
12031                            .max_by_key(|range| range.end.column - range.start.column)
12032                            .expect("prefixes is non-empty");
12033
12034                        if prefix_range.is_empty() {
12035                            all_selection_lines_are_comments = false;
12036                        }
12037
12038                        selection_edit_ranges.push(prefix_range);
12039                    }
12040
12041                    if all_selection_lines_are_comments {
12042                        edits.extend(
12043                            selection_edit_ranges
12044                                .iter()
12045                                .cloned()
12046                                .map(|range| (range, empty_str.clone())),
12047                        );
12048                    } else {
12049                        let min_column = selection_edit_ranges
12050                            .iter()
12051                            .map(|range| range.start.column)
12052                            .min()
12053                            .unwrap_or(0);
12054                        edits.extend(selection_edit_ranges.iter().map(|range| {
12055                            let position = Point::new(range.start.row, min_column);
12056                            (position..position, first_prefix.clone())
12057                        }));
12058                    }
12059                } else if let Some((full_comment_prefix, comment_suffix)) =
12060                    language.block_comment_delimiters()
12061                {
12062                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12063                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12064                    let prefix_range = comment_prefix_range(
12065                        snapshot.deref(),
12066                        start_row,
12067                        comment_prefix,
12068                        comment_prefix_whitespace,
12069                        ignore_indent,
12070                    );
12071                    let suffix_range = comment_suffix_range(
12072                        snapshot.deref(),
12073                        end_row,
12074                        comment_suffix.trim_start_matches(' '),
12075                        comment_suffix.starts_with(' '),
12076                    );
12077
12078                    if prefix_range.is_empty() || suffix_range.is_empty() {
12079                        edits.push((
12080                            prefix_range.start..prefix_range.start,
12081                            full_comment_prefix.clone(),
12082                        ));
12083                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12084                        suffixes_inserted.push((end_row, comment_suffix.len()));
12085                    } else {
12086                        edits.push((prefix_range, empty_str.clone()));
12087                        edits.push((suffix_range, empty_str.clone()));
12088                    }
12089                } else {
12090                    continue;
12091                }
12092            }
12093
12094            drop(snapshot);
12095            this.buffer.update(cx, |buffer, cx| {
12096                buffer.edit(edits, None, cx);
12097            });
12098
12099            // Adjust selections so that they end before any comment suffixes that
12100            // were inserted.
12101            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12102            let mut selections = this.selections.all::<Point>(cx);
12103            let snapshot = this.buffer.read(cx).read(cx);
12104            for selection in &mut selections {
12105                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12106                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12107                        Ordering::Less => {
12108                            suffixes_inserted.next();
12109                            continue;
12110                        }
12111                        Ordering::Greater => break,
12112                        Ordering::Equal => {
12113                            if selection.end.column == snapshot.line_len(row) {
12114                                if selection.is_empty() {
12115                                    selection.start.column -= suffix_len as u32;
12116                                }
12117                                selection.end.column -= suffix_len as u32;
12118                            }
12119                            break;
12120                        }
12121                    }
12122                }
12123            }
12124
12125            drop(snapshot);
12126            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12127                s.select(selections)
12128            });
12129
12130            let selections = this.selections.all::<Point>(cx);
12131            let selections_on_single_row = selections.windows(2).all(|selections| {
12132                selections[0].start.row == selections[1].start.row
12133                    && selections[0].end.row == selections[1].end.row
12134                    && selections[0].start.row == selections[0].end.row
12135            });
12136            let selections_selecting = selections
12137                .iter()
12138                .any(|selection| selection.start != selection.end);
12139            let advance_downwards = action.advance_downwards
12140                && selections_on_single_row
12141                && !selections_selecting
12142                && !matches!(this.mode, EditorMode::SingleLine { .. });
12143
12144            if advance_downwards {
12145                let snapshot = this.buffer.read(cx).snapshot(cx);
12146
12147                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12148                    s.move_cursors_with(|display_snapshot, display_point, _| {
12149                        let mut point = display_point.to_point(display_snapshot);
12150                        point.row += 1;
12151                        point = snapshot.clip_point(point, Bias::Left);
12152                        let display_point = point.to_display_point(display_snapshot);
12153                        let goal = SelectionGoal::HorizontalPosition(
12154                            display_snapshot
12155                                .x_for_display_point(display_point, text_layout_details)
12156                                .into(),
12157                        );
12158                        (display_point, goal)
12159                    })
12160                });
12161            }
12162        });
12163    }
12164
12165    pub fn select_enclosing_symbol(
12166        &mut self,
12167        _: &SelectEnclosingSymbol,
12168        window: &mut Window,
12169        cx: &mut Context<Self>,
12170    ) {
12171        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12172
12173        let buffer = self.buffer.read(cx).snapshot(cx);
12174        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12175
12176        fn update_selection(
12177            selection: &Selection<usize>,
12178            buffer_snap: &MultiBufferSnapshot,
12179        ) -> Option<Selection<usize>> {
12180            let cursor = selection.head();
12181            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12182            for symbol in symbols.iter().rev() {
12183                let start = symbol.range.start.to_offset(buffer_snap);
12184                let end = symbol.range.end.to_offset(buffer_snap);
12185                let new_range = start..end;
12186                if start < selection.start || end > selection.end {
12187                    return Some(Selection {
12188                        id: selection.id,
12189                        start: new_range.start,
12190                        end: new_range.end,
12191                        goal: SelectionGoal::None,
12192                        reversed: selection.reversed,
12193                    });
12194                }
12195            }
12196            None
12197        }
12198
12199        let mut selected_larger_symbol = false;
12200        let new_selections = old_selections
12201            .iter()
12202            .map(|selection| match update_selection(selection, &buffer) {
12203                Some(new_selection) => {
12204                    if new_selection.range() != selection.range() {
12205                        selected_larger_symbol = true;
12206                    }
12207                    new_selection
12208                }
12209                None => selection.clone(),
12210            })
12211            .collect::<Vec<_>>();
12212
12213        if selected_larger_symbol {
12214            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12215                s.select(new_selections);
12216            });
12217        }
12218    }
12219
12220    pub fn select_larger_syntax_node(
12221        &mut self,
12222        _: &SelectLargerSyntaxNode,
12223        window: &mut Window,
12224        cx: &mut Context<Self>,
12225    ) {
12226        let Some(visible_row_count) = self.visible_row_count() else {
12227            return;
12228        };
12229        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12230        if old_selections.is_empty() {
12231            return;
12232        }
12233
12234        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12235
12236        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12237        let buffer = self.buffer.read(cx).snapshot(cx);
12238
12239        let mut selected_larger_node = false;
12240        let mut new_selections = old_selections
12241            .iter()
12242            .map(|selection| {
12243                let old_range = selection.start..selection.end;
12244                let mut new_range = old_range.clone();
12245                let mut new_node = None;
12246                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12247                {
12248                    new_node = Some(node);
12249                    new_range = match containing_range {
12250                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12251                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12252                    };
12253                    if !display_map.intersects_fold(new_range.start)
12254                        && !display_map.intersects_fold(new_range.end)
12255                    {
12256                        break;
12257                    }
12258                }
12259
12260                if let Some(node) = new_node {
12261                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12262                    // nodes. Parent and grandparent are also logged because this operation will not
12263                    // visit nodes that have the same range as their parent.
12264                    log::info!("Node: {node:?}");
12265                    let parent = node.parent();
12266                    log::info!("Parent: {parent:?}");
12267                    let grandparent = parent.and_then(|x| x.parent());
12268                    log::info!("Grandparent: {grandparent:?}");
12269                }
12270
12271                selected_larger_node |= new_range != old_range;
12272                Selection {
12273                    id: selection.id,
12274                    start: new_range.start,
12275                    end: new_range.end,
12276                    goal: SelectionGoal::None,
12277                    reversed: selection.reversed,
12278                }
12279            })
12280            .collect::<Vec<_>>();
12281
12282        if !selected_larger_node {
12283            return; // don't put this call in the history
12284        }
12285
12286        // scroll based on transformation done to the last selection created by the user
12287        let (last_old, last_new) = old_selections
12288            .last()
12289            .zip(new_selections.last().cloned())
12290            .expect("old_selections isn't empty");
12291
12292        // revert selection
12293        let is_selection_reversed = {
12294            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12295            new_selections.last_mut().expect("checked above").reversed =
12296                should_newest_selection_be_reversed;
12297            should_newest_selection_be_reversed
12298        };
12299
12300        if selected_larger_node {
12301            self.select_syntax_node_history.disable_clearing = true;
12302            self.change_selections(None, window, cx, |s| {
12303                s.select(new_selections.clone());
12304            });
12305            self.select_syntax_node_history.disable_clearing = false;
12306        }
12307
12308        let start_row = last_new.start.to_display_point(&display_map).row().0;
12309        let end_row = last_new.end.to_display_point(&display_map).row().0;
12310        let selection_height = end_row - start_row + 1;
12311        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12312
12313        // if fits on screen (considering margin), keep it in the middle, else, scroll to selection head
12314        let scroll_behavior = if visible_row_count >= selection_height + scroll_margin_rows * 2 {
12315            let middle_row = (end_row + start_row) / 2;
12316            let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12317            self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12318            SelectSyntaxNodeScrollBehavior::CenterSelection
12319        } else if is_selection_reversed {
12320            self.scroll_cursor_top(&Default::default(), window, cx);
12321            SelectSyntaxNodeScrollBehavior::CursorTop
12322        } else {
12323            self.scroll_cursor_bottom(&Default::default(), window, cx);
12324            SelectSyntaxNodeScrollBehavior::CursorBottom
12325        };
12326
12327        self.select_syntax_node_history.push((
12328            old_selections,
12329            scroll_behavior,
12330            is_selection_reversed,
12331        ));
12332    }
12333
12334    pub fn select_smaller_syntax_node(
12335        &mut self,
12336        _: &SelectSmallerSyntaxNode,
12337        window: &mut Window,
12338        cx: &mut Context<Self>,
12339    ) {
12340        let Some(visible_row_count) = self.visible_row_count() else {
12341            return;
12342        };
12343
12344        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12345
12346        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12347            self.select_syntax_node_history.pop()
12348        {
12349            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12350
12351            if let Some(selection) = selections.last_mut() {
12352                selection.reversed = is_selection_reversed;
12353            }
12354
12355            self.select_syntax_node_history.disable_clearing = true;
12356            self.change_selections(None, window, cx, |s| {
12357                s.select(selections.to_vec());
12358            });
12359            self.select_syntax_node_history.disable_clearing = false;
12360
12361            let newest = self.selections.newest::<usize>(cx);
12362            let start_row = newest.start.to_display_point(&display_map).row().0;
12363            let end_row = newest.end.to_display_point(&display_map).row().0;
12364
12365            match scroll_behavior {
12366                SelectSyntaxNodeScrollBehavior::CursorTop => {
12367                    self.scroll_cursor_top(&Default::default(), window, cx);
12368                }
12369                SelectSyntaxNodeScrollBehavior::CenterSelection => {
12370                    let middle_row = (end_row + start_row) / 2;
12371                    let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12372                    // centralize the selection, not the cursor
12373                    self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12374                }
12375                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12376                    self.scroll_cursor_bottom(&Default::default(), window, cx);
12377                }
12378            }
12379        }
12380    }
12381
12382    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12383        if !EditorSettings::get_global(cx).gutter.runnables {
12384            self.clear_tasks();
12385            return Task::ready(());
12386        }
12387        let project = self.project.as_ref().map(Entity::downgrade);
12388        cx.spawn_in(window, async move |this, cx| {
12389            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12390            let Some(project) = project.and_then(|p| p.upgrade()) else {
12391                return;
12392            };
12393            let Ok(display_snapshot) = this.update(cx, |this, cx| {
12394                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12395            }) else {
12396                return;
12397            };
12398
12399            let hide_runnables = project
12400                .update(cx, |project, cx| {
12401                    // Do not display any test indicators in non-dev server remote projects.
12402                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12403                })
12404                .unwrap_or(true);
12405            if hide_runnables {
12406                return;
12407            }
12408            let new_rows =
12409                cx.background_spawn({
12410                    let snapshot = display_snapshot.clone();
12411                    async move {
12412                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12413                    }
12414                })
12415                    .await;
12416
12417            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12418            this.update(cx, |this, _| {
12419                this.clear_tasks();
12420                for (key, value) in rows {
12421                    this.insert_tasks(key, value);
12422                }
12423            })
12424            .ok();
12425        })
12426    }
12427    fn fetch_runnable_ranges(
12428        snapshot: &DisplaySnapshot,
12429        range: Range<Anchor>,
12430    ) -> Vec<language::RunnableRange> {
12431        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12432    }
12433
12434    fn runnable_rows(
12435        project: Entity<Project>,
12436        snapshot: DisplaySnapshot,
12437        runnable_ranges: Vec<RunnableRange>,
12438        mut cx: AsyncWindowContext,
12439    ) -> Vec<((BufferId, u32), RunnableTasks)> {
12440        runnable_ranges
12441            .into_iter()
12442            .filter_map(|mut runnable| {
12443                let tasks = cx
12444                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12445                    .ok()?;
12446                if tasks.is_empty() {
12447                    return None;
12448                }
12449
12450                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12451
12452                let row = snapshot
12453                    .buffer_snapshot
12454                    .buffer_line_for_row(MultiBufferRow(point.row))?
12455                    .1
12456                    .start
12457                    .row;
12458
12459                let context_range =
12460                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12461                Some((
12462                    (runnable.buffer_id, row),
12463                    RunnableTasks {
12464                        templates: tasks,
12465                        offset: snapshot
12466                            .buffer_snapshot
12467                            .anchor_before(runnable.run_range.start),
12468                        context_range,
12469                        column: point.column,
12470                        extra_variables: runnable.extra_captures,
12471                    },
12472                ))
12473            })
12474            .collect()
12475    }
12476
12477    fn templates_with_tags(
12478        project: &Entity<Project>,
12479        runnable: &mut Runnable,
12480        cx: &mut App,
12481    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12482        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12483            let (worktree_id, file) = project
12484                .buffer_for_id(runnable.buffer, cx)
12485                .and_then(|buffer| buffer.read(cx).file())
12486                .map(|file| (file.worktree_id(cx), file.clone()))
12487                .unzip();
12488
12489            (
12490                project.task_store().read(cx).task_inventory().cloned(),
12491                worktree_id,
12492                file,
12493            )
12494        });
12495
12496        let tags = mem::take(&mut runnable.tags);
12497        let mut tags: Vec<_> = tags
12498            .into_iter()
12499            .flat_map(|tag| {
12500                let tag = tag.0.clone();
12501                inventory
12502                    .as_ref()
12503                    .into_iter()
12504                    .flat_map(|inventory| {
12505                        inventory.read(cx).list_tasks(
12506                            file.clone(),
12507                            Some(runnable.language.clone()),
12508                            worktree_id,
12509                            cx,
12510                        )
12511                    })
12512                    .filter(move |(_, template)| {
12513                        template.tags.iter().any(|source_tag| source_tag == &tag)
12514                    })
12515            })
12516            .sorted_by_key(|(kind, _)| kind.to_owned())
12517            .collect();
12518        if let Some((leading_tag_source, _)) = tags.first() {
12519            // Strongest source wins; if we have worktree tag binding, prefer that to
12520            // global and language bindings;
12521            // if we have a global binding, prefer that to language binding.
12522            let first_mismatch = tags
12523                .iter()
12524                .position(|(tag_source, _)| tag_source != leading_tag_source);
12525            if let Some(index) = first_mismatch {
12526                tags.truncate(index);
12527            }
12528        }
12529
12530        tags
12531    }
12532
12533    pub fn move_to_enclosing_bracket(
12534        &mut self,
12535        _: &MoveToEnclosingBracket,
12536        window: &mut Window,
12537        cx: &mut Context<Self>,
12538    ) {
12539        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12540        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12541            s.move_offsets_with(|snapshot, selection| {
12542                let Some(enclosing_bracket_ranges) =
12543                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12544                else {
12545                    return;
12546                };
12547
12548                let mut best_length = usize::MAX;
12549                let mut best_inside = false;
12550                let mut best_in_bracket_range = false;
12551                let mut best_destination = None;
12552                for (open, close) in enclosing_bracket_ranges {
12553                    let close = close.to_inclusive();
12554                    let length = close.end() - open.start;
12555                    let inside = selection.start >= open.end && selection.end <= *close.start();
12556                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12557                        || close.contains(&selection.head());
12558
12559                    // If best is next to a bracket and current isn't, skip
12560                    if !in_bracket_range && best_in_bracket_range {
12561                        continue;
12562                    }
12563
12564                    // Prefer smaller lengths unless best is inside and current isn't
12565                    if length > best_length && (best_inside || !inside) {
12566                        continue;
12567                    }
12568
12569                    best_length = length;
12570                    best_inside = inside;
12571                    best_in_bracket_range = in_bracket_range;
12572                    best_destination = Some(
12573                        if close.contains(&selection.start) && close.contains(&selection.end) {
12574                            if inside { open.end } else { open.start }
12575                        } else if inside {
12576                            *close.start()
12577                        } else {
12578                            *close.end()
12579                        },
12580                    );
12581                }
12582
12583                if let Some(destination) = best_destination {
12584                    selection.collapse_to(destination, SelectionGoal::None);
12585                }
12586            })
12587        });
12588    }
12589
12590    pub fn undo_selection(
12591        &mut self,
12592        _: &UndoSelection,
12593        window: &mut Window,
12594        cx: &mut Context<Self>,
12595    ) {
12596        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12597        self.end_selection(window, cx);
12598        self.selection_history.mode = SelectionHistoryMode::Undoing;
12599        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12600            self.change_selections(None, window, cx, |s| {
12601                s.select_anchors(entry.selections.to_vec())
12602            });
12603            self.select_next_state = entry.select_next_state;
12604            self.select_prev_state = entry.select_prev_state;
12605            self.add_selections_state = entry.add_selections_state;
12606            self.request_autoscroll(Autoscroll::newest(), cx);
12607        }
12608        self.selection_history.mode = SelectionHistoryMode::Normal;
12609    }
12610
12611    pub fn redo_selection(
12612        &mut self,
12613        _: &RedoSelection,
12614        window: &mut Window,
12615        cx: &mut Context<Self>,
12616    ) {
12617        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12618        self.end_selection(window, cx);
12619        self.selection_history.mode = SelectionHistoryMode::Redoing;
12620        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12621            self.change_selections(None, window, cx, |s| {
12622                s.select_anchors(entry.selections.to_vec())
12623            });
12624            self.select_next_state = entry.select_next_state;
12625            self.select_prev_state = entry.select_prev_state;
12626            self.add_selections_state = entry.add_selections_state;
12627            self.request_autoscroll(Autoscroll::newest(), cx);
12628        }
12629        self.selection_history.mode = SelectionHistoryMode::Normal;
12630    }
12631
12632    pub fn expand_excerpts(
12633        &mut self,
12634        action: &ExpandExcerpts,
12635        _: &mut Window,
12636        cx: &mut Context<Self>,
12637    ) {
12638        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12639    }
12640
12641    pub fn expand_excerpts_down(
12642        &mut self,
12643        action: &ExpandExcerptsDown,
12644        _: &mut Window,
12645        cx: &mut Context<Self>,
12646    ) {
12647        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12648    }
12649
12650    pub fn expand_excerpts_up(
12651        &mut self,
12652        action: &ExpandExcerptsUp,
12653        _: &mut Window,
12654        cx: &mut Context<Self>,
12655    ) {
12656        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12657    }
12658
12659    pub fn expand_excerpts_for_direction(
12660        &mut self,
12661        lines: u32,
12662        direction: ExpandExcerptDirection,
12663
12664        cx: &mut Context<Self>,
12665    ) {
12666        let selections = self.selections.disjoint_anchors();
12667
12668        let lines = if lines == 0 {
12669            EditorSettings::get_global(cx).expand_excerpt_lines
12670        } else {
12671            lines
12672        };
12673
12674        self.buffer.update(cx, |buffer, cx| {
12675            let snapshot = buffer.snapshot(cx);
12676            let mut excerpt_ids = selections
12677                .iter()
12678                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12679                .collect::<Vec<_>>();
12680            excerpt_ids.sort();
12681            excerpt_ids.dedup();
12682            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12683        })
12684    }
12685
12686    pub fn expand_excerpt(
12687        &mut self,
12688        excerpt: ExcerptId,
12689        direction: ExpandExcerptDirection,
12690        window: &mut Window,
12691        cx: &mut Context<Self>,
12692    ) {
12693        let current_scroll_position = self.scroll_position(cx);
12694        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12695        self.buffer.update(cx, |buffer, cx| {
12696            buffer.expand_excerpts([excerpt], lines, direction, cx)
12697        });
12698        if direction == ExpandExcerptDirection::Down {
12699            let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12700            self.set_scroll_position(new_scroll_position, window, cx);
12701        }
12702    }
12703
12704    pub fn go_to_singleton_buffer_point(
12705        &mut self,
12706        point: Point,
12707        window: &mut Window,
12708        cx: &mut Context<Self>,
12709    ) {
12710        self.go_to_singleton_buffer_range(point..point, window, cx);
12711    }
12712
12713    pub fn go_to_singleton_buffer_range(
12714        &mut self,
12715        range: Range<Point>,
12716        window: &mut Window,
12717        cx: &mut Context<Self>,
12718    ) {
12719        let multibuffer = self.buffer().read(cx);
12720        let Some(buffer) = multibuffer.as_singleton() else {
12721            return;
12722        };
12723        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12724            return;
12725        };
12726        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12727            return;
12728        };
12729        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12730            s.select_anchor_ranges([start..end])
12731        });
12732    }
12733
12734    fn go_to_diagnostic(
12735        &mut self,
12736        _: &GoToDiagnostic,
12737        window: &mut Window,
12738        cx: &mut Context<Self>,
12739    ) {
12740        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12741        self.go_to_diagnostic_impl(Direction::Next, window, cx)
12742    }
12743
12744    fn go_to_prev_diagnostic(
12745        &mut self,
12746        _: &GoToPreviousDiagnostic,
12747        window: &mut Window,
12748        cx: &mut Context<Self>,
12749    ) {
12750        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12751        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12752    }
12753
12754    pub fn go_to_diagnostic_impl(
12755        &mut self,
12756        direction: Direction,
12757        window: &mut Window,
12758        cx: &mut Context<Self>,
12759    ) {
12760        let buffer = self.buffer.read(cx).snapshot(cx);
12761        let selection = self.selections.newest::<usize>(cx);
12762
12763        // If there is an active Diagnostic Popover jump to its diagnostic instead.
12764        if direction == Direction::Next {
12765            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12766                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12767                    return;
12768                };
12769                self.activate_diagnostics(
12770                    buffer_id,
12771                    popover.local_diagnostic.diagnostic.group_id,
12772                    window,
12773                    cx,
12774                );
12775                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12776                    let primary_range_start = active_diagnostics.primary_range.start;
12777                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12778                        let mut new_selection = s.newest_anchor().clone();
12779                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12780                        s.select_anchors(vec![new_selection.clone()]);
12781                    });
12782                    self.refresh_inline_completion(false, true, window, cx);
12783                }
12784                return;
12785            }
12786        }
12787
12788        let active_group_id = self
12789            .active_diagnostics
12790            .as_ref()
12791            .map(|active_group| active_group.group_id);
12792        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12793            active_diagnostics
12794                .primary_range
12795                .to_offset(&buffer)
12796                .to_inclusive()
12797        });
12798        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12799            if active_primary_range.contains(&selection.head()) {
12800                *active_primary_range.start()
12801            } else {
12802                selection.head()
12803            }
12804        } else {
12805            selection.head()
12806        };
12807
12808        let snapshot = self.snapshot(window, cx);
12809        let primary_diagnostics_before = buffer
12810            .diagnostics_in_range::<usize>(0..search_start)
12811            .filter(|entry| entry.diagnostic.is_primary)
12812            .filter(|entry| entry.range.start != entry.range.end)
12813            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12814            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12815            .collect::<Vec<_>>();
12816        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12817            primary_diagnostics_before
12818                .iter()
12819                .position(|entry| entry.diagnostic.group_id == active_group_id)
12820        });
12821
12822        let primary_diagnostics_after = buffer
12823            .diagnostics_in_range::<usize>(search_start..buffer.len())
12824            .filter(|entry| entry.diagnostic.is_primary)
12825            .filter(|entry| entry.range.start != entry.range.end)
12826            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12827            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12828            .collect::<Vec<_>>();
12829        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12830            primary_diagnostics_after
12831                .iter()
12832                .enumerate()
12833                .rev()
12834                .find_map(|(i, entry)| {
12835                    if entry.diagnostic.group_id == active_group_id {
12836                        Some(i)
12837                    } else {
12838                        None
12839                    }
12840                })
12841        });
12842
12843        let next_primary_diagnostic = match direction {
12844            Direction::Prev => primary_diagnostics_before
12845                .iter()
12846                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12847                .rev()
12848                .next(),
12849            Direction::Next => primary_diagnostics_after
12850                .iter()
12851                .skip(
12852                    last_same_group_diagnostic_after
12853                        .map(|index| index + 1)
12854                        .unwrap_or(0),
12855                )
12856                .next(),
12857        };
12858
12859        // Cycle around to the start of the buffer, potentially moving back to the start of
12860        // the currently active diagnostic.
12861        let cycle_around = || match direction {
12862            Direction::Prev => primary_diagnostics_after
12863                .iter()
12864                .rev()
12865                .chain(primary_diagnostics_before.iter().rev())
12866                .next(),
12867            Direction::Next => primary_diagnostics_before
12868                .iter()
12869                .chain(primary_diagnostics_after.iter())
12870                .next(),
12871        };
12872
12873        if let Some((primary_range, group_id)) = next_primary_diagnostic
12874            .or_else(cycle_around)
12875            .map(|entry| (&entry.range, entry.diagnostic.group_id))
12876        {
12877            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12878                return;
12879            };
12880            self.activate_diagnostics(buffer_id, group_id, window, cx);
12881            if self.active_diagnostics.is_some() {
12882                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12883                    s.select(vec![Selection {
12884                        id: selection.id,
12885                        start: primary_range.start,
12886                        end: primary_range.start,
12887                        reversed: false,
12888                        goal: SelectionGoal::None,
12889                    }]);
12890                });
12891                self.refresh_inline_completion(false, true, window, cx);
12892            }
12893        }
12894    }
12895
12896    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12897        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12898        let snapshot = self.snapshot(window, cx);
12899        let selection = self.selections.newest::<Point>(cx);
12900        self.go_to_hunk_before_or_after_position(
12901            &snapshot,
12902            selection.head(),
12903            Direction::Next,
12904            window,
12905            cx,
12906        );
12907    }
12908
12909    pub fn go_to_hunk_before_or_after_position(
12910        &mut self,
12911        snapshot: &EditorSnapshot,
12912        position: Point,
12913        direction: Direction,
12914        window: &mut Window,
12915        cx: &mut Context<Editor>,
12916    ) {
12917        let row = if direction == Direction::Next {
12918            self.hunk_after_position(snapshot, position)
12919                .map(|hunk| hunk.row_range.start)
12920        } else {
12921            self.hunk_before_position(snapshot, position)
12922        };
12923
12924        if let Some(row) = row {
12925            let destination = Point::new(row.0, 0);
12926            let autoscroll = Autoscroll::center();
12927
12928            self.unfold_ranges(&[destination..destination], false, false, cx);
12929            self.change_selections(Some(autoscroll), window, cx, |s| {
12930                s.select_ranges([destination..destination]);
12931            });
12932        }
12933    }
12934
12935    fn hunk_after_position(
12936        &mut self,
12937        snapshot: &EditorSnapshot,
12938        position: Point,
12939    ) -> Option<MultiBufferDiffHunk> {
12940        snapshot
12941            .buffer_snapshot
12942            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12943            .find(|hunk| hunk.row_range.start.0 > position.row)
12944            .or_else(|| {
12945                snapshot
12946                    .buffer_snapshot
12947                    .diff_hunks_in_range(Point::zero()..position)
12948                    .find(|hunk| hunk.row_range.end.0 < position.row)
12949            })
12950    }
12951
12952    fn go_to_prev_hunk(
12953        &mut self,
12954        _: &GoToPreviousHunk,
12955        window: &mut Window,
12956        cx: &mut Context<Self>,
12957    ) {
12958        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12959        let snapshot = self.snapshot(window, cx);
12960        let selection = self.selections.newest::<Point>(cx);
12961        self.go_to_hunk_before_or_after_position(
12962            &snapshot,
12963            selection.head(),
12964            Direction::Prev,
12965            window,
12966            cx,
12967        );
12968    }
12969
12970    fn hunk_before_position(
12971        &mut self,
12972        snapshot: &EditorSnapshot,
12973        position: Point,
12974    ) -> Option<MultiBufferRow> {
12975        snapshot
12976            .buffer_snapshot
12977            .diff_hunk_before(position)
12978            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
12979    }
12980
12981    fn go_to_line<T: 'static>(
12982        &mut self,
12983        position: Anchor,
12984        highlight_color: Option<Hsla>,
12985        window: &mut Window,
12986        cx: &mut Context<Self>,
12987    ) {
12988        let snapshot = self.snapshot(window, cx).display_snapshot;
12989        let position = position.to_point(&snapshot.buffer_snapshot);
12990        let start = snapshot
12991            .buffer_snapshot
12992            .clip_point(Point::new(position.row, 0), Bias::Left);
12993        let end = start + Point::new(1, 0);
12994        let start = snapshot.buffer_snapshot.anchor_before(start);
12995        let end = snapshot.buffer_snapshot.anchor_before(end);
12996
12997        self.highlight_rows::<T>(
12998            start..end,
12999            highlight_color
13000                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13001            false,
13002            cx,
13003        );
13004        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13005    }
13006
13007    pub fn go_to_definition(
13008        &mut self,
13009        _: &GoToDefinition,
13010        window: &mut Window,
13011        cx: &mut Context<Self>,
13012    ) -> Task<Result<Navigated>> {
13013        let definition =
13014            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13015        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13016        cx.spawn_in(window, async move |editor, cx| {
13017            if definition.await? == Navigated::Yes {
13018                return Ok(Navigated::Yes);
13019            }
13020            match fallback_strategy {
13021                GoToDefinitionFallback::None => Ok(Navigated::No),
13022                GoToDefinitionFallback::FindAllReferences => {
13023                    match editor.update_in(cx, |editor, window, cx| {
13024                        editor.find_all_references(&FindAllReferences, window, cx)
13025                    })? {
13026                        Some(references) => references.await,
13027                        None => Ok(Navigated::No),
13028                    }
13029                }
13030            }
13031        })
13032    }
13033
13034    pub fn go_to_declaration(
13035        &mut self,
13036        _: &GoToDeclaration,
13037        window: &mut Window,
13038        cx: &mut Context<Self>,
13039    ) -> Task<Result<Navigated>> {
13040        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13041    }
13042
13043    pub fn go_to_declaration_split(
13044        &mut self,
13045        _: &GoToDeclaration,
13046        window: &mut Window,
13047        cx: &mut Context<Self>,
13048    ) -> Task<Result<Navigated>> {
13049        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13050    }
13051
13052    pub fn go_to_implementation(
13053        &mut self,
13054        _: &GoToImplementation,
13055        window: &mut Window,
13056        cx: &mut Context<Self>,
13057    ) -> Task<Result<Navigated>> {
13058        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13059    }
13060
13061    pub fn go_to_implementation_split(
13062        &mut self,
13063        _: &GoToImplementationSplit,
13064        window: &mut Window,
13065        cx: &mut Context<Self>,
13066    ) -> Task<Result<Navigated>> {
13067        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13068    }
13069
13070    pub fn go_to_type_definition(
13071        &mut self,
13072        _: &GoToTypeDefinition,
13073        window: &mut Window,
13074        cx: &mut Context<Self>,
13075    ) -> Task<Result<Navigated>> {
13076        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13077    }
13078
13079    pub fn go_to_definition_split(
13080        &mut self,
13081        _: &GoToDefinitionSplit,
13082        window: &mut Window,
13083        cx: &mut Context<Self>,
13084    ) -> Task<Result<Navigated>> {
13085        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13086    }
13087
13088    pub fn go_to_type_definition_split(
13089        &mut self,
13090        _: &GoToTypeDefinitionSplit,
13091        window: &mut Window,
13092        cx: &mut Context<Self>,
13093    ) -> Task<Result<Navigated>> {
13094        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13095    }
13096
13097    fn go_to_definition_of_kind(
13098        &mut self,
13099        kind: GotoDefinitionKind,
13100        split: bool,
13101        window: &mut Window,
13102        cx: &mut Context<Self>,
13103    ) -> Task<Result<Navigated>> {
13104        let Some(provider) = self.semantics_provider.clone() else {
13105            return Task::ready(Ok(Navigated::No));
13106        };
13107        let head = self.selections.newest::<usize>(cx).head();
13108        let buffer = self.buffer.read(cx);
13109        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13110            text_anchor
13111        } else {
13112            return Task::ready(Ok(Navigated::No));
13113        };
13114
13115        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13116            return Task::ready(Ok(Navigated::No));
13117        };
13118
13119        cx.spawn_in(window, async move |editor, cx| {
13120            let definitions = definitions.await?;
13121            let navigated = editor
13122                .update_in(cx, |editor, window, cx| {
13123                    editor.navigate_to_hover_links(
13124                        Some(kind),
13125                        definitions
13126                            .into_iter()
13127                            .filter(|location| {
13128                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13129                            })
13130                            .map(HoverLink::Text)
13131                            .collect::<Vec<_>>(),
13132                        split,
13133                        window,
13134                        cx,
13135                    )
13136                })?
13137                .await?;
13138            anyhow::Ok(navigated)
13139        })
13140    }
13141
13142    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13143        let selection = self.selections.newest_anchor();
13144        let head = selection.head();
13145        let tail = selection.tail();
13146
13147        let Some((buffer, start_position)) =
13148            self.buffer.read(cx).text_anchor_for_position(head, cx)
13149        else {
13150            return;
13151        };
13152
13153        let end_position = if head != tail {
13154            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13155                return;
13156            };
13157            Some(pos)
13158        } else {
13159            None
13160        };
13161
13162        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13163            let url = if let Some(end_pos) = end_position {
13164                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13165            } else {
13166                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13167            };
13168
13169            if let Some(url) = url {
13170                editor.update(cx, |_, cx| {
13171                    cx.open_url(&url);
13172                })
13173            } else {
13174                Ok(())
13175            }
13176        });
13177
13178        url_finder.detach();
13179    }
13180
13181    pub fn open_selected_filename(
13182        &mut self,
13183        _: &OpenSelectedFilename,
13184        window: &mut Window,
13185        cx: &mut Context<Self>,
13186    ) {
13187        let Some(workspace) = self.workspace() else {
13188            return;
13189        };
13190
13191        let position = self.selections.newest_anchor().head();
13192
13193        let Some((buffer, buffer_position)) =
13194            self.buffer.read(cx).text_anchor_for_position(position, cx)
13195        else {
13196            return;
13197        };
13198
13199        let project = self.project.clone();
13200
13201        cx.spawn_in(window, async move |_, cx| {
13202            let result = find_file(&buffer, project, buffer_position, cx).await;
13203
13204            if let Some((_, path)) = result {
13205                workspace
13206                    .update_in(cx, |workspace, window, cx| {
13207                        workspace.open_resolved_path(path, window, cx)
13208                    })?
13209                    .await?;
13210            }
13211            anyhow::Ok(())
13212        })
13213        .detach();
13214    }
13215
13216    pub(crate) fn navigate_to_hover_links(
13217        &mut self,
13218        kind: Option<GotoDefinitionKind>,
13219        mut definitions: Vec<HoverLink>,
13220        split: bool,
13221        window: &mut Window,
13222        cx: &mut Context<Editor>,
13223    ) -> Task<Result<Navigated>> {
13224        // If there is one definition, just open it directly
13225        if definitions.len() == 1 {
13226            let definition = definitions.pop().unwrap();
13227
13228            enum TargetTaskResult {
13229                Location(Option<Location>),
13230                AlreadyNavigated,
13231            }
13232
13233            let target_task = match definition {
13234                HoverLink::Text(link) => {
13235                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13236                }
13237                HoverLink::InlayHint(lsp_location, server_id) => {
13238                    let computation =
13239                        self.compute_target_location(lsp_location, server_id, window, cx);
13240                    cx.background_spawn(async move {
13241                        let location = computation.await?;
13242                        Ok(TargetTaskResult::Location(location))
13243                    })
13244                }
13245                HoverLink::Url(url) => {
13246                    cx.open_url(&url);
13247                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13248                }
13249                HoverLink::File(path) => {
13250                    if let Some(workspace) = self.workspace() {
13251                        cx.spawn_in(window, async move |_, cx| {
13252                            workspace
13253                                .update_in(cx, |workspace, window, cx| {
13254                                    workspace.open_resolved_path(path, window, cx)
13255                                })?
13256                                .await
13257                                .map(|_| TargetTaskResult::AlreadyNavigated)
13258                        })
13259                    } else {
13260                        Task::ready(Ok(TargetTaskResult::Location(None)))
13261                    }
13262                }
13263            };
13264            cx.spawn_in(window, async move |editor, cx| {
13265                let target = match target_task.await.context("target resolution task")? {
13266                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13267                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13268                    TargetTaskResult::Location(Some(target)) => target,
13269                };
13270
13271                editor.update_in(cx, |editor, window, cx| {
13272                    let Some(workspace) = editor.workspace() else {
13273                        return Navigated::No;
13274                    };
13275                    let pane = workspace.read(cx).active_pane().clone();
13276
13277                    let range = target.range.to_point(target.buffer.read(cx));
13278                    let range = editor.range_for_match(&range);
13279                    let range = collapse_multiline_range(range);
13280
13281                    if !split
13282                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13283                    {
13284                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13285                    } else {
13286                        window.defer(cx, move |window, cx| {
13287                            let target_editor: Entity<Self> =
13288                                workspace.update(cx, |workspace, cx| {
13289                                    let pane = if split {
13290                                        workspace.adjacent_pane(window, cx)
13291                                    } else {
13292                                        workspace.active_pane().clone()
13293                                    };
13294
13295                                    workspace.open_project_item(
13296                                        pane,
13297                                        target.buffer.clone(),
13298                                        true,
13299                                        true,
13300                                        window,
13301                                        cx,
13302                                    )
13303                                });
13304                            target_editor.update(cx, |target_editor, cx| {
13305                                // When selecting a definition in a different buffer, disable the nav history
13306                                // to avoid creating a history entry at the previous cursor location.
13307                                pane.update(cx, |pane, _| pane.disable_history());
13308                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13309                                pane.update(cx, |pane, _| pane.enable_history());
13310                            });
13311                        });
13312                    }
13313                    Navigated::Yes
13314                })
13315            })
13316        } else if !definitions.is_empty() {
13317            cx.spawn_in(window, async move |editor, cx| {
13318                let (title, location_tasks, workspace) = editor
13319                    .update_in(cx, |editor, window, cx| {
13320                        let tab_kind = match kind {
13321                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13322                            _ => "Definitions",
13323                        };
13324                        let title = definitions
13325                            .iter()
13326                            .find_map(|definition| match definition {
13327                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13328                                    let buffer = origin.buffer.read(cx);
13329                                    format!(
13330                                        "{} for {}",
13331                                        tab_kind,
13332                                        buffer
13333                                            .text_for_range(origin.range.clone())
13334                                            .collect::<String>()
13335                                    )
13336                                }),
13337                                HoverLink::InlayHint(_, _) => None,
13338                                HoverLink::Url(_) => None,
13339                                HoverLink::File(_) => None,
13340                            })
13341                            .unwrap_or(tab_kind.to_string());
13342                        let location_tasks = definitions
13343                            .into_iter()
13344                            .map(|definition| match definition {
13345                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13346                                HoverLink::InlayHint(lsp_location, server_id) => editor
13347                                    .compute_target_location(lsp_location, server_id, window, cx),
13348                                HoverLink::Url(_) => Task::ready(Ok(None)),
13349                                HoverLink::File(_) => Task::ready(Ok(None)),
13350                            })
13351                            .collect::<Vec<_>>();
13352                        (title, location_tasks, editor.workspace().clone())
13353                    })
13354                    .context("location tasks preparation")?;
13355
13356                let locations = future::join_all(location_tasks)
13357                    .await
13358                    .into_iter()
13359                    .filter_map(|location| location.transpose())
13360                    .collect::<Result<_>>()
13361                    .context("location tasks")?;
13362
13363                let Some(workspace) = workspace else {
13364                    return Ok(Navigated::No);
13365                };
13366                let opened = workspace
13367                    .update_in(cx, |workspace, window, cx| {
13368                        Self::open_locations_in_multibuffer(
13369                            workspace,
13370                            locations,
13371                            title,
13372                            split,
13373                            MultibufferSelectionMode::First,
13374                            window,
13375                            cx,
13376                        )
13377                    })
13378                    .ok();
13379
13380                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13381            })
13382        } else {
13383            Task::ready(Ok(Navigated::No))
13384        }
13385    }
13386
13387    fn compute_target_location(
13388        &self,
13389        lsp_location: lsp::Location,
13390        server_id: LanguageServerId,
13391        window: &mut Window,
13392        cx: &mut Context<Self>,
13393    ) -> Task<anyhow::Result<Option<Location>>> {
13394        let Some(project) = self.project.clone() else {
13395            return Task::ready(Ok(None));
13396        };
13397
13398        cx.spawn_in(window, async move |editor, cx| {
13399            let location_task = editor.update(cx, |_, cx| {
13400                project.update(cx, |project, cx| {
13401                    let language_server_name = project
13402                        .language_server_statuses(cx)
13403                        .find(|(id, _)| server_id == *id)
13404                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13405                    language_server_name.map(|language_server_name| {
13406                        project.open_local_buffer_via_lsp(
13407                            lsp_location.uri.clone(),
13408                            server_id,
13409                            language_server_name,
13410                            cx,
13411                        )
13412                    })
13413                })
13414            })?;
13415            let location = match location_task {
13416                Some(task) => Some({
13417                    let target_buffer_handle = task.await.context("open local buffer")?;
13418                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13419                        let target_start = target_buffer
13420                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13421                        let target_end = target_buffer
13422                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13423                        target_buffer.anchor_after(target_start)
13424                            ..target_buffer.anchor_before(target_end)
13425                    })?;
13426                    Location {
13427                        buffer: target_buffer_handle,
13428                        range,
13429                    }
13430                }),
13431                None => None,
13432            };
13433            Ok(location)
13434        })
13435    }
13436
13437    pub fn find_all_references(
13438        &mut self,
13439        _: &FindAllReferences,
13440        window: &mut Window,
13441        cx: &mut Context<Self>,
13442    ) -> Option<Task<Result<Navigated>>> {
13443        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13444
13445        let selection = self.selections.newest::<usize>(cx);
13446        let multi_buffer = self.buffer.read(cx);
13447        let head = selection.head();
13448
13449        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13450        let head_anchor = multi_buffer_snapshot.anchor_at(
13451            head,
13452            if head < selection.tail() {
13453                Bias::Right
13454            } else {
13455                Bias::Left
13456            },
13457        );
13458
13459        match self
13460            .find_all_references_task_sources
13461            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13462        {
13463            Ok(_) => {
13464                log::info!(
13465                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13466                );
13467                return None;
13468            }
13469            Err(i) => {
13470                self.find_all_references_task_sources.insert(i, head_anchor);
13471            }
13472        }
13473
13474        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13475        let workspace = self.workspace()?;
13476        let project = workspace.read(cx).project().clone();
13477        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13478        Some(cx.spawn_in(window, async move |editor, cx| {
13479            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13480                if let Ok(i) = editor
13481                    .find_all_references_task_sources
13482                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13483                {
13484                    editor.find_all_references_task_sources.remove(i);
13485                }
13486            });
13487
13488            let locations = references.await?;
13489            if locations.is_empty() {
13490                return anyhow::Ok(Navigated::No);
13491            }
13492
13493            workspace.update_in(cx, |workspace, window, cx| {
13494                let title = locations
13495                    .first()
13496                    .as_ref()
13497                    .map(|location| {
13498                        let buffer = location.buffer.read(cx);
13499                        format!(
13500                            "References to `{}`",
13501                            buffer
13502                                .text_for_range(location.range.clone())
13503                                .collect::<String>()
13504                        )
13505                    })
13506                    .unwrap();
13507                Self::open_locations_in_multibuffer(
13508                    workspace,
13509                    locations,
13510                    title,
13511                    false,
13512                    MultibufferSelectionMode::First,
13513                    window,
13514                    cx,
13515                );
13516                Navigated::Yes
13517            })
13518        }))
13519    }
13520
13521    /// Opens a multibuffer with the given project locations in it
13522    pub fn open_locations_in_multibuffer(
13523        workspace: &mut Workspace,
13524        mut locations: Vec<Location>,
13525        title: String,
13526        split: bool,
13527        multibuffer_selection_mode: MultibufferSelectionMode,
13528        window: &mut Window,
13529        cx: &mut Context<Workspace>,
13530    ) {
13531        // If there are multiple definitions, open them in a multibuffer
13532        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13533        let mut locations = locations.into_iter().peekable();
13534        let mut ranges = Vec::new();
13535        let capability = workspace.project().read(cx).capability();
13536
13537        let excerpt_buffer = cx.new(|cx| {
13538            let mut multibuffer = MultiBuffer::new(capability);
13539            while let Some(location) = locations.next() {
13540                let buffer = location.buffer.read(cx);
13541                let mut ranges_for_buffer = Vec::new();
13542                let range = location.range.to_offset(buffer);
13543                ranges_for_buffer.push(range.clone());
13544
13545                while let Some(next_location) = locations.peek() {
13546                    if next_location.buffer == location.buffer {
13547                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
13548                        locations.next();
13549                    } else {
13550                        break;
13551                    }
13552                }
13553
13554                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13555                ranges.extend(multibuffer.push_excerpts_with_context_lines(
13556                    location.buffer.clone(),
13557                    ranges_for_buffer,
13558                    DEFAULT_MULTIBUFFER_CONTEXT,
13559                    cx,
13560                ))
13561            }
13562
13563            multibuffer.with_title(title)
13564        });
13565
13566        let editor = cx.new(|cx| {
13567            Editor::for_multibuffer(
13568                excerpt_buffer,
13569                Some(workspace.project().clone()),
13570                window,
13571                cx,
13572            )
13573        });
13574        editor.update(cx, |editor, cx| {
13575            match multibuffer_selection_mode {
13576                MultibufferSelectionMode::First => {
13577                    if let Some(first_range) = ranges.first() {
13578                        editor.change_selections(None, window, cx, |selections| {
13579                            selections.clear_disjoint();
13580                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13581                        });
13582                    }
13583                    editor.highlight_background::<Self>(
13584                        &ranges,
13585                        |theme| theme.editor_highlighted_line_background,
13586                        cx,
13587                    );
13588                }
13589                MultibufferSelectionMode::All => {
13590                    editor.change_selections(None, window, cx, |selections| {
13591                        selections.clear_disjoint();
13592                        selections.select_anchor_ranges(ranges);
13593                    });
13594                }
13595            }
13596            editor.register_buffers_with_language_servers(cx);
13597        });
13598
13599        let item = Box::new(editor);
13600        let item_id = item.item_id();
13601
13602        if split {
13603            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13604        } else {
13605            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13606                let (preview_item_id, preview_item_idx) =
13607                    workspace.active_pane().update(cx, |pane, _| {
13608                        (pane.preview_item_id(), pane.preview_item_idx())
13609                    });
13610
13611                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13612
13613                if let Some(preview_item_id) = preview_item_id {
13614                    workspace.active_pane().update(cx, |pane, cx| {
13615                        pane.remove_item(preview_item_id, false, false, window, cx);
13616                    });
13617                }
13618            } else {
13619                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13620            }
13621        }
13622        workspace.active_pane().update(cx, |pane, cx| {
13623            pane.set_preview_item_id(Some(item_id), cx);
13624        });
13625    }
13626
13627    pub fn rename(
13628        &mut self,
13629        _: &Rename,
13630        window: &mut Window,
13631        cx: &mut Context<Self>,
13632    ) -> Option<Task<Result<()>>> {
13633        use language::ToOffset as _;
13634
13635        let provider = self.semantics_provider.clone()?;
13636        let selection = self.selections.newest_anchor().clone();
13637        let (cursor_buffer, cursor_buffer_position) = self
13638            .buffer
13639            .read(cx)
13640            .text_anchor_for_position(selection.head(), cx)?;
13641        let (tail_buffer, cursor_buffer_position_end) = self
13642            .buffer
13643            .read(cx)
13644            .text_anchor_for_position(selection.tail(), cx)?;
13645        if tail_buffer != cursor_buffer {
13646            return None;
13647        }
13648
13649        let snapshot = cursor_buffer.read(cx).snapshot();
13650        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13651        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13652        let prepare_rename = provider
13653            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13654            .unwrap_or_else(|| Task::ready(Ok(None)));
13655        drop(snapshot);
13656
13657        Some(cx.spawn_in(window, async move |this, cx| {
13658            let rename_range = if let Some(range) = prepare_rename.await? {
13659                Some(range)
13660            } else {
13661                this.update(cx, |this, cx| {
13662                    let buffer = this.buffer.read(cx).snapshot(cx);
13663                    let mut buffer_highlights = this
13664                        .document_highlights_for_position(selection.head(), &buffer)
13665                        .filter(|highlight| {
13666                            highlight.start.excerpt_id == selection.head().excerpt_id
13667                                && highlight.end.excerpt_id == selection.head().excerpt_id
13668                        });
13669                    buffer_highlights
13670                        .next()
13671                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13672                })?
13673            };
13674            if let Some(rename_range) = rename_range {
13675                this.update_in(cx, |this, window, cx| {
13676                    let snapshot = cursor_buffer.read(cx).snapshot();
13677                    let rename_buffer_range = rename_range.to_offset(&snapshot);
13678                    let cursor_offset_in_rename_range =
13679                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13680                    let cursor_offset_in_rename_range_end =
13681                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13682
13683                    this.take_rename(false, window, cx);
13684                    let buffer = this.buffer.read(cx).read(cx);
13685                    let cursor_offset = selection.head().to_offset(&buffer);
13686                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13687                    let rename_end = rename_start + rename_buffer_range.len();
13688                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13689                    let mut old_highlight_id = None;
13690                    let old_name: Arc<str> = buffer
13691                        .chunks(rename_start..rename_end, true)
13692                        .map(|chunk| {
13693                            if old_highlight_id.is_none() {
13694                                old_highlight_id = chunk.syntax_highlight_id;
13695                            }
13696                            chunk.text
13697                        })
13698                        .collect::<String>()
13699                        .into();
13700
13701                    drop(buffer);
13702
13703                    // Position the selection in the rename editor so that it matches the current selection.
13704                    this.show_local_selections = false;
13705                    let rename_editor = cx.new(|cx| {
13706                        let mut editor = Editor::single_line(window, cx);
13707                        editor.buffer.update(cx, |buffer, cx| {
13708                            buffer.edit([(0..0, old_name.clone())], None, cx)
13709                        });
13710                        let rename_selection_range = match cursor_offset_in_rename_range
13711                            .cmp(&cursor_offset_in_rename_range_end)
13712                        {
13713                            Ordering::Equal => {
13714                                editor.select_all(&SelectAll, window, cx);
13715                                return editor;
13716                            }
13717                            Ordering::Less => {
13718                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13719                            }
13720                            Ordering::Greater => {
13721                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13722                            }
13723                        };
13724                        if rename_selection_range.end > old_name.len() {
13725                            editor.select_all(&SelectAll, window, cx);
13726                        } else {
13727                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13728                                s.select_ranges([rename_selection_range]);
13729                            });
13730                        }
13731                        editor
13732                    });
13733                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13734                        if e == &EditorEvent::Focused {
13735                            cx.emit(EditorEvent::FocusedIn)
13736                        }
13737                    })
13738                    .detach();
13739
13740                    let write_highlights =
13741                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13742                    let read_highlights =
13743                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
13744                    let ranges = write_highlights
13745                        .iter()
13746                        .flat_map(|(_, ranges)| ranges.iter())
13747                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13748                        .cloned()
13749                        .collect();
13750
13751                    this.highlight_text::<Rename>(
13752                        ranges,
13753                        HighlightStyle {
13754                            fade_out: Some(0.6),
13755                            ..Default::default()
13756                        },
13757                        cx,
13758                    );
13759                    let rename_focus_handle = rename_editor.focus_handle(cx);
13760                    window.focus(&rename_focus_handle);
13761                    let block_id = this.insert_blocks(
13762                        [BlockProperties {
13763                            style: BlockStyle::Flex,
13764                            placement: BlockPlacement::Below(range.start),
13765                            height: 1,
13766                            render: Arc::new({
13767                                let rename_editor = rename_editor.clone();
13768                                move |cx: &mut BlockContext| {
13769                                    let mut text_style = cx.editor_style.text.clone();
13770                                    if let Some(highlight_style) = old_highlight_id
13771                                        .and_then(|h| h.style(&cx.editor_style.syntax))
13772                                    {
13773                                        text_style = text_style.highlight(highlight_style);
13774                                    }
13775                                    div()
13776                                        .block_mouse_down()
13777                                        .pl(cx.anchor_x)
13778                                        .child(EditorElement::new(
13779                                            &rename_editor,
13780                                            EditorStyle {
13781                                                background: cx.theme().system().transparent,
13782                                                local_player: cx.editor_style.local_player,
13783                                                text: text_style,
13784                                                scrollbar_width: cx.editor_style.scrollbar_width,
13785                                                syntax: cx.editor_style.syntax.clone(),
13786                                                status: cx.editor_style.status.clone(),
13787                                                inlay_hints_style: HighlightStyle {
13788                                                    font_weight: Some(FontWeight::BOLD),
13789                                                    ..make_inlay_hints_style(cx.app)
13790                                                },
13791                                                inline_completion_styles: make_suggestion_styles(
13792                                                    cx.app,
13793                                                ),
13794                                                ..EditorStyle::default()
13795                                            },
13796                                        ))
13797                                        .into_any_element()
13798                                }
13799                            }),
13800                            priority: 0,
13801                        }],
13802                        Some(Autoscroll::fit()),
13803                        cx,
13804                    )[0];
13805                    this.pending_rename = Some(RenameState {
13806                        range,
13807                        old_name,
13808                        editor: rename_editor,
13809                        block_id,
13810                    });
13811                })?;
13812            }
13813
13814            Ok(())
13815        }))
13816    }
13817
13818    pub fn confirm_rename(
13819        &mut self,
13820        _: &ConfirmRename,
13821        window: &mut Window,
13822        cx: &mut Context<Self>,
13823    ) -> Option<Task<Result<()>>> {
13824        let rename = self.take_rename(false, window, cx)?;
13825        let workspace = self.workspace()?.downgrade();
13826        let (buffer, start) = self
13827            .buffer
13828            .read(cx)
13829            .text_anchor_for_position(rename.range.start, cx)?;
13830        let (end_buffer, _) = self
13831            .buffer
13832            .read(cx)
13833            .text_anchor_for_position(rename.range.end, cx)?;
13834        if buffer != end_buffer {
13835            return None;
13836        }
13837
13838        let old_name = rename.old_name;
13839        let new_name = rename.editor.read(cx).text(cx);
13840
13841        let rename = self.semantics_provider.as_ref()?.perform_rename(
13842            &buffer,
13843            start,
13844            new_name.clone(),
13845            cx,
13846        )?;
13847
13848        Some(cx.spawn_in(window, async move |editor, cx| {
13849            let project_transaction = rename.await?;
13850            Self::open_project_transaction(
13851                &editor,
13852                workspace,
13853                project_transaction,
13854                format!("Rename: {}{}", old_name, new_name),
13855                cx,
13856            )
13857            .await?;
13858
13859            editor.update(cx, |editor, cx| {
13860                editor.refresh_document_highlights(cx);
13861            })?;
13862            Ok(())
13863        }))
13864    }
13865
13866    fn take_rename(
13867        &mut self,
13868        moving_cursor: bool,
13869        window: &mut Window,
13870        cx: &mut Context<Self>,
13871    ) -> Option<RenameState> {
13872        let rename = self.pending_rename.take()?;
13873        if rename.editor.focus_handle(cx).is_focused(window) {
13874            window.focus(&self.focus_handle);
13875        }
13876
13877        self.remove_blocks(
13878            [rename.block_id].into_iter().collect(),
13879            Some(Autoscroll::fit()),
13880            cx,
13881        );
13882        self.clear_highlights::<Rename>(cx);
13883        self.show_local_selections = true;
13884
13885        if moving_cursor {
13886            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13887                editor.selections.newest::<usize>(cx).head()
13888            });
13889
13890            // Update the selection to match the position of the selection inside
13891            // the rename editor.
13892            let snapshot = self.buffer.read(cx).read(cx);
13893            let rename_range = rename.range.to_offset(&snapshot);
13894            let cursor_in_editor = snapshot
13895                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13896                .min(rename_range.end);
13897            drop(snapshot);
13898
13899            self.change_selections(None, window, cx, |s| {
13900                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13901            });
13902        } else {
13903            self.refresh_document_highlights(cx);
13904        }
13905
13906        Some(rename)
13907    }
13908
13909    pub fn pending_rename(&self) -> Option<&RenameState> {
13910        self.pending_rename.as_ref()
13911    }
13912
13913    fn format(
13914        &mut self,
13915        _: &Format,
13916        window: &mut Window,
13917        cx: &mut Context<Self>,
13918    ) -> Option<Task<Result<()>>> {
13919        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13920
13921        let project = match &self.project {
13922            Some(project) => project.clone(),
13923            None => return None,
13924        };
13925
13926        Some(self.perform_format(
13927            project,
13928            FormatTrigger::Manual,
13929            FormatTarget::Buffers,
13930            window,
13931            cx,
13932        ))
13933    }
13934
13935    fn format_selections(
13936        &mut self,
13937        _: &FormatSelections,
13938        window: &mut Window,
13939        cx: &mut Context<Self>,
13940    ) -> Option<Task<Result<()>>> {
13941        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13942
13943        let project = match &self.project {
13944            Some(project) => project.clone(),
13945            None => return None,
13946        };
13947
13948        let ranges = self
13949            .selections
13950            .all_adjusted(cx)
13951            .into_iter()
13952            .map(|selection| selection.range())
13953            .collect_vec();
13954
13955        Some(self.perform_format(
13956            project,
13957            FormatTrigger::Manual,
13958            FormatTarget::Ranges(ranges),
13959            window,
13960            cx,
13961        ))
13962    }
13963
13964    fn perform_format(
13965        &mut self,
13966        project: Entity<Project>,
13967        trigger: FormatTrigger,
13968        target: FormatTarget,
13969        window: &mut Window,
13970        cx: &mut Context<Self>,
13971    ) -> Task<Result<()>> {
13972        let buffer = self.buffer.clone();
13973        let (buffers, target) = match target {
13974            FormatTarget::Buffers => {
13975                let mut buffers = buffer.read(cx).all_buffers();
13976                if trigger == FormatTrigger::Save {
13977                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
13978                }
13979                (buffers, LspFormatTarget::Buffers)
13980            }
13981            FormatTarget::Ranges(selection_ranges) => {
13982                let multi_buffer = buffer.read(cx);
13983                let snapshot = multi_buffer.read(cx);
13984                let mut buffers = HashSet::default();
13985                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
13986                    BTreeMap::new();
13987                for selection_range in selection_ranges {
13988                    for (buffer, buffer_range, _) in
13989                        snapshot.range_to_buffer_ranges(selection_range)
13990                    {
13991                        let buffer_id = buffer.remote_id();
13992                        let start = buffer.anchor_before(buffer_range.start);
13993                        let end = buffer.anchor_after(buffer_range.end);
13994                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
13995                        buffer_id_to_ranges
13996                            .entry(buffer_id)
13997                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
13998                            .or_insert_with(|| vec![start..end]);
13999                    }
14000                }
14001                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14002            }
14003        };
14004
14005        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14006        let format = project.update(cx, |project, cx| {
14007            project.format(buffers, target, true, trigger, cx)
14008        });
14009
14010        cx.spawn_in(window, async move |_, cx| {
14011            let transaction = futures::select_biased! {
14012                transaction = format.log_err().fuse() => transaction,
14013                () = timeout => {
14014                    log::warn!("timed out waiting for formatting");
14015                    None
14016                }
14017            };
14018
14019            buffer
14020                .update(cx, |buffer, cx| {
14021                    if let Some(transaction) = transaction {
14022                        if !buffer.is_singleton() {
14023                            buffer.push_transaction(&transaction.0, cx);
14024                        }
14025                    }
14026                    cx.notify();
14027                })
14028                .ok();
14029
14030            Ok(())
14031        })
14032    }
14033
14034    fn organize_imports(
14035        &mut self,
14036        _: &OrganizeImports,
14037        window: &mut Window,
14038        cx: &mut Context<Self>,
14039    ) -> Option<Task<Result<()>>> {
14040        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14041        let project = match &self.project {
14042            Some(project) => project.clone(),
14043            None => return None,
14044        };
14045        Some(self.perform_code_action_kind(
14046            project,
14047            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14048            window,
14049            cx,
14050        ))
14051    }
14052
14053    fn perform_code_action_kind(
14054        &mut self,
14055        project: Entity<Project>,
14056        kind: CodeActionKind,
14057        window: &mut Window,
14058        cx: &mut Context<Self>,
14059    ) -> Task<Result<()>> {
14060        let buffer = self.buffer.clone();
14061        let buffers = buffer.read(cx).all_buffers();
14062        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14063        let apply_action = project.update(cx, |project, cx| {
14064            project.apply_code_action_kind(buffers, kind, true, cx)
14065        });
14066        cx.spawn_in(window, async move |_, cx| {
14067            let transaction = futures::select_biased! {
14068                () = timeout => {
14069                    log::warn!("timed out waiting for executing code action");
14070                    None
14071                }
14072                transaction = apply_action.log_err().fuse() => transaction,
14073            };
14074            buffer
14075                .update(cx, |buffer, cx| {
14076                    // check if we need this
14077                    if let Some(transaction) = transaction {
14078                        if !buffer.is_singleton() {
14079                            buffer.push_transaction(&transaction.0, cx);
14080                        }
14081                    }
14082                    cx.notify();
14083                })
14084                .ok();
14085            Ok(())
14086        })
14087    }
14088
14089    fn restart_language_server(
14090        &mut self,
14091        _: &RestartLanguageServer,
14092        _: &mut Window,
14093        cx: &mut Context<Self>,
14094    ) {
14095        if let Some(project) = self.project.clone() {
14096            self.buffer.update(cx, |multi_buffer, cx| {
14097                project.update(cx, |project, cx| {
14098                    project.restart_language_servers_for_buffers(
14099                        multi_buffer.all_buffers().into_iter().collect(),
14100                        cx,
14101                    );
14102                });
14103            })
14104        }
14105    }
14106
14107    fn cancel_language_server_work(
14108        workspace: &mut Workspace,
14109        _: &actions::CancelLanguageServerWork,
14110        _: &mut Window,
14111        cx: &mut Context<Workspace>,
14112    ) {
14113        let project = workspace.project();
14114        let buffers = workspace
14115            .active_item(cx)
14116            .and_then(|item| item.act_as::<Editor>(cx))
14117            .map_or(HashSet::default(), |editor| {
14118                editor.read(cx).buffer.read(cx).all_buffers()
14119            });
14120        project.update(cx, |project, cx| {
14121            project.cancel_language_server_work_for_buffers(buffers, cx);
14122        });
14123    }
14124
14125    fn show_character_palette(
14126        &mut self,
14127        _: &ShowCharacterPalette,
14128        window: &mut Window,
14129        _: &mut Context<Self>,
14130    ) {
14131        window.show_character_palette();
14132    }
14133
14134    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14135        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14136            let buffer = self.buffer.read(cx).snapshot(cx);
14137            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14138            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14139            let is_valid = buffer
14140                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14141                .any(|entry| {
14142                    entry.diagnostic.is_primary
14143                        && !entry.range.is_empty()
14144                        && entry.range.start == primary_range_start
14145                        && entry.diagnostic.message == active_diagnostics.primary_message
14146                });
14147
14148            if is_valid != active_diagnostics.is_valid {
14149                active_diagnostics.is_valid = is_valid;
14150                if is_valid {
14151                    let mut new_styles = HashMap::default();
14152                    for (block_id, diagnostic) in &active_diagnostics.blocks {
14153                        new_styles.insert(
14154                            *block_id,
14155                            diagnostic_block_renderer(diagnostic.clone(), None, true),
14156                        );
14157                    }
14158                    self.display_map.update(cx, |display_map, _cx| {
14159                        display_map.replace_blocks(new_styles);
14160                    });
14161                } else {
14162                    self.dismiss_diagnostics(cx);
14163                }
14164            }
14165        }
14166    }
14167
14168    fn activate_diagnostics(
14169        &mut self,
14170        buffer_id: BufferId,
14171        group_id: usize,
14172        window: &mut Window,
14173        cx: &mut Context<Self>,
14174    ) {
14175        self.dismiss_diagnostics(cx);
14176        let snapshot = self.snapshot(window, cx);
14177        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14178            let buffer = self.buffer.read(cx).snapshot(cx);
14179
14180            let mut primary_range = None;
14181            let mut primary_message = None;
14182            let diagnostic_group = buffer
14183                .diagnostic_group(buffer_id, group_id)
14184                .filter_map(|entry| {
14185                    let start = entry.range.start;
14186                    let end = entry.range.end;
14187                    if snapshot.is_line_folded(MultiBufferRow(start.row))
14188                        && (start.row == end.row
14189                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
14190                    {
14191                        return None;
14192                    }
14193                    if entry.diagnostic.is_primary {
14194                        primary_range = Some(entry.range.clone());
14195                        primary_message = Some(entry.diagnostic.message.clone());
14196                    }
14197                    Some(entry)
14198                })
14199                .collect::<Vec<_>>();
14200            let primary_range = primary_range?;
14201            let primary_message = primary_message?;
14202
14203            let blocks = display_map
14204                .insert_blocks(
14205                    diagnostic_group.iter().map(|entry| {
14206                        let diagnostic = entry.diagnostic.clone();
14207                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14208                        BlockProperties {
14209                            style: BlockStyle::Fixed,
14210                            placement: BlockPlacement::Below(
14211                                buffer.anchor_after(entry.range.start),
14212                            ),
14213                            height: message_height,
14214                            render: diagnostic_block_renderer(diagnostic, None, true),
14215                            priority: 0,
14216                        }
14217                    }),
14218                    cx,
14219                )
14220                .into_iter()
14221                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14222                .collect();
14223
14224            Some(ActiveDiagnosticGroup {
14225                primary_range: buffer.anchor_before(primary_range.start)
14226                    ..buffer.anchor_after(primary_range.end),
14227                primary_message,
14228                group_id,
14229                blocks,
14230                is_valid: true,
14231            })
14232        });
14233    }
14234
14235    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14236        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14237            self.display_map.update(cx, |display_map, cx| {
14238                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14239            });
14240            cx.notify();
14241        }
14242    }
14243
14244    /// Disable inline diagnostics rendering for this editor.
14245    pub fn disable_inline_diagnostics(&mut self) {
14246        self.inline_diagnostics_enabled = false;
14247        self.inline_diagnostics_update = Task::ready(());
14248        self.inline_diagnostics.clear();
14249    }
14250
14251    pub fn inline_diagnostics_enabled(&self) -> bool {
14252        self.inline_diagnostics_enabled
14253    }
14254
14255    pub fn show_inline_diagnostics(&self) -> bool {
14256        self.show_inline_diagnostics
14257    }
14258
14259    pub fn toggle_inline_diagnostics(
14260        &mut self,
14261        _: &ToggleInlineDiagnostics,
14262        window: &mut Window,
14263        cx: &mut Context<Editor>,
14264    ) {
14265        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14266        self.refresh_inline_diagnostics(false, window, cx);
14267    }
14268
14269    fn refresh_inline_diagnostics(
14270        &mut self,
14271        debounce: bool,
14272        window: &mut Window,
14273        cx: &mut Context<Self>,
14274    ) {
14275        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14276            self.inline_diagnostics_update = Task::ready(());
14277            self.inline_diagnostics.clear();
14278            return;
14279        }
14280
14281        let debounce_ms = ProjectSettings::get_global(cx)
14282            .diagnostics
14283            .inline
14284            .update_debounce_ms;
14285        let debounce = if debounce && debounce_ms > 0 {
14286            Some(Duration::from_millis(debounce_ms))
14287        } else {
14288            None
14289        };
14290        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14291            if let Some(debounce) = debounce {
14292                cx.background_executor().timer(debounce).await;
14293            }
14294            let Some(snapshot) = editor
14295                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14296                .ok()
14297            else {
14298                return;
14299            };
14300
14301            let new_inline_diagnostics = cx
14302                .background_spawn(async move {
14303                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14304                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14305                        let message = diagnostic_entry
14306                            .diagnostic
14307                            .message
14308                            .split_once('\n')
14309                            .map(|(line, _)| line)
14310                            .map(SharedString::new)
14311                            .unwrap_or_else(|| {
14312                                SharedString::from(diagnostic_entry.diagnostic.message)
14313                            });
14314                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14315                        let (Ok(i) | Err(i)) = inline_diagnostics
14316                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14317                        inline_diagnostics.insert(
14318                            i,
14319                            (
14320                                start_anchor,
14321                                InlineDiagnostic {
14322                                    message,
14323                                    group_id: diagnostic_entry.diagnostic.group_id,
14324                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14325                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14326                                    severity: diagnostic_entry.diagnostic.severity,
14327                                },
14328                            ),
14329                        );
14330                    }
14331                    inline_diagnostics
14332                })
14333                .await;
14334
14335            editor
14336                .update(cx, |editor, cx| {
14337                    editor.inline_diagnostics = new_inline_diagnostics;
14338                    cx.notify();
14339                })
14340                .ok();
14341        });
14342    }
14343
14344    pub fn set_selections_from_remote(
14345        &mut self,
14346        selections: Vec<Selection<Anchor>>,
14347        pending_selection: Option<Selection<Anchor>>,
14348        window: &mut Window,
14349        cx: &mut Context<Self>,
14350    ) {
14351        let old_cursor_position = self.selections.newest_anchor().head();
14352        self.selections.change_with(cx, |s| {
14353            s.select_anchors(selections);
14354            if let Some(pending_selection) = pending_selection {
14355                s.set_pending(pending_selection, SelectMode::Character);
14356            } else {
14357                s.clear_pending();
14358            }
14359        });
14360        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14361    }
14362
14363    fn push_to_selection_history(&mut self) {
14364        self.selection_history.push(SelectionHistoryEntry {
14365            selections: self.selections.disjoint_anchors(),
14366            select_next_state: self.select_next_state.clone(),
14367            select_prev_state: self.select_prev_state.clone(),
14368            add_selections_state: self.add_selections_state.clone(),
14369        });
14370    }
14371
14372    pub fn transact(
14373        &mut self,
14374        window: &mut Window,
14375        cx: &mut Context<Self>,
14376        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14377    ) -> Option<TransactionId> {
14378        self.start_transaction_at(Instant::now(), window, cx);
14379        update(self, window, cx);
14380        self.end_transaction_at(Instant::now(), cx)
14381    }
14382
14383    pub fn start_transaction_at(
14384        &mut self,
14385        now: Instant,
14386        window: &mut Window,
14387        cx: &mut Context<Self>,
14388    ) {
14389        self.end_selection(window, cx);
14390        if let Some(tx_id) = self
14391            .buffer
14392            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14393        {
14394            self.selection_history
14395                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14396            cx.emit(EditorEvent::TransactionBegun {
14397                transaction_id: tx_id,
14398            })
14399        }
14400    }
14401
14402    pub fn end_transaction_at(
14403        &mut self,
14404        now: Instant,
14405        cx: &mut Context<Self>,
14406    ) -> Option<TransactionId> {
14407        if let Some(transaction_id) = self
14408            .buffer
14409            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14410        {
14411            if let Some((_, end_selections)) =
14412                self.selection_history.transaction_mut(transaction_id)
14413            {
14414                *end_selections = Some(self.selections.disjoint_anchors());
14415            } else {
14416                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14417            }
14418
14419            cx.emit(EditorEvent::Edited { transaction_id });
14420            Some(transaction_id)
14421        } else {
14422            None
14423        }
14424    }
14425
14426    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14427        if self.selection_mark_mode {
14428            self.change_selections(None, window, cx, |s| {
14429                s.move_with(|_, sel| {
14430                    sel.collapse_to(sel.head(), SelectionGoal::None);
14431                });
14432            })
14433        }
14434        self.selection_mark_mode = true;
14435        cx.notify();
14436    }
14437
14438    pub fn swap_selection_ends(
14439        &mut self,
14440        _: &actions::SwapSelectionEnds,
14441        window: &mut Window,
14442        cx: &mut Context<Self>,
14443    ) {
14444        self.change_selections(None, window, cx, |s| {
14445            s.move_with(|_, sel| {
14446                if sel.start != sel.end {
14447                    sel.reversed = !sel.reversed
14448                }
14449            });
14450        });
14451        self.request_autoscroll(Autoscroll::newest(), cx);
14452        cx.notify();
14453    }
14454
14455    pub fn toggle_fold(
14456        &mut self,
14457        _: &actions::ToggleFold,
14458        window: &mut Window,
14459        cx: &mut Context<Self>,
14460    ) {
14461        if self.is_singleton(cx) {
14462            let selection = self.selections.newest::<Point>(cx);
14463
14464            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14465            let range = if selection.is_empty() {
14466                let point = selection.head().to_display_point(&display_map);
14467                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14468                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14469                    .to_point(&display_map);
14470                start..end
14471            } else {
14472                selection.range()
14473            };
14474            if display_map.folds_in_range(range).next().is_some() {
14475                self.unfold_lines(&Default::default(), window, cx)
14476            } else {
14477                self.fold(&Default::default(), window, cx)
14478            }
14479        } else {
14480            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14481            let buffer_ids: HashSet<_> = self
14482                .selections
14483                .disjoint_anchor_ranges()
14484                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14485                .collect();
14486
14487            let should_unfold = buffer_ids
14488                .iter()
14489                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14490
14491            for buffer_id in buffer_ids {
14492                if should_unfold {
14493                    self.unfold_buffer(buffer_id, cx);
14494                } else {
14495                    self.fold_buffer(buffer_id, cx);
14496                }
14497            }
14498        }
14499    }
14500
14501    pub fn toggle_fold_recursive(
14502        &mut self,
14503        _: &actions::ToggleFoldRecursive,
14504        window: &mut Window,
14505        cx: &mut Context<Self>,
14506    ) {
14507        let selection = self.selections.newest::<Point>(cx);
14508
14509        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14510        let range = if selection.is_empty() {
14511            let point = selection.head().to_display_point(&display_map);
14512            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14513            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14514                .to_point(&display_map);
14515            start..end
14516        } else {
14517            selection.range()
14518        };
14519        if display_map.folds_in_range(range).next().is_some() {
14520            self.unfold_recursive(&Default::default(), window, cx)
14521        } else {
14522            self.fold_recursive(&Default::default(), window, cx)
14523        }
14524    }
14525
14526    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14527        if self.is_singleton(cx) {
14528            let mut to_fold = Vec::new();
14529            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14530            let selections = self.selections.all_adjusted(cx);
14531
14532            for selection in selections {
14533                let range = selection.range().sorted();
14534                let buffer_start_row = range.start.row;
14535
14536                if range.start.row != range.end.row {
14537                    let mut found = false;
14538                    let mut row = range.start.row;
14539                    while row <= range.end.row {
14540                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14541                        {
14542                            found = true;
14543                            row = crease.range().end.row + 1;
14544                            to_fold.push(crease);
14545                        } else {
14546                            row += 1
14547                        }
14548                    }
14549                    if found {
14550                        continue;
14551                    }
14552                }
14553
14554                for row in (0..=range.start.row).rev() {
14555                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14556                        if crease.range().end.row >= buffer_start_row {
14557                            to_fold.push(crease);
14558                            if row <= range.start.row {
14559                                break;
14560                            }
14561                        }
14562                    }
14563                }
14564            }
14565
14566            self.fold_creases(to_fold, true, window, cx);
14567        } else {
14568            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14569            let buffer_ids = self
14570                .selections
14571                .disjoint_anchor_ranges()
14572                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14573                .collect::<HashSet<_>>();
14574            for buffer_id in buffer_ids {
14575                self.fold_buffer(buffer_id, cx);
14576            }
14577        }
14578    }
14579
14580    fn fold_at_level(
14581        &mut self,
14582        fold_at: &FoldAtLevel,
14583        window: &mut Window,
14584        cx: &mut Context<Self>,
14585    ) {
14586        if !self.buffer.read(cx).is_singleton() {
14587            return;
14588        }
14589
14590        let fold_at_level = fold_at.0;
14591        let snapshot = self.buffer.read(cx).snapshot(cx);
14592        let mut to_fold = Vec::new();
14593        let mut stack = vec![(0, snapshot.max_row().0, 1)];
14594
14595        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14596            while start_row < end_row {
14597                match self
14598                    .snapshot(window, cx)
14599                    .crease_for_buffer_row(MultiBufferRow(start_row))
14600                {
14601                    Some(crease) => {
14602                        let nested_start_row = crease.range().start.row + 1;
14603                        let nested_end_row = crease.range().end.row;
14604
14605                        if current_level < fold_at_level {
14606                            stack.push((nested_start_row, nested_end_row, current_level + 1));
14607                        } else if current_level == fold_at_level {
14608                            to_fold.push(crease);
14609                        }
14610
14611                        start_row = nested_end_row + 1;
14612                    }
14613                    None => start_row += 1,
14614                }
14615            }
14616        }
14617
14618        self.fold_creases(to_fold, true, window, cx);
14619    }
14620
14621    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14622        if self.buffer.read(cx).is_singleton() {
14623            let mut fold_ranges = Vec::new();
14624            let snapshot = self.buffer.read(cx).snapshot(cx);
14625
14626            for row in 0..snapshot.max_row().0 {
14627                if let Some(foldable_range) = self
14628                    .snapshot(window, cx)
14629                    .crease_for_buffer_row(MultiBufferRow(row))
14630                {
14631                    fold_ranges.push(foldable_range);
14632                }
14633            }
14634
14635            self.fold_creases(fold_ranges, true, window, cx);
14636        } else {
14637            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14638                editor
14639                    .update_in(cx, |editor, _, cx| {
14640                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14641                            editor.fold_buffer(buffer_id, cx);
14642                        }
14643                    })
14644                    .ok();
14645            });
14646        }
14647    }
14648
14649    pub fn fold_function_bodies(
14650        &mut self,
14651        _: &actions::FoldFunctionBodies,
14652        window: &mut Window,
14653        cx: &mut Context<Self>,
14654    ) {
14655        let snapshot = self.buffer.read(cx).snapshot(cx);
14656
14657        let ranges = snapshot
14658            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14659            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14660            .collect::<Vec<_>>();
14661
14662        let creases = ranges
14663            .into_iter()
14664            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14665            .collect();
14666
14667        self.fold_creases(creases, true, window, cx);
14668    }
14669
14670    pub fn fold_recursive(
14671        &mut self,
14672        _: &actions::FoldRecursive,
14673        window: &mut Window,
14674        cx: &mut Context<Self>,
14675    ) {
14676        let mut to_fold = Vec::new();
14677        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14678        let selections = self.selections.all_adjusted(cx);
14679
14680        for selection in selections {
14681            let range = selection.range().sorted();
14682            let buffer_start_row = range.start.row;
14683
14684            if range.start.row != range.end.row {
14685                let mut found = false;
14686                for row in range.start.row..=range.end.row {
14687                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14688                        found = true;
14689                        to_fold.push(crease);
14690                    }
14691                }
14692                if found {
14693                    continue;
14694                }
14695            }
14696
14697            for row in (0..=range.start.row).rev() {
14698                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14699                    if crease.range().end.row >= buffer_start_row {
14700                        to_fold.push(crease);
14701                    } else {
14702                        break;
14703                    }
14704                }
14705            }
14706        }
14707
14708        self.fold_creases(to_fold, true, window, cx);
14709    }
14710
14711    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14712        let buffer_row = fold_at.buffer_row;
14713        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14714
14715        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14716            let autoscroll = self
14717                .selections
14718                .all::<Point>(cx)
14719                .iter()
14720                .any(|selection| crease.range().overlaps(&selection.range()));
14721
14722            self.fold_creases(vec![crease], autoscroll, window, cx);
14723        }
14724    }
14725
14726    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14727        if self.is_singleton(cx) {
14728            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14729            let buffer = &display_map.buffer_snapshot;
14730            let selections = self.selections.all::<Point>(cx);
14731            let ranges = selections
14732                .iter()
14733                .map(|s| {
14734                    let range = s.display_range(&display_map).sorted();
14735                    let mut start = range.start.to_point(&display_map);
14736                    let mut end = range.end.to_point(&display_map);
14737                    start.column = 0;
14738                    end.column = buffer.line_len(MultiBufferRow(end.row));
14739                    start..end
14740                })
14741                .collect::<Vec<_>>();
14742
14743            self.unfold_ranges(&ranges, true, true, cx);
14744        } else {
14745            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14746            let buffer_ids = self
14747                .selections
14748                .disjoint_anchor_ranges()
14749                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14750                .collect::<HashSet<_>>();
14751            for buffer_id in buffer_ids {
14752                self.unfold_buffer(buffer_id, cx);
14753            }
14754        }
14755    }
14756
14757    pub fn unfold_recursive(
14758        &mut self,
14759        _: &UnfoldRecursive,
14760        _window: &mut Window,
14761        cx: &mut Context<Self>,
14762    ) {
14763        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14764        let selections = self.selections.all::<Point>(cx);
14765        let ranges = selections
14766            .iter()
14767            .map(|s| {
14768                let mut range = s.display_range(&display_map).sorted();
14769                *range.start.column_mut() = 0;
14770                *range.end.column_mut() = display_map.line_len(range.end.row());
14771                let start = range.start.to_point(&display_map);
14772                let end = range.end.to_point(&display_map);
14773                start..end
14774            })
14775            .collect::<Vec<_>>();
14776
14777        self.unfold_ranges(&ranges, true, true, cx);
14778    }
14779
14780    pub fn unfold_at(
14781        &mut self,
14782        unfold_at: &UnfoldAt,
14783        _window: &mut Window,
14784        cx: &mut Context<Self>,
14785    ) {
14786        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14787
14788        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14789            ..Point::new(
14790                unfold_at.buffer_row.0,
14791                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14792            );
14793
14794        let autoscroll = self
14795            .selections
14796            .all::<Point>(cx)
14797            .iter()
14798            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14799
14800        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14801    }
14802
14803    pub fn unfold_all(
14804        &mut self,
14805        _: &actions::UnfoldAll,
14806        _window: &mut Window,
14807        cx: &mut Context<Self>,
14808    ) {
14809        if self.buffer.read(cx).is_singleton() {
14810            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14811            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14812        } else {
14813            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14814                editor
14815                    .update(cx, |editor, cx| {
14816                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14817                            editor.unfold_buffer(buffer_id, cx);
14818                        }
14819                    })
14820                    .ok();
14821            });
14822        }
14823    }
14824
14825    pub fn fold_selected_ranges(
14826        &mut self,
14827        _: &FoldSelectedRanges,
14828        window: &mut Window,
14829        cx: &mut Context<Self>,
14830    ) {
14831        let selections = self.selections.all_adjusted(cx);
14832        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14833        let ranges = selections
14834            .into_iter()
14835            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
14836            .collect::<Vec<_>>();
14837        self.fold_creases(ranges, true, window, cx);
14838    }
14839
14840    pub fn fold_ranges<T: ToOffset + Clone>(
14841        &mut self,
14842        ranges: Vec<Range<T>>,
14843        auto_scroll: bool,
14844        window: &mut Window,
14845        cx: &mut Context<Self>,
14846    ) {
14847        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14848        let ranges = ranges
14849            .into_iter()
14850            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14851            .collect::<Vec<_>>();
14852        self.fold_creases(ranges, auto_scroll, window, cx);
14853    }
14854
14855    pub fn fold_creases<T: ToOffset + Clone>(
14856        &mut self,
14857        creases: Vec<Crease<T>>,
14858        auto_scroll: bool,
14859        window: &mut Window,
14860        cx: &mut Context<Self>,
14861    ) {
14862        if creases.is_empty() {
14863            return;
14864        }
14865
14866        let mut buffers_affected = HashSet::default();
14867        let multi_buffer = self.buffer().read(cx);
14868        for crease in &creases {
14869            if let Some((_, buffer, _)) =
14870                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14871            {
14872                buffers_affected.insert(buffer.read(cx).remote_id());
14873            };
14874        }
14875
14876        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14877
14878        if auto_scroll {
14879            self.request_autoscroll(Autoscroll::fit(), cx);
14880        }
14881
14882        cx.notify();
14883
14884        if let Some(active_diagnostics) = self.active_diagnostics.take() {
14885            // Clear diagnostics block when folding a range that contains it.
14886            let snapshot = self.snapshot(window, cx);
14887            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14888                drop(snapshot);
14889                self.active_diagnostics = Some(active_diagnostics);
14890                self.dismiss_diagnostics(cx);
14891            } else {
14892                self.active_diagnostics = Some(active_diagnostics);
14893            }
14894        }
14895
14896        self.scrollbar_marker_state.dirty = true;
14897        self.folds_did_change(cx);
14898    }
14899
14900    /// Removes any folds whose ranges intersect any of the given ranges.
14901    pub fn unfold_ranges<T: ToOffset + Clone>(
14902        &mut self,
14903        ranges: &[Range<T>],
14904        inclusive: bool,
14905        auto_scroll: bool,
14906        cx: &mut Context<Self>,
14907    ) {
14908        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14909            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14910        });
14911        self.folds_did_change(cx);
14912    }
14913
14914    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14915        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14916            return;
14917        }
14918        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14919        self.display_map.update(cx, |display_map, cx| {
14920            display_map.fold_buffers([buffer_id], cx)
14921        });
14922        cx.emit(EditorEvent::BufferFoldToggled {
14923            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14924            folded: true,
14925        });
14926        cx.notify();
14927    }
14928
14929    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14930        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14931            return;
14932        }
14933        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14934        self.display_map.update(cx, |display_map, cx| {
14935            display_map.unfold_buffers([buffer_id], cx);
14936        });
14937        cx.emit(EditorEvent::BufferFoldToggled {
14938            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14939            folded: false,
14940        });
14941        cx.notify();
14942    }
14943
14944    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14945        self.display_map.read(cx).is_buffer_folded(buffer)
14946    }
14947
14948    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14949        self.display_map.read(cx).folded_buffers()
14950    }
14951
14952    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14953        self.display_map.update(cx, |display_map, cx| {
14954            display_map.disable_header_for_buffer(buffer_id, cx);
14955        });
14956        cx.notify();
14957    }
14958
14959    /// Removes any folds with the given ranges.
14960    pub fn remove_folds_with_type<T: ToOffset + Clone>(
14961        &mut self,
14962        ranges: &[Range<T>],
14963        type_id: TypeId,
14964        auto_scroll: bool,
14965        cx: &mut Context<Self>,
14966    ) {
14967        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14968            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
14969        });
14970        self.folds_did_change(cx);
14971    }
14972
14973    fn remove_folds_with<T: ToOffset + Clone>(
14974        &mut self,
14975        ranges: &[Range<T>],
14976        auto_scroll: bool,
14977        cx: &mut Context<Self>,
14978        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
14979    ) {
14980        if ranges.is_empty() {
14981            return;
14982        }
14983
14984        let mut buffers_affected = HashSet::default();
14985        let multi_buffer = self.buffer().read(cx);
14986        for range in ranges {
14987            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
14988                buffers_affected.insert(buffer.read(cx).remote_id());
14989            };
14990        }
14991
14992        self.display_map.update(cx, update);
14993
14994        if auto_scroll {
14995            self.request_autoscroll(Autoscroll::fit(), cx);
14996        }
14997
14998        cx.notify();
14999        self.scrollbar_marker_state.dirty = true;
15000        self.active_indent_guides_state.dirty = true;
15001    }
15002
15003    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15004        self.display_map.read(cx).fold_placeholder.clone()
15005    }
15006
15007    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15008        self.buffer.update(cx, |buffer, cx| {
15009            buffer.set_all_diff_hunks_expanded(cx);
15010        });
15011    }
15012
15013    pub fn expand_all_diff_hunks(
15014        &mut self,
15015        _: &ExpandAllDiffHunks,
15016        _window: &mut Window,
15017        cx: &mut Context<Self>,
15018    ) {
15019        self.buffer.update(cx, |buffer, cx| {
15020            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15021        });
15022    }
15023
15024    pub fn toggle_selected_diff_hunks(
15025        &mut self,
15026        _: &ToggleSelectedDiffHunks,
15027        _window: &mut Window,
15028        cx: &mut Context<Self>,
15029    ) {
15030        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15031        self.toggle_diff_hunks_in_ranges(ranges, cx);
15032    }
15033
15034    pub fn diff_hunks_in_ranges<'a>(
15035        &'a self,
15036        ranges: &'a [Range<Anchor>],
15037        buffer: &'a MultiBufferSnapshot,
15038    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15039        ranges.iter().flat_map(move |range| {
15040            let end_excerpt_id = range.end.excerpt_id;
15041            let range = range.to_point(buffer);
15042            let mut peek_end = range.end;
15043            if range.end.row < buffer.max_row().0 {
15044                peek_end = Point::new(range.end.row + 1, 0);
15045            }
15046            buffer
15047                .diff_hunks_in_range(range.start..peek_end)
15048                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15049        })
15050    }
15051
15052    pub fn has_stageable_diff_hunks_in_ranges(
15053        &self,
15054        ranges: &[Range<Anchor>],
15055        snapshot: &MultiBufferSnapshot,
15056    ) -> bool {
15057        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15058        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15059    }
15060
15061    pub fn toggle_staged_selected_diff_hunks(
15062        &mut self,
15063        _: &::git::ToggleStaged,
15064        _: &mut Window,
15065        cx: &mut Context<Self>,
15066    ) {
15067        let snapshot = self.buffer.read(cx).snapshot(cx);
15068        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15069        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15070        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15071    }
15072
15073    pub fn set_render_diff_hunk_controls(
15074        &mut self,
15075        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15076        cx: &mut Context<Self>,
15077    ) {
15078        self.render_diff_hunk_controls = render_diff_hunk_controls;
15079        cx.notify();
15080    }
15081
15082    pub fn stage_and_next(
15083        &mut self,
15084        _: &::git::StageAndNext,
15085        window: &mut Window,
15086        cx: &mut Context<Self>,
15087    ) {
15088        self.do_stage_or_unstage_and_next(true, window, cx);
15089    }
15090
15091    pub fn unstage_and_next(
15092        &mut self,
15093        _: &::git::UnstageAndNext,
15094        window: &mut Window,
15095        cx: &mut Context<Self>,
15096    ) {
15097        self.do_stage_or_unstage_and_next(false, window, cx);
15098    }
15099
15100    pub fn stage_or_unstage_diff_hunks(
15101        &mut self,
15102        stage: bool,
15103        ranges: Vec<Range<Anchor>>,
15104        cx: &mut Context<Self>,
15105    ) {
15106        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15107        cx.spawn(async move |this, cx| {
15108            task.await?;
15109            this.update(cx, |this, cx| {
15110                let snapshot = this.buffer.read(cx).snapshot(cx);
15111                let chunk_by = this
15112                    .diff_hunks_in_ranges(&ranges, &snapshot)
15113                    .chunk_by(|hunk| hunk.buffer_id);
15114                for (buffer_id, hunks) in &chunk_by {
15115                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15116                }
15117            })
15118        })
15119        .detach_and_log_err(cx);
15120    }
15121
15122    fn save_buffers_for_ranges_if_needed(
15123        &mut self,
15124        ranges: &[Range<Anchor>],
15125        cx: &mut Context<Editor>,
15126    ) -> Task<Result<()>> {
15127        let multibuffer = self.buffer.read(cx);
15128        let snapshot = multibuffer.read(cx);
15129        let buffer_ids: HashSet<_> = ranges
15130            .iter()
15131            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15132            .collect();
15133        drop(snapshot);
15134
15135        let mut buffers = HashSet::default();
15136        for buffer_id in buffer_ids {
15137            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15138                let buffer = buffer_entity.read(cx);
15139                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15140                {
15141                    buffers.insert(buffer_entity);
15142                }
15143            }
15144        }
15145
15146        if let Some(project) = &self.project {
15147            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15148        } else {
15149            Task::ready(Ok(()))
15150        }
15151    }
15152
15153    fn do_stage_or_unstage_and_next(
15154        &mut self,
15155        stage: bool,
15156        window: &mut Window,
15157        cx: &mut Context<Self>,
15158    ) {
15159        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15160
15161        if ranges.iter().any(|range| range.start != range.end) {
15162            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15163            return;
15164        }
15165
15166        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15167        let snapshot = self.snapshot(window, cx);
15168        let position = self.selections.newest::<Point>(cx).head();
15169        let mut row = snapshot
15170            .buffer_snapshot
15171            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15172            .find(|hunk| hunk.row_range.start.0 > position.row)
15173            .map(|hunk| hunk.row_range.start);
15174
15175        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15176        // Outside of the project diff editor, wrap around to the beginning.
15177        if !all_diff_hunks_expanded {
15178            row = row.or_else(|| {
15179                snapshot
15180                    .buffer_snapshot
15181                    .diff_hunks_in_range(Point::zero()..position)
15182                    .find(|hunk| hunk.row_range.end.0 < position.row)
15183                    .map(|hunk| hunk.row_range.start)
15184            });
15185        }
15186
15187        if let Some(row) = row {
15188            let destination = Point::new(row.0, 0);
15189            let autoscroll = Autoscroll::center();
15190
15191            self.unfold_ranges(&[destination..destination], false, false, cx);
15192            self.change_selections(Some(autoscroll), window, cx, |s| {
15193                s.select_ranges([destination..destination]);
15194            });
15195        }
15196    }
15197
15198    fn do_stage_or_unstage(
15199        &self,
15200        stage: bool,
15201        buffer_id: BufferId,
15202        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15203        cx: &mut App,
15204    ) -> Option<()> {
15205        let project = self.project.as_ref()?;
15206        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15207        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15208        let buffer_snapshot = buffer.read(cx).snapshot();
15209        let file_exists = buffer_snapshot
15210            .file()
15211            .is_some_and(|file| file.disk_state().exists());
15212        diff.update(cx, |diff, cx| {
15213            diff.stage_or_unstage_hunks(
15214                stage,
15215                &hunks
15216                    .map(|hunk| buffer_diff::DiffHunk {
15217                        buffer_range: hunk.buffer_range,
15218                        diff_base_byte_range: hunk.diff_base_byte_range,
15219                        secondary_status: hunk.secondary_status,
15220                        range: Point::zero()..Point::zero(), // unused
15221                    })
15222                    .collect::<Vec<_>>(),
15223                &buffer_snapshot,
15224                file_exists,
15225                cx,
15226            )
15227        });
15228        None
15229    }
15230
15231    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15232        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15233        self.buffer
15234            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15235    }
15236
15237    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15238        self.buffer.update(cx, |buffer, cx| {
15239            let ranges = vec![Anchor::min()..Anchor::max()];
15240            if !buffer.all_diff_hunks_expanded()
15241                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15242            {
15243                buffer.collapse_diff_hunks(ranges, cx);
15244                true
15245            } else {
15246                false
15247            }
15248        })
15249    }
15250
15251    fn toggle_diff_hunks_in_ranges(
15252        &mut self,
15253        ranges: Vec<Range<Anchor>>,
15254        cx: &mut Context<Editor>,
15255    ) {
15256        self.buffer.update(cx, |buffer, cx| {
15257            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15258            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15259        })
15260    }
15261
15262    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15263        self.buffer.update(cx, |buffer, cx| {
15264            let snapshot = buffer.snapshot(cx);
15265            let excerpt_id = range.end.excerpt_id;
15266            let point_range = range.to_point(&snapshot);
15267            let expand = !buffer.single_hunk_is_expanded(range, cx);
15268            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15269        })
15270    }
15271
15272    pub(crate) fn apply_all_diff_hunks(
15273        &mut self,
15274        _: &ApplyAllDiffHunks,
15275        window: &mut Window,
15276        cx: &mut Context<Self>,
15277    ) {
15278        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15279
15280        let buffers = self.buffer.read(cx).all_buffers();
15281        for branch_buffer in buffers {
15282            branch_buffer.update(cx, |branch_buffer, cx| {
15283                branch_buffer.merge_into_base(Vec::new(), cx);
15284            });
15285        }
15286
15287        if let Some(project) = self.project.clone() {
15288            self.save(true, project, window, cx).detach_and_log_err(cx);
15289        }
15290    }
15291
15292    pub(crate) fn apply_selected_diff_hunks(
15293        &mut self,
15294        _: &ApplyDiffHunk,
15295        window: &mut Window,
15296        cx: &mut Context<Self>,
15297    ) {
15298        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15299        let snapshot = self.snapshot(window, cx);
15300        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15301        let mut ranges_by_buffer = HashMap::default();
15302        self.transact(window, cx, |editor, _window, cx| {
15303            for hunk in hunks {
15304                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15305                    ranges_by_buffer
15306                        .entry(buffer.clone())
15307                        .or_insert_with(Vec::new)
15308                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15309                }
15310            }
15311
15312            for (buffer, ranges) in ranges_by_buffer {
15313                buffer.update(cx, |buffer, cx| {
15314                    buffer.merge_into_base(ranges, cx);
15315                });
15316            }
15317        });
15318
15319        if let Some(project) = self.project.clone() {
15320            self.save(true, project, window, cx).detach_and_log_err(cx);
15321        }
15322    }
15323
15324    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15325        if hovered != self.gutter_hovered {
15326            self.gutter_hovered = hovered;
15327            cx.notify();
15328        }
15329    }
15330
15331    pub fn insert_blocks(
15332        &mut self,
15333        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15334        autoscroll: Option<Autoscroll>,
15335        cx: &mut Context<Self>,
15336    ) -> Vec<CustomBlockId> {
15337        let blocks = self
15338            .display_map
15339            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15340        if let Some(autoscroll) = autoscroll {
15341            self.request_autoscroll(autoscroll, cx);
15342        }
15343        cx.notify();
15344        blocks
15345    }
15346
15347    pub fn resize_blocks(
15348        &mut self,
15349        heights: HashMap<CustomBlockId, u32>,
15350        autoscroll: Option<Autoscroll>,
15351        cx: &mut Context<Self>,
15352    ) {
15353        self.display_map
15354            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15355        if let Some(autoscroll) = autoscroll {
15356            self.request_autoscroll(autoscroll, cx);
15357        }
15358        cx.notify();
15359    }
15360
15361    pub fn replace_blocks(
15362        &mut self,
15363        renderers: HashMap<CustomBlockId, RenderBlock>,
15364        autoscroll: Option<Autoscroll>,
15365        cx: &mut Context<Self>,
15366    ) {
15367        self.display_map
15368            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15369        if let Some(autoscroll) = autoscroll {
15370            self.request_autoscroll(autoscroll, cx);
15371        }
15372        cx.notify();
15373    }
15374
15375    pub fn remove_blocks(
15376        &mut self,
15377        block_ids: HashSet<CustomBlockId>,
15378        autoscroll: Option<Autoscroll>,
15379        cx: &mut Context<Self>,
15380    ) {
15381        self.display_map.update(cx, |display_map, cx| {
15382            display_map.remove_blocks(block_ids, cx)
15383        });
15384        if let Some(autoscroll) = autoscroll {
15385            self.request_autoscroll(autoscroll, cx);
15386        }
15387        cx.notify();
15388    }
15389
15390    pub fn row_for_block(
15391        &self,
15392        block_id: CustomBlockId,
15393        cx: &mut Context<Self>,
15394    ) -> Option<DisplayRow> {
15395        self.display_map
15396            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15397    }
15398
15399    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15400        self.focused_block = Some(focused_block);
15401    }
15402
15403    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15404        self.focused_block.take()
15405    }
15406
15407    pub fn insert_creases(
15408        &mut self,
15409        creases: impl IntoIterator<Item = Crease<Anchor>>,
15410        cx: &mut Context<Self>,
15411    ) -> Vec<CreaseId> {
15412        self.display_map
15413            .update(cx, |map, cx| map.insert_creases(creases, cx))
15414    }
15415
15416    pub fn remove_creases(
15417        &mut self,
15418        ids: impl IntoIterator<Item = CreaseId>,
15419        cx: &mut Context<Self>,
15420    ) {
15421        self.display_map
15422            .update(cx, |map, cx| map.remove_creases(ids, cx));
15423    }
15424
15425    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15426        self.display_map
15427            .update(cx, |map, cx| map.snapshot(cx))
15428            .longest_row()
15429    }
15430
15431    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15432        self.display_map
15433            .update(cx, |map, cx| map.snapshot(cx))
15434            .max_point()
15435    }
15436
15437    pub fn text(&self, cx: &App) -> String {
15438        self.buffer.read(cx).read(cx).text()
15439    }
15440
15441    pub fn is_empty(&self, cx: &App) -> bool {
15442        self.buffer.read(cx).read(cx).is_empty()
15443    }
15444
15445    pub fn text_option(&self, cx: &App) -> Option<String> {
15446        let text = self.text(cx);
15447        let text = text.trim();
15448
15449        if text.is_empty() {
15450            return None;
15451        }
15452
15453        Some(text.to_string())
15454    }
15455
15456    pub fn set_text(
15457        &mut self,
15458        text: impl Into<Arc<str>>,
15459        window: &mut Window,
15460        cx: &mut Context<Self>,
15461    ) {
15462        self.transact(window, cx, |this, _, cx| {
15463            this.buffer
15464                .read(cx)
15465                .as_singleton()
15466                .expect("you can only call set_text on editors for singleton buffers")
15467                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15468        });
15469    }
15470
15471    pub fn display_text(&self, cx: &mut App) -> String {
15472        self.display_map
15473            .update(cx, |map, cx| map.snapshot(cx))
15474            .text()
15475    }
15476
15477    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15478        let mut wrap_guides = smallvec::smallvec![];
15479
15480        if self.show_wrap_guides == Some(false) {
15481            return wrap_guides;
15482        }
15483
15484        let settings = self.buffer.read(cx).language_settings(cx);
15485        if settings.show_wrap_guides {
15486            match self.soft_wrap_mode(cx) {
15487                SoftWrap::Column(soft_wrap) => {
15488                    wrap_guides.push((soft_wrap as usize, true));
15489                }
15490                SoftWrap::Bounded(soft_wrap) => {
15491                    wrap_guides.push((soft_wrap as usize, true));
15492                }
15493                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15494            }
15495            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15496        }
15497
15498        wrap_guides
15499    }
15500
15501    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15502        let settings = self.buffer.read(cx).language_settings(cx);
15503        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15504        match mode {
15505            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15506                SoftWrap::None
15507            }
15508            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15509            language_settings::SoftWrap::PreferredLineLength => {
15510                SoftWrap::Column(settings.preferred_line_length)
15511            }
15512            language_settings::SoftWrap::Bounded => {
15513                SoftWrap::Bounded(settings.preferred_line_length)
15514            }
15515        }
15516    }
15517
15518    pub fn set_soft_wrap_mode(
15519        &mut self,
15520        mode: language_settings::SoftWrap,
15521
15522        cx: &mut Context<Self>,
15523    ) {
15524        self.soft_wrap_mode_override = Some(mode);
15525        cx.notify();
15526    }
15527
15528    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15529        self.hard_wrap = hard_wrap;
15530        cx.notify();
15531    }
15532
15533    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15534        self.text_style_refinement = Some(style);
15535    }
15536
15537    /// called by the Element so we know what style we were most recently rendered with.
15538    pub(crate) fn set_style(
15539        &mut self,
15540        style: EditorStyle,
15541        window: &mut Window,
15542        cx: &mut Context<Self>,
15543    ) {
15544        let rem_size = window.rem_size();
15545        self.display_map.update(cx, |map, cx| {
15546            map.set_font(
15547                style.text.font(),
15548                style.text.font_size.to_pixels(rem_size),
15549                cx,
15550            )
15551        });
15552        self.style = Some(style);
15553    }
15554
15555    pub fn style(&self) -> Option<&EditorStyle> {
15556        self.style.as_ref()
15557    }
15558
15559    // Called by the element. This method is not designed to be called outside of the editor
15560    // element's layout code because it does not notify when rewrapping is computed synchronously.
15561    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15562        self.display_map
15563            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15564    }
15565
15566    pub fn set_soft_wrap(&mut self) {
15567        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15568    }
15569
15570    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15571        if self.soft_wrap_mode_override.is_some() {
15572            self.soft_wrap_mode_override.take();
15573        } else {
15574            let soft_wrap = match self.soft_wrap_mode(cx) {
15575                SoftWrap::GitDiff => return,
15576                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15577                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15578                    language_settings::SoftWrap::None
15579                }
15580            };
15581            self.soft_wrap_mode_override = Some(soft_wrap);
15582        }
15583        cx.notify();
15584    }
15585
15586    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15587        let Some(workspace) = self.workspace() else {
15588            return;
15589        };
15590        let fs = workspace.read(cx).app_state().fs.clone();
15591        let current_show = TabBarSettings::get_global(cx).show;
15592        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15593            setting.show = Some(!current_show);
15594        });
15595    }
15596
15597    pub fn toggle_indent_guides(
15598        &mut self,
15599        _: &ToggleIndentGuides,
15600        _: &mut Window,
15601        cx: &mut Context<Self>,
15602    ) {
15603        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15604            self.buffer
15605                .read(cx)
15606                .language_settings(cx)
15607                .indent_guides
15608                .enabled
15609        });
15610        self.show_indent_guides = Some(!currently_enabled);
15611        cx.notify();
15612    }
15613
15614    fn should_show_indent_guides(&self) -> Option<bool> {
15615        self.show_indent_guides
15616    }
15617
15618    pub fn toggle_line_numbers(
15619        &mut self,
15620        _: &ToggleLineNumbers,
15621        _: &mut Window,
15622        cx: &mut Context<Self>,
15623    ) {
15624        let mut editor_settings = EditorSettings::get_global(cx).clone();
15625        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15626        EditorSettings::override_global(editor_settings, cx);
15627    }
15628
15629    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15630        if let Some(show_line_numbers) = self.show_line_numbers {
15631            return show_line_numbers;
15632        }
15633        EditorSettings::get_global(cx).gutter.line_numbers
15634    }
15635
15636    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15637        self.use_relative_line_numbers
15638            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15639    }
15640
15641    pub fn toggle_relative_line_numbers(
15642        &mut self,
15643        _: &ToggleRelativeLineNumbers,
15644        _: &mut Window,
15645        cx: &mut Context<Self>,
15646    ) {
15647        let is_relative = self.should_use_relative_line_numbers(cx);
15648        self.set_relative_line_number(Some(!is_relative), cx)
15649    }
15650
15651    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15652        self.use_relative_line_numbers = is_relative;
15653        cx.notify();
15654    }
15655
15656    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15657        self.show_gutter = show_gutter;
15658        cx.notify();
15659    }
15660
15661    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15662        self.show_scrollbars = show_scrollbars;
15663        cx.notify();
15664    }
15665
15666    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15667        self.show_line_numbers = Some(show_line_numbers);
15668        cx.notify();
15669    }
15670
15671    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15672        self.show_git_diff_gutter = Some(show_git_diff_gutter);
15673        cx.notify();
15674    }
15675
15676    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15677        self.show_code_actions = Some(show_code_actions);
15678        cx.notify();
15679    }
15680
15681    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15682        self.show_runnables = Some(show_runnables);
15683        cx.notify();
15684    }
15685
15686    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15687        self.show_breakpoints = Some(show_breakpoints);
15688        cx.notify();
15689    }
15690
15691    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15692        if self.display_map.read(cx).masked != masked {
15693            self.display_map.update(cx, |map, _| map.masked = masked);
15694        }
15695        cx.notify()
15696    }
15697
15698    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15699        self.show_wrap_guides = Some(show_wrap_guides);
15700        cx.notify();
15701    }
15702
15703    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15704        self.show_indent_guides = Some(show_indent_guides);
15705        cx.notify();
15706    }
15707
15708    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15709        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15710            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15711                if let Some(dir) = file.abs_path(cx).parent() {
15712                    return Some(dir.to_owned());
15713                }
15714            }
15715
15716            if let Some(project_path) = buffer.read(cx).project_path(cx) {
15717                return Some(project_path.path.to_path_buf());
15718            }
15719        }
15720
15721        None
15722    }
15723
15724    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15725        self.active_excerpt(cx)?
15726            .1
15727            .read(cx)
15728            .file()
15729            .and_then(|f| f.as_local())
15730    }
15731
15732    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15733        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15734            let buffer = buffer.read(cx);
15735            if let Some(project_path) = buffer.project_path(cx) {
15736                let project = self.project.as_ref()?.read(cx);
15737                project.absolute_path(&project_path, cx)
15738            } else {
15739                buffer
15740                    .file()
15741                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15742            }
15743        })
15744    }
15745
15746    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15747        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15748            let project_path = buffer.read(cx).project_path(cx)?;
15749            let project = self.project.as_ref()?.read(cx);
15750            let entry = project.entry_for_path(&project_path, cx)?;
15751            let path = entry.path.to_path_buf();
15752            Some(path)
15753        })
15754    }
15755
15756    pub fn reveal_in_finder(
15757        &mut self,
15758        _: &RevealInFileManager,
15759        _window: &mut Window,
15760        cx: &mut Context<Self>,
15761    ) {
15762        if let Some(target) = self.target_file(cx) {
15763            cx.reveal_path(&target.abs_path(cx));
15764        }
15765    }
15766
15767    pub fn copy_path(
15768        &mut self,
15769        _: &zed_actions::workspace::CopyPath,
15770        _window: &mut Window,
15771        cx: &mut Context<Self>,
15772    ) {
15773        if let Some(path) = self.target_file_abs_path(cx) {
15774            if let Some(path) = path.to_str() {
15775                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15776            }
15777        }
15778    }
15779
15780    pub fn copy_relative_path(
15781        &mut self,
15782        _: &zed_actions::workspace::CopyRelativePath,
15783        _window: &mut Window,
15784        cx: &mut Context<Self>,
15785    ) {
15786        if let Some(path) = self.target_file_path(cx) {
15787            if let Some(path) = path.to_str() {
15788                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15789            }
15790        }
15791    }
15792
15793    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
15794        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15795            buffer.read(cx).project_path(cx)
15796        } else {
15797            None
15798        }
15799    }
15800
15801    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15802        let _ = maybe!({
15803            let breakpoint_store = self.breakpoint_store.as_ref()?;
15804
15805            let Some((_, _, active_position)) =
15806                breakpoint_store.read(cx).active_position().cloned()
15807            else {
15808                self.clear_row_highlights::<DebugCurrentRowHighlight>();
15809                return None;
15810            };
15811
15812            let snapshot = self
15813                .project
15814                .as_ref()?
15815                .read(cx)
15816                .buffer_for_id(active_position.buffer_id?, cx)?
15817                .read(cx)
15818                .snapshot();
15819
15820            for (id, ExcerptRange { context, .. }) in self
15821                .buffer
15822                .read(cx)
15823                .excerpts_for_buffer(active_position.buffer_id?, cx)
15824            {
15825                if context.start.cmp(&active_position, &snapshot).is_ge()
15826                    || context.end.cmp(&active_position, &snapshot).is_lt()
15827                {
15828                    continue;
15829                }
15830                let snapshot = self.buffer.read(cx).snapshot(cx);
15831                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15832
15833                self.clear_row_highlights::<DebugCurrentRowHighlight>();
15834                self.go_to_line::<DebugCurrentRowHighlight>(
15835                    multibuffer_anchor,
15836                    Some(cx.theme().colors().editor_debugger_active_line_background),
15837                    window,
15838                    cx,
15839                );
15840
15841                cx.notify();
15842            }
15843
15844            Some(())
15845        });
15846    }
15847
15848    pub fn copy_file_name_without_extension(
15849        &mut self,
15850        _: &CopyFileNameWithoutExtension,
15851        _: &mut Window,
15852        cx: &mut Context<Self>,
15853    ) {
15854        if let Some(file) = self.target_file(cx) {
15855            if let Some(file_stem) = file.path().file_stem() {
15856                if let Some(name) = file_stem.to_str() {
15857                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15858                }
15859            }
15860        }
15861    }
15862
15863    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15864        if let Some(file) = self.target_file(cx) {
15865            if let Some(file_name) = file.path().file_name() {
15866                if let Some(name) = file_name.to_str() {
15867                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15868                }
15869            }
15870        }
15871    }
15872
15873    pub fn toggle_git_blame(
15874        &mut self,
15875        _: &::git::Blame,
15876        window: &mut Window,
15877        cx: &mut Context<Self>,
15878    ) {
15879        self.show_git_blame_gutter = !self.show_git_blame_gutter;
15880
15881        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15882            self.start_git_blame(true, window, cx);
15883        }
15884
15885        cx.notify();
15886    }
15887
15888    pub fn toggle_git_blame_inline(
15889        &mut self,
15890        _: &ToggleGitBlameInline,
15891        window: &mut Window,
15892        cx: &mut Context<Self>,
15893    ) {
15894        self.toggle_git_blame_inline_internal(true, window, cx);
15895        cx.notify();
15896    }
15897
15898    pub fn open_git_blame_commit(
15899        &mut self,
15900        _: &OpenGitBlameCommit,
15901        window: &mut Window,
15902        cx: &mut Context<Self>,
15903    ) {
15904        self.open_git_blame_commit_internal(window, cx);
15905    }
15906
15907    fn open_git_blame_commit_internal(
15908        &mut self,
15909        window: &mut Window,
15910        cx: &mut Context<Self>,
15911    ) -> Option<()> {
15912        let blame = self.blame.as_ref()?;
15913        let snapshot = self.snapshot(window, cx);
15914        let cursor = self.selections.newest::<Point>(cx).head();
15915        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
15916        let blame_entry = blame
15917            .update(cx, |blame, cx| {
15918                blame
15919                    .blame_for_rows(
15920                        &[RowInfo {
15921                            buffer_id: Some(buffer.remote_id()),
15922                            buffer_row: Some(point.row),
15923                            ..Default::default()
15924                        }],
15925                        cx,
15926                    )
15927                    .next()
15928            })
15929            .flatten()?;
15930        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
15931        let repo = blame.read(cx).repository(cx)?;
15932        let workspace = self.workspace()?.downgrade();
15933        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
15934        None
15935    }
15936
15937    pub fn git_blame_inline_enabled(&self) -> bool {
15938        self.git_blame_inline_enabled
15939    }
15940
15941    pub fn toggle_selection_menu(
15942        &mut self,
15943        _: &ToggleSelectionMenu,
15944        _: &mut Window,
15945        cx: &mut Context<Self>,
15946    ) {
15947        self.show_selection_menu = self
15948            .show_selection_menu
15949            .map(|show_selections_menu| !show_selections_menu)
15950            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
15951
15952        cx.notify();
15953    }
15954
15955    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
15956        self.show_selection_menu
15957            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
15958    }
15959
15960    fn start_git_blame(
15961        &mut self,
15962        user_triggered: bool,
15963        window: &mut Window,
15964        cx: &mut Context<Self>,
15965    ) {
15966        if let Some(project) = self.project.as_ref() {
15967            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
15968                return;
15969            };
15970
15971            if buffer.read(cx).file().is_none() {
15972                return;
15973            }
15974
15975            let focused = self.focus_handle(cx).contains_focused(window, cx);
15976
15977            let project = project.clone();
15978            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
15979            self.blame_subscription =
15980                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
15981            self.blame = Some(blame);
15982        }
15983    }
15984
15985    fn toggle_git_blame_inline_internal(
15986        &mut self,
15987        user_triggered: bool,
15988        window: &mut Window,
15989        cx: &mut Context<Self>,
15990    ) {
15991        if self.git_blame_inline_enabled {
15992            self.git_blame_inline_enabled = false;
15993            self.show_git_blame_inline = false;
15994            self.show_git_blame_inline_delay_task.take();
15995        } else {
15996            self.git_blame_inline_enabled = true;
15997            self.start_git_blame_inline(user_triggered, window, cx);
15998        }
15999
16000        cx.notify();
16001    }
16002
16003    fn start_git_blame_inline(
16004        &mut self,
16005        user_triggered: bool,
16006        window: &mut Window,
16007        cx: &mut Context<Self>,
16008    ) {
16009        self.start_git_blame(user_triggered, window, cx);
16010
16011        if ProjectSettings::get_global(cx)
16012            .git
16013            .inline_blame_delay()
16014            .is_some()
16015        {
16016            self.start_inline_blame_timer(window, cx);
16017        } else {
16018            self.show_git_blame_inline = true
16019        }
16020    }
16021
16022    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16023        self.blame.as_ref()
16024    }
16025
16026    pub fn show_git_blame_gutter(&self) -> bool {
16027        self.show_git_blame_gutter
16028    }
16029
16030    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16031        self.show_git_blame_gutter && self.has_blame_entries(cx)
16032    }
16033
16034    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16035        self.show_git_blame_inline
16036            && (self.focus_handle.is_focused(window)
16037                || self
16038                    .git_blame_inline_tooltip
16039                    .as_ref()
16040                    .and_then(|t| t.upgrade())
16041                    .is_some())
16042            && !self.newest_selection_head_on_empty_line(cx)
16043            && self.has_blame_entries(cx)
16044    }
16045
16046    fn has_blame_entries(&self, cx: &App) -> bool {
16047        self.blame()
16048            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16049    }
16050
16051    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16052        let cursor_anchor = self.selections.newest_anchor().head();
16053
16054        let snapshot = self.buffer.read(cx).snapshot(cx);
16055        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16056
16057        snapshot.line_len(buffer_row) == 0
16058    }
16059
16060    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16061        let buffer_and_selection = maybe!({
16062            let selection = self.selections.newest::<Point>(cx);
16063            let selection_range = selection.range();
16064
16065            let multi_buffer = self.buffer().read(cx);
16066            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16067            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16068
16069            let (buffer, range, _) = if selection.reversed {
16070                buffer_ranges.first()
16071            } else {
16072                buffer_ranges.last()
16073            }?;
16074
16075            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16076                ..text::ToPoint::to_point(&range.end, &buffer).row;
16077            Some((
16078                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16079                selection,
16080            ))
16081        });
16082
16083        let Some((buffer, selection)) = buffer_and_selection else {
16084            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16085        };
16086
16087        let Some(project) = self.project.as_ref() else {
16088            return Task::ready(Err(anyhow!("editor does not have project")));
16089        };
16090
16091        project.update(cx, |project, cx| {
16092            project.get_permalink_to_line(&buffer, selection, cx)
16093        })
16094    }
16095
16096    pub fn copy_permalink_to_line(
16097        &mut self,
16098        _: &CopyPermalinkToLine,
16099        window: &mut Window,
16100        cx: &mut Context<Self>,
16101    ) {
16102        let permalink_task = self.get_permalink_to_line(cx);
16103        let workspace = self.workspace();
16104
16105        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16106            Ok(permalink) => {
16107                cx.update(|_, cx| {
16108                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16109                })
16110                .ok();
16111            }
16112            Err(err) => {
16113                let message = format!("Failed to copy permalink: {err}");
16114
16115                Err::<(), anyhow::Error>(err).log_err();
16116
16117                if let Some(workspace) = workspace {
16118                    workspace
16119                        .update_in(cx, |workspace, _, cx| {
16120                            struct CopyPermalinkToLine;
16121
16122                            workspace.show_toast(
16123                                Toast::new(
16124                                    NotificationId::unique::<CopyPermalinkToLine>(),
16125                                    message,
16126                                ),
16127                                cx,
16128                            )
16129                        })
16130                        .ok();
16131                }
16132            }
16133        })
16134        .detach();
16135    }
16136
16137    pub fn copy_file_location(
16138        &mut self,
16139        _: &CopyFileLocation,
16140        _: &mut Window,
16141        cx: &mut Context<Self>,
16142    ) {
16143        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16144        if let Some(file) = self.target_file(cx) {
16145            if let Some(path) = file.path().to_str() {
16146                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16147            }
16148        }
16149    }
16150
16151    pub fn open_permalink_to_line(
16152        &mut self,
16153        _: &OpenPermalinkToLine,
16154        window: &mut Window,
16155        cx: &mut Context<Self>,
16156    ) {
16157        let permalink_task = self.get_permalink_to_line(cx);
16158        let workspace = self.workspace();
16159
16160        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16161            Ok(permalink) => {
16162                cx.update(|_, cx| {
16163                    cx.open_url(permalink.as_ref());
16164                })
16165                .ok();
16166            }
16167            Err(err) => {
16168                let message = format!("Failed to open permalink: {err}");
16169
16170                Err::<(), anyhow::Error>(err).log_err();
16171
16172                if let Some(workspace) = workspace {
16173                    workspace
16174                        .update(cx, |workspace, cx| {
16175                            struct OpenPermalinkToLine;
16176
16177                            workspace.show_toast(
16178                                Toast::new(
16179                                    NotificationId::unique::<OpenPermalinkToLine>(),
16180                                    message,
16181                                ),
16182                                cx,
16183                            )
16184                        })
16185                        .ok();
16186                }
16187            }
16188        })
16189        .detach();
16190    }
16191
16192    pub fn insert_uuid_v4(
16193        &mut self,
16194        _: &InsertUuidV4,
16195        window: &mut Window,
16196        cx: &mut Context<Self>,
16197    ) {
16198        self.insert_uuid(UuidVersion::V4, window, cx);
16199    }
16200
16201    pub fn insert_uuid_v7(
16202        &mut self,
16203        _: &InsertUuidV7,
16204        window: &mut Window,
16205        cx: &mut Context<Self>,
16206    ) {
16207        self.insert_uuid(UuidVersion::V7, window, cx);
16208    }
16209
16210    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16211        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16212        self.transact(window, cx, |this, window, cx| {
16213            let edits = this
16214                .selections
16215                .all::<Point>(cx)
16216                .into_iter()
16217                .map(|selection| {
16218                    let uuid = match version {
16219                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16220                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16221                    };
16222
16223                    (selection.range(), uuid.to_string())
16224                });
16225            this.edit(edits, cx);
16226            this.refresh_inline_completion(true, false, window, cx);
16227        });
16228    }
16229
16230    pub fn open_selections_in_multibuffer(
16231        &mut self,
16232        _: &OpenSelectionsInMultibuffer,
16233        window: &mut Window,
16234        cx: &mut Context<Self>,
16235    ) {
16236        let multibuffer = self.buffer.read(cx);
16237
16238        let Some(buffer) = multibuffer.as_singleton() else {
16239            return;
16240        };
16241
16242        let Some(workspace) = self.workspace() else {
16243            return;
16244        };
16245
16246        let locations = self
16247            .selections
16248            .disjoint_anchors()
16249            .iter()
16250            .map(|range| Location {
16251                buffer: buffer.clone(),
16252                range: range.start.text_anchor..range.end.text_anchor,
16253            })
16254            .collect::<Vec<_>>();
16255
16256        let title = multibuffer.title(cx).to_string();
16257
16258        cx.spawn_in(window, async move |_, cx| {
16259            workspace.update_in(cx, |workspace, window, cx| {
16260                Self::open_locations_in_multibuffer(
16261                    workspace,
16262                    locations,
16263                    format!("Selections for '{title}'"),
16264                    false,
16265                    MultibufferSelectionMode::All,
16266                    window,
16267                    cx,
16268                );
16269            })
16270        })
16271        .detach();
16272    }
16273
16274    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16275    /// last highlight added will be used.
16276    ///
16277    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16278    pub fn highlight_rows<T: 'static>(
16279        &mut self,
16280        range: Range<Anchor>,
16281        color: Hsla,
16282        should_autoscroll: bool,
16283        cx: &mut Context<Self>,
16284    ) {
16285        let snapshot = self.buffer().read(cx).snapshot(cx);
16286        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16287        let ix = row_highlights.binary_search_by(|highlight| {
16288            Ordering::Equal
16289                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16290                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16291        });
16292
16293        if let Err(mut ix) = ix {
16294            let index = post_inc(&mut self.highlight_order);
16295
16296            // If this range intersects with the preceding highlight, then merge it with
16297            // the preceding highlight. Otherwise insert a new highlight.
16298            let mut merged = false;
16299            if ix > 0 {
16300                let prev_highlight = &mut row_highlights[ix - 1];
16301                if prev_highlight
16302                    .range
16303                    .end
16304                    .cmp(&range.start, &snapshot)
16305                    .is_ge()
16306                {
16307                    ix -= 1;
16308                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16309                        prev_highlight.range.end = range.end;
16310                    }
16311                    merged = true;
16312                    prev_highlight.index = index;
16313                    prev_highlight.color = color;
16314                    prev_highlight.should_autoscroll = should_autoscroll;
16315                }
16316            }
16317
16318            if !merged {
16319                row_highlights.insert(
16320                    ix,
16321                    RowHighlight {
16322                        range: range.clone(),
16323                        index,
16324                        color,
16325                        should_autoscroll,
16326                    },
16327                );
16328            }
16329
16330            // If any of the following highlights intersect with this one, merge them.
16331            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16332                let highlight = &row_highlights[ix];
16333                if next_highlight
16334                    .range
16335                    .start
16336                    .cmp(&highlight.range.end, &snapshot)
16337                    .is_le()
16338                {
16339                    if next_highlight
16340                        .range
16341                        .end
16342                        .cmp(&highlight.range.end, &snapshot)
16343                        .is_gt()
16344                    {
16345                        row_highlights[ix].range.end = next_highlight.range.end;
16346                    }
16347                    row_highlights.remove(ix + 1);
16348                } else {
16349                    break;
16350                }
16351            }
16352        }
16353    }
16354
16355    /// Remove any highlighted row ranges of the given type that intersect the
16356    /// given ranges.
16357    pub fn remove_highlighted_rows<T: 'static>(
16358        &mut self,
16359        ranges_to_remove: Vec<Range<Anchor>>,
16360        cx: &mut Context<Self>,
16361    ) {
16362        let snapshot = self.buffer().read(cx).snapshot(cx);
16363        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16364        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16365        row_highlights.retain(|highlight| {
16366            while let Some(range_to_remove) = ranges_to_remove.peek() {
16367                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16368                    Ordering::Less | Ordering::Equal => {
16369                        ranges_to_remove.next();
16370                    }
16371                    Ordering::Greater => {
16372                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16373                            Ordering::Less | Ordering::Equal => {
16374                                return false;
16375                            }
16376                            Ordering::Greater => break,
16377                        }
16378                    }
16379                }
16380            }
16381
16382            true
16383        })
16384    }
16385
16386    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16387    pub fn clear_row_highlights<T: 'static>(&mut self) {
16388        self.highlighted_rows.remove(&TypeId::of::<T>());
16389    }
16390
16391    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16392    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16393        self.highlighted_rows
16394            .get(&TypeId::of::<T>())
16395            .map_or(&[] as &[_], |vec| vec.as_slice())
16396            .iter()
16397            .map(|highlight| (highlight.range.clone(), highlight.color))
16398    }
16399
16400    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16401    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16402    /// Allows to ignore certain kinds of highlights.
16403    pub fn highlighted_display_rows(
16404        &self,
16405        window: &mut Window,
16406        cx: &mut App,
16407    ) -> BTreeMap<DisplayRow, LineHighlight> {
16408        let snapshot = self.snapshot(window, cx);
16409        let mut used_highlight_orders = HashMap::default();
16410        self.highlighted_rows
16411            .iter()
16412            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16413            .fold(
16414                BTreeMap::<DisplayRow, LineHighlight>::new(),
16415                |mut unique_rows, highlight| {
16416                    let start = highlight.range.start.to_display_point(&snapshot);
16417                    let end = highlight.range.end.to_display_point(&snapshot);
16418                    let start_row = start.row().0;
16419                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16420                        && end.column() == 0
16421                    {
16422                        end.row().0.saturating_sub(1)
16423                    } else {
16424                        end.row().0
16425                    };
16426                    for row in start_row..=end_row {
16427                        let used_index =
16428                            used_highlight_orders.entry(row).or_insert(highlight.index);
16429                        if highlight.index >= *used_index {
16430                            *used_index = highlight.index;
16431                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16432                        }
16433                    }
16434                    unique_rows
16435                },
16436            )
16437    }
16438
16439    pub fn highlighted_display_row_for_autoscroll(
16440        &self,
16441        snapshot: &DisplaySnapshot,
16442    ) -> Option<DisplayRow> {
16443        self.highlighted_rows
16444            .values()
16445            .flat_map(|highlighted_rows| highlighted_rows.iter())
16446            .filter_map(|highlight| {
16447                if highlight.should_autoscroll {
16448                    Some(highlight.range.start.to_display_point(snapshot).row())
16449                } else {
16450                    None
16451                }
16452            })
16453            .min()
16454    }
16455
16456    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16457        self.highlight_background::<SearchWithinRange>(
16458            ranges,
16459            |colors| colors.editor_document_highlight_read_background,
16460            cx,
16461        )
16462    }
16463
16464    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16465        self.breadcrumb_header = Some(new_header);
16466    }
16467
16468    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16469        self.clear_background_highlights::<SearchWithinRange>(cx);
16470    }
16471
16472    pub fn highlight_background<T: 'static>(
16473        &mut self,
16474        ranges: &[Range<Anchor>],
16475        color_fetcher: fn(&ThemeColors) -> Hsla,
16476        cx: &mut Context<Self>,
16477    ) {
16478        self.background_highlights
16479            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16480        self.scrollbar_marker_state.dirty = true;
16481        cx.notify();
16482    }
16483
16484    pub fn clear_background_highlights<T: 'static>(
16485        &mut self,
16486        cx: &mut Context<Self>,
16487    ) -> Option<BackgroundHighlight> {
16488        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16489        if !text_highlights.1.is_empty() {
16490            self.scrollbar_marker_state.dirty = true;
16491            cx.notify();
16492        }
16493        Some(text_highlights)
16494    }
16495
16496    pub fn highlight_gutter<T: 'static>(
16497        &mut self,
16498        ranges: &[Range<Anchor>],
16499        color_fetcher: fn(&App) -> Hsla,
16500        cx: &mut Context<Self>,
16501    ) {
16502        self.gutter_highlights
16503            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16504        cx.notify();
16505    }
16506
16507    pub fn clear_gutter_highlights<T: 'static>(
16508        &mut self,
16509        cx: &mut Context<Self>,
16510    ) -> Option<GutterHighlight> {
16511        cx.notify();
16512        self.gutter_highlights.remove(&TypeId::of::<T>())
16513    }
16514
16515    #[cfg(feature = "test-support")]
16516    pub fn all_text_background_highlights(
16517        &self,
16518        window: &mut Window,
16519        cx: &mut Context<Self>,
16520    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16521        let snapshot = self.snapshot(window, cx);
16522        let buffer = &snapshot.buffer_snapshot;
16523        let start = buffer.anchor_before(0);
16524        let end = buffer.anchor_after(buffer.len());
16525        let theme = cx.theme().colors();
16526        self.background_highlights_in_range(start..end, &snapshot, theme)
16527    }
16528
16529    #[cfg(feature = "test-support")]
16530    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16531        let snapshot = self.buffer().read(cx).snapshot(cx);
16532
16533        let highlights = self
16534            .background_highlights
16535            .get(&TypeId::of::<items::BufferSearchHighlights>());
16536
16537        if let Some((_color, ranges)) = highlights {
16538            ranges
16539                .iter()
16540                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16541                .collect_vec()
16542        } else {
16543            vec![]
16544        }
16545    }
16546
16547    fn document_highlights_for_position<'a>(
16548        &'a self,
16549        position: Anchor,
16550        buffer: &'a MultiBufferSnapshot,
16551    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16552        let read_highlights = self
16553            .background_highlights
16554            .get(&TypeId::of::<DocumentHighlightRead>())
16555            .map(|h| &h.1);
16556        let write_highlights = self
16557            .background_highlights
16558            .get(&TypeId::of::<DocumentHighlightWrite>())
16559            .map(|h| &h.1);
16560        let left_position = position.bias_left(buffer);
16561        let right_position = position.bias_right(buffer);
16562        read_highlights
16563            .into_iter()
16564            .chain(write_highlights)
16565            .flat_map(move |ranges| {
16566                let start_ix = match ranges.binary_search_by(|probe| {
16567                    let cmp = probe.end.cmp(&left_position, buffer);
16568                    if cmp.is_ge() {
16569                        Ordering::Greater
16570                    } else {
16571                        Ordering::Less
16572                    }
16573                }) {
16574                    Ok(i) | Err(i) => i,
16575                };
16576
16577                ranges[start_ix..]
16578                    .iter()
16579                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16580            })
16581    }
16582
16583    pub fn has_background_highlights<T: 'static>(&self) -> bool {
16584        self.background_highlights
16585            .get(&TypeId::of::<T>())
16586            .map_or(false, |(_, highlights)| !highlights.is_empty())
16587    }
16588
16589    pub fn background_highlights_in_range(
16590        &self,
16591        search_range: Range<Anchor>,
16592        display_snapshot: &DisplaySnapshot,
16593        theme: &ThemeColors,
16594    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16595        let mut results = Vec::new();
16596        for (color_fetcher, ranges) in self.background_highlights.values() {
16597            let color = color_fetcher(theme);
16598            let start_ix = match ranges.binary_search_by(|probe| {
16599                let cmp = probe
16600                    .end
16601                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16602                if cmp.is_gt() {
16603                    Ordering::Greater
16604                } else {
16605                    Ordering::Less
16606                }
16607            }) {
16608                Ok(i) | Err(i) => i,
16609            };
16610            for range in &ranges[start_ix..] {
16611                if range
16612                    .start
16613                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16614                    .is_ge()
16615                {
16616                    break;
16617                }
16618
16619                let start = range.start.to_display_point(display_snapshot);
16620                let end = range.end.to_display_point(display_snapshot);
16621                results.push((start..end, color))
16622            }
16623        }
16624        results
16625    }
16626
16627    pub fn background_highlight_row_ranges<T: 'static>(
16628        &self,
16629        search_range: Range<Anchor>,
16630        display_snapshot: &DisplaySnapshot,
16631        count: usize,
16632    ) -> Vec<RangeInclusive<DisplayPoint>> {
16633        let mut results = Vec::new();
16634        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16635            return vec![];
16636        };
16637
16638        let start_ix = match ranges.binary_search_by(|probe| {
16639            let cmp = probe
16640                .end
16641                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16642            if cmp.is_gt() {
16643                Ordering::Greater
16644            } else {
16645                Ordering::Less
16646            }
16647        }) {
16648            Ok(i) | Err(i) => i,
16649        };
16650        let mut push_region = |start: Option<Point>, end: Option<Point>| {
16651            if let (Some(start_display), Some(end_display)) = (start, end) {
16652                results.push(
16653                    start_display.to_display_point(display_snapshot)
16654                        ..=end_display.to_display_point(display_snapshot),
16655                );
16656            }
16657        };
16658        let mut start_row: Option<Point> = None;
16659        let mut end_row: Option<Point> = None;
16660        if ranges.len() > count {
16661            return Vec::new();
16662        }
16663        for range in &ranges[start_ix..] {
16664            if range
16665                .start
16666                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16667                .is_ge()
16668            {
16669                break;
16670            }
16671            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16672            if let Some(current_row) = &end_row {
16673                if end.row == current_row.row {
16674                    continue;
16675                }
16676            }
16677            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16678            if start_row.is_none() {
16679                assert_eq!(end_row, None);
16680                start_row = Some(start);
16681                end_row = Some(end);
16682                continue;
16683            }
16684            if let Some(current_end) = end_row.as_mut() {
16685                if start.row > current_end.row + 1 {
16686                    push_region(start_row, end_row);
16687                    start_row = Some(start);
16688                    end_row = Some(end);
16689                } else {
16690                    // Merge two hunks.
16691                    *current_end = end;
16692                }
16693            } else {
16694                unreachable!();
16695            }
16696        }
16697        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16698        push_region(start_row, end_row);
16699        results
16700    }
16701
16702    pub fn gutter_highlights_in_range(
16703        &self,
16704        search_range: Range<Anchor>,
16705        display_snapshot: &DisplaySnapshot,
16706        cx: &App,
16707    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16708        let mut results = Vec::new();
16709        for (color_fetcher, ranges) in self.gutter_highlights.values() {
16710            let color = color_fetcher(cx);
16711            let start_ix = match ranges.binary_search_by(|probe| {
16712                let cmp = probe
16713                    .end
16714                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16715                if cmp.is_gt() {
16716                    Ordering::Greater
16717                } else {
16718                    Ordering::Less
16719                }
16720            }) {
16721                Ok(i) | Err(i) => i,
16722            };
16723            for range in &ranges[start_ix..] {
16724                if range
16725                    .start
16726                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16727                    .is_ge()
16728                {
16729                    break;
16730                }
16731
16732                let start = range.start.to_display_point(display_snapshot);
16733                let end = range.end.to_display_point(display_snapshot);
16734                results.push((start..end, color))
16735            }
16736        }
16737        results
16738    }
16739
16740    /// Get the text ranges corresponding to the redaction query
16741    pub fn redacted_ranges(
16742        &self,
16743        search_range: Range<Anchor>,
16744        display_snapshot: &DisplaySnapshot,
16745        cx: &App,
16746    ) -> Vec<Range<DisplayPoint>> {
16747        display_snapshot
16748            .buffer_snapshot
16749            .redacted_ranges(search_range, |file| {
16750                if let Some(file) = file {
16751                    file.is_private()
16752                        && EditorSettings::get(
16753                            Some(SettingsLocation {
16754                                worktree_id: file.worktree_id(cx),
16755                                path: file.path().as_ref(),
16756                            }),
16757                            cx,
16758                        )
16759                        .redact_private_values
16760                } else {
16761                    false
16762                }
16763            })
16764            .map(|range| {
16765                range.start.to_display_point(display_snapshot)
16766                    ..range.end.to_display_point(display_snapshot)
16767            })
16768            .collect()
16769    }
16770
16771    pub fn highlight_text<T: 'static>(
16772        &mut self,
16773        ranges: Vec<Range<Anchor>>,
16774        style: HighlightStyle,
16775        cx: &mut Context<Self>,
16776    ) {
16777        self.display_map.update(cx, |map, _| {
16778            map.highlight_text(TypeId::of::<T>(), ranges, style)
16779        });
16780        cx.notify();
16781    }
16782
16783    pub(crate) fn highlight_inlays<T: 'static>(
16784        &mut self,
16785        highlights: Vec<InlayHighlight>,
16786        style: HighlightStyle,
16787        cx: &mut Context<Self>,
16788    ) {
16789        self.display_map.update(cx, |map, _| {
16790            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16791        });
16792        cx.notify();
16793    }
16794
16795    pub fn text_highlights<'a, T: 'static>(
16796        &'a self,
16797        cx: &'a App,
16798    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16799        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16800    }
16801
16802    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16803        let cleared = self
16804            .display_map
16805            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16806        if cleared {
16807            cx.notify();
16808        }
16809    }
16810
16811    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16812        (self.read_only(cx) || self.blink_manager.read(cx).visible())
16813            && self.focus_handle.is_focused(window)
16814    }
16815
16816    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16817        self.show_cursor_when_unfocused = is_enabled;
16818        cx.notify();
16819    }
16820
16821    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16822        cx.notify();
16823    }
16824
16825    fn on_buffer_event(
16826        &mut self,
16827        multibuffer: &Entity<MultiBuffer>,
16828        event: &multi_buffer::Event,
16829        window: &mut Window,
16830        cx: &mut Context<Self>,
16831    ) {
16832        match event {
16833            multi_buffer::Event::Edited {
16834                singleton_buffer_edited,
16835                edited_buffer: buffer_edited,
16836            } => {
16837                self.scrollbar_marker_state.dirty = true;
16838                self.active_indent_guides_state.dirty = true;
16839                self.refresh_active_diagnostics(cx);
16840                self.refresh_code_actions(window, cx);
16841                if self.has_active_inline_completion() {
16842                    self.update_visible_inline_completion(window, cx);
16843                }
16844                if let Some(buffer) = buffer_edited {
16845                    let buffer_id = buffer.read(cx).remote_id();
16846                    if !self.registered_buffers.contains_key(&buffer_id) {
16847                        if let Some(project) = self.project.as_ref() {
16848                            project.update(cx, |project, cx| {
16849                                self.registered_buffers.insert(
16850                                    buffer_id,
16851                                    project.register_buffer_with_language_servers(&buffer, cx),
16852                                );
16853                            })
16854                        }
16855                    }
16856                }
16857                cx.emit(EditorEvent::BufferEdited);
16858                cx.emit(SearchEvent::MatchesInvalidated);
16859                if *singleton_buffer_edited {
16860                    if let Some(project) = &self.project {
16861                        #[allow(clippy::mutable_key_type)]
16862                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16863                            multibuffer
16864                                .all_buffers()
16865                                .into_iter()
16866                                .filter_map(|buffer| {
16867                                    buffer.update(cx, |buffer, cx| {
16868                                        let language = buffer.language()?;
16869                                        let should_discard = project.update(cx, |project, cx| {
16870                                            project.is_local()
16871                                                && !project.has_language_servers_for(buffer, cx)
16872                                        });
16873                                        should_discard.not().then_some(language.clone())
16874                                    })
16875                                })
16876                                .collect::<HashSet<_>>()
16877                        });
16878                        if !languages_affected.is_empty() {
16879                            self.refresh_inlay_hints(
16880                                InlayHintRefreshReason::BufferEdited(languages_affected),
16881                                cx,
16882                            );
16883                        }
16884                    }
16885                }
16886
16887                let Some(project) = &self.project else { return };
16888                let (telemetry, is_via_ssh) = {
16889                    let project = project.read(cx);
16890                    let telemetry = project.client().telemetry().clone();
16891                    let is_via_ssh = project.is_via_ssh();
16892                    (telemetry, is_via_ssh)
16893                };
16894                refresh_linked_ranges(self, window, cx);
16895                telemetry.log_edit_event("editor", is_via_ssh);
16896            }
16897            multi_buffer::Event::ExcerptsAdded {
16898                buffer,
16899                predecessor,
16900                excerpts,
16901            } => {
16902                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16903                let buffer_id = buffer.read(cx).remote_id();
16904                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16905                    if let Some(project) = &self.project {
16906                        get_uncommitted_diff_for_buffer(
16907                            project,
16908                            [buffer.clone()],
16909                            self.buffer.clone(),
16910                            cx,
16911                        )
16912                        .detach();
16913                    }
16914                }
16915                cx.emit(EditorEvent::ExcerptsAdded {
16916                    buffer: buffer.clone(),
16917                    predecessor: *predecessor,
16918                    excerpts: excerpts.clone(),
16919                });
16920                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16921            }
16922            multi_buffer::Event::ExcerptsRemoved { ids } => {
16923                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16924                let buffer = self.buffer.read(cx);
16925                self.registered_buffers
16926                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16927                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16928                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16929            }
16930            multi_buffer::Event::ExcerptsEdited {
16931                excerpt_ids,
16932                buffer_ids,
16933            } => {
16934                self.display_map.update(cx, |map, cx| {
16935                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
16936                });
16937                cx.emit(EditorEvent::ExcerptsEdited {
16938                    ids: excerpt_ids.clone(),
16939                })
16940            }
16941            multi_buffer::Event::ExcerptsExpanded { ids } => {
16942                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16943                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
16944            }
16945            multi_buffer::Event::Reparsed(buffer_id) => {
16946                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16947                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16948
16949                cx.emit(EditorEvent::Reparsed(*buffer_id));
16950            }
16951            multi_buffer::Event::DiffHunksToggled => {
16952                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16953            }
16954            multi_buffer::Event::LanguageChanged(buffer_id) => {
16955                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
16956                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16957                cx.emit(EditorEvent::Reparsed(*buffer_id));
16958                cx.notify();
16959            }
16960            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
16961            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
16962            multi_buffer::Event::FileHandleChanged
16963            | multi_buffer::Event::Reloaded
16964            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
16965            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
16966            multi_buffer::Event::DiagnosticsUpdated => {
16967                self.refresh_active_diagnostics(cx);
16968                self.refresh_inline_diagnostics(true, window, cx);
16969                self.scrollbar_marker_state.dirty = true;
16970                cx.notify();
16971            }
16972            _ => {}
16973        };
16974    }
16975
16976    fn on_display_map_changed(
16977        &mut self,
16978        _: Entity<DisplayMap>,
16979        _: &mut Window,
16980        cx: &mut Context<Self>,
16981    ) {
16982        cx.notify();
16983    }
16984
16985    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16986        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16987        self.update_edit_prediction_settings(cx);
16988        self.refresh_inline_completion(true, false, window, cx);
16989        self.refresh_inlay_hints(
16990            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
16991                self.selections.newest_anchor().head(),
16992                &self.buffer.read(cx).snapshot(cx),
16993                cx,
16994            )),
16995            cx,
16996        );
16997
16998        let old_cursor_shape = self.cursor_shape;
16999
17000        {
17001            let editor_settings = EditorSettings::get_global(cx);
17002            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17003            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17004            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17005            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17006        }
17007
17008        if old_cursor_shape != self.cursor_shape {
17009            cx.emit(EditorEvent::CursorShapeChanged);
17010        }
17011
17012        let project_settings = ProjectSettings::get_global(cx);
17013        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17014
17015        if self.mode == EditorMode::Full {
17016            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17017            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17018            if self.show_inline_diagnostics != show_inline_diagnostics {
17019                self.show_inline_diagnostics = show_inline_diagnostics;
17020                self.refresh_inline_diagnostics(false, window, cx);
17021            }
17022
17023            if self.git_blame_inline_enabled != inline_blame_enabled {
17024                self.toggle_git_blame_inline_internal(false, window, cx);
17025            }
17026        }
17027
17028        cx.notify();
17029    }
17030
17031    pub fn set_searchable(&mut self, searchable: bool) {
17032        self.searchable = searchable;
17033    }
17034
17035    pub fn searchable(&self) -> bool {
17036        self.searchable
17037    }
17038
17039    fn open_proposed_changes_editor(
17040        &mut self,
17041        _: &OpenProposedChangesEditor,
17042        window: &mut Window,
17043        cx: &mut Context<Self>,
17044    ) {
17045        let Some(workspace) = self.workspace() else {
17046            cx.propagate();
17047            return;
17048        };
17049
17050        let selections = self.selections.all::<usize>(cx);
17051        let multi_buffer = self.buffer.read(cx);
17052        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17053        let mut new_selections_by_buffer = HashMap::default();
17054        for selection in selections {
17055            for (buffer, range, _) in
17056                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17057            {
17058                let mut range = range.to_point(buffer);
17059                range.start.column = 0;
17060                range.end.column = buffer.line_len(range.end.row);
17061                new_selections_by_buffer
17062                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17063                    .or_insert(Vec::new())
17064                    .push(range)
17065            }
17066        }
17067
17068        let proposed_changes_buffers = new_selections_by_buffer
17069            .into_iter()
17070            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17071            .collect::<Vec<_>>();
17072        let proposed_changes_editor = cx.new(|cx| {
17073            ProposedChangesEditor::new(
17074                "Proposed changes",
17075                proposed_changes_buffers,
17076                self.project.clone(),
17077                window,
17078                cx,
17079            )
17080        });
17081
17082        window.defer(cx, move |window, cx| {
17083            workspace.update(cx, |workspace, cx| {
17084                workspace.active_pane().update(cx, |pane, cx| {
17085                    pane.add_item(
17086                        Box::new(proposed_changes_editor),
17087                        true,
17088                        true,
17089                        None,
17090                        window,
17091                        cx,
17092                    );
17093                });
17094            });
17095        });
17096    }
17097
17098    pub fn open_excerpts_in_split(
17099        &mut self,
17100        _: &OpenExcerptsSplit,
17101        window: &mut Window,
17102        cx: &mut Context<Self>,
17103    ) {
17104        self.open_excerpts_common(None, true, window, cx)
17105    }
17106
17107    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17108        self.open_excerpts_common(None, false, window, cx)
17109    }
17110
17111    fn open_excerpts_common(
17112        &mut self,
17113        jump_data: Option<JumpData>,
17114        split: bool,
17115        window: &mut Window,
17116        cx: &mut Context<Self>,
17117    ) {
17118        let Some(workspace) = self.workspace() else {
17119            cx.propagate();
17120            return;
17121        };
17122
17123        if self.buffer.read(cx).is_singleton() {
17124            cx.propagate();
17125            return;
17126        }
17127
17128        let mut new_selections_by_buffer = HashMap::default();
17129        match &jump_data {
17130            Some(JumpData::MultiBufferPoint {
17131                excerpt_id,
17132                position,
17133                anchor,
17134                line_offset_from_top,
17135            }) => {
17136                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17137                if let Some(buffer) = multi_buffer_snapshot
17138                    .buffer_id_for_excerpt(*excerpt_id)
17139                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17140                {
17141                    let buffer_snapshot = buffer.read(cx).snapshot();
17142                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17143                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17144                    } else {
17145                        buffer_snapshot.clip_point(*position, Bias::Left)
17146                    };
17147                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17148                    new_selections_by_buffer.insert(
17149                        buffer,
17150                        (
17151                            vec![jump_to_offset..jump_to_offset],
17152                            Some(*line_offset_from_top),
17153                        ),
17154                    );
17155                }
17156            }
17157            Some(JumpData::MultiBufferRow {
17158                row,
17159                line_offset_from_top,
17160            }) => {
17161                let point = MultiBufferPoint::new(row.0, 0);
17162                if let Some((buffer, buffer_point, _)) =
17163                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17164                {
17165                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17166                    new_selections_by_buffer
17167                        .entry(buffer)
17168                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17169                        .0
17170                        .push(buffer_offset..buffer_offset)
17171                }
17172            }
17173            None => {
17174                let selections = self.selections.all::<usize>(cx);
17175                let multi_buffer = self.buffer.read(cx);
17176                for selection in selections {
17177                    for (snapshot, range, _, anchor) in multi_buffer
17178                        .snapshot(cx)
17179                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17180                    {
17181                        if let Some(anchor) = anchor {
17182                            // selection is in a deleted hunk
17183                            let Some(buffer_id) = anchor.buffer_id else {
17184                                continue;
17185                            };
17186                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17187                                continue;
17188                            };
17189                            let offset = text::ToOffset::to_offset(
17190                                &anchor.text_anchor,
17191                                &buffer_handle.read(cx).snapshot(),
17192                            );
17193                            let range = offset..offset;
17194                            new_selections_by_buffer
17195                                .entry(buffer_handle)
17196                                .or_insert((Vec::new(), None))
17197                                .0
17198                                .push(range)
17199                        } else {
17200                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17201                            else {
17202                                continue;
17203                            };
17204                            new_selections_by_buffer
17205                                .entry(buffer_handle)
17206                                .or_insert((Vec::new(), None))
17207                                .0
17208                                .push(range)
17209                        }
17210                    }
17211                }
17212            }
17213        }
17214
17215        if new_selections_by_buffer.is_empty() {
17216            return;
17217        }
17218
17219        // We defer the pane interaction because we ourselves are a workspace item
17220        // and activating a new item causes the pane to call a method on us reentrantly,
17221        // which panics if we're on the stack.
17222        window.defer(cx, move |window, cx| {
17223            workspace.update(cx, |workspace, cx| {
17224                let pane = if split {
17225                    workspace.adjacent_pane(window, cx)
17226                } else {
17227                    workspace.active_pane().clone()
17228                };
17229
17230                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17231                    let editor = buffer
17232                        .read(cx)
17233                        .file()
17234                        .is_none()
17235                        .then(|| {
17236                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17237                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17238                            // Instead, we try to activate the existing editor in the pane first.
17239                            let (editor, pane_item_index) =
17240                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17241                                    let editor = item.downcast::<Editor>()?;
17242                                    let singleton_buffer =
17243                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17244                                    if singleton_buffer == buffer {
17245                                        Some((editor, i))
17246                                    } else {
17247                                        None
17248                                    }
17249                                })?;
17250                            pane.update(cx, |pane, cx| {
17251                                pane.activate_item(pane_item_index, true, true, window, cx)
17252                            });
17253                            Some(editor)
17254                        })
17255                        .flatten()
17256                        .unwrap_or_else(|| {
17257                            workspace.open_project_item::<Self>(
17258                                pane.clone(),
17259                                buffer,
17260                                true,
17261                                true,
17262                                window,
17263                                cx,
17264                            )
17265                        });
17266
17267                    editor.update(cx, |editor, cx| {
17268                        let autoscroll = match scroll_offset {
17269                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17270                            None => Autoscroll::newest(),
17271                        };
17272                        let nav_history = editor.nav_history.take();
17273                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17274                            s.select_ranges(ranges);
17275                        });
17276                        editor.nav_history = nav_history;
17277                    });
17278                }
17279            })
17280        });
17281    }
17282
17283    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17284        let snapshot = self.buffer.read(cx).read(cx);
17285        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17286        Some(
17287            ranges
17288                .iter()
17289                .map(move |range| {
17290                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17291                })
17292                .collect(),
17293        )
17294    }
17295
17296    fn selection_replacement_ranges(
17297        &self,
17298        range: Range<OffsetUtf16>,
17299        cx: &mut App,
17300    ) -> Vec<Range<OffsetUtf16>> {
17301        let selections = self.selections.all::<OffsetUtf16>(cx);
17302        let newest_selection = selections
17303            .iter()
17304            .max_by_key(|selection| selection.id)
17305            .unwrap();
17306        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17307        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17308        let snapshot = self.buffer.read(cx).read(cx);
17309        selections
17310            .into_iter()
17311            .map(|mut selection| {
17312                selection.start.0 =
17313                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17314                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17315                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17316                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17317            })
17318            .collect()
17319    }
17320
17321    fn report_editor_event(
17322        &self,
17323        event_type: &'static str,
17324        file_extension: Option<String>,
17325        cx: &App,
17326    ) {
17327        if cfg!(any(test, feature = "test-support")) {
17328            return;
17329        }
17330
17331        let Some(project) = &self.project else { return };
17332
17333        // If None, we are in a file without an extension
17334        let file = self
17335            .buffer
17336            .read(cx)
17337            .as_singleton()
17338            .and_then(|b| b.read(cx).file());
17339        let file_extension = file_extension.or(file
17340            .as_ref()
17341            .and_then(|file| Path::new(file.file_name(cx)).extension())
17342            .and_then(|e| e.to_str())
17343            .map(|a| a.to_string()));
17344
17345        let vim_mode = cx
17346            .global::<SettingsStore>()
17347            .raw_user_settings()
17348            .get("vim_mode")
17349            == Some(&serde_json::Value::Bool(true));
17350
17351        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17352        let copilot_enabled = edit_predictions_provider
17353            == language::language_settings::EditPredictionProvider::Copilot;
17354        let copilot_enabled_for_language = self
17355            .buffer
17356            .read(cx)
17357            .language_settings(cx)
17358            .show_edit_predictions;
17359
17360        let project = project.read(cx);
17361        telemetry::event!(
17362            event_type,
17363            file_extension,
17364            vim_mode,
17365            copilot_enabled,
17366            copilot_enabled_for_language,
17367            edit_predictions_provider,
17368            is_via_ssh = project.is_via_ssh(),
17369        );
17370    }
17371
17372    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17373    /// with each line being an array of {text, highlight} objects.
17374    fn copy_highlight_json(
17375        &mut self,
17376        _: &CopyHighlightJson,
17377        window: &mut Window,
17378        cx: &mut Context<Self>,
17379    ) {
17380        #[derive(Serialize)]
17381        struct Chunk<'a> {
17382            text: String,
17383            highlight: Option<&'a str>,
17384        }
17385
17386        let snapshot = self.buffer.read(cx).snapshot(cx);
17387        let range = self
17388            .selected_text_range(false, window, cx)
17389            .and_then(|selection| {
17390                if selection.range.is_empty() {
17391                    None
17392                } else {
17393                    Some(selection.range)
17394                }
17395            })
17396            .unwrap_or_else(|| 0..snapshot.len());
17397
17398        let chunks = snapshot.chunks(range, true);
17399        let mut lines = Vec::new();
17400        let mut line: VecDeque<Chunk> = VecDeque::new();
17401
17402        let Some(style) = self.style.as_ref() else {
17403            return;
17404        };
17405
17406        for chunk in chunks {
17407            let highlight = chunk
17408                .syntax_highlight_id
17409                .and_then(|id| id.name(&style.syntax));
17410            let mut chunk_lines = chunk.text.split('\n').peekable();
17411            while let Some(text) = chunk_lines.next() {
17412                let mut merged_with_last_token = false;
17413                if let Some(last_token) = line.back_mut() {
17414                    if last_token.highlight == highlight {
17415                        last_token.text.push_str(text);
17416                        merged_with_last_token = true;
17417                    }
17418                }
17419
17420                if !merged_with_last_token {
17421                    line.push_back(Chunk {
17422                        text: text.into(),
17423                        highlight,
17424                    });
17425                }
17426
17427                if chunk_lines.peek().is_some() {
17428                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17429                        line.pop_front();
17430                    }
17431                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17432                        line.pop_back();
17433                    }
17434
17435                    lines.push(mem::take(&mut line));
17436                }
17437            }
17438        }
17439
17440        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17441            return;
17442        };
17443        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17444    }
17445
17446    pub fn open_context_menu(
17447        &mut self,
17448        _: &OpenContextMenu,
17449        window: &mut Window,
17450        cx: &mut Context<Self>,
17451    ) {
17452        self.request_autoscroll(Autoscroll::newest(), cx);
17453        let position = self.selections.newest_display(cx).start;
17454        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17455    }
17456
17457    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17458        &self.inlay_hint_cache
17459    }
17460
17461    pub fn replay_insert_event(
17462        &mut self,
17463        text: &str,
17464        relative_utf16_range: Option<Range<isize>>,
17465        window: &mut Window,
17466        cx: &mut Context<Self>,
17467    ) {
17468        if !self.input_enabled {
17469            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17470            return;
17471        }
17472        if let Some(relative_utf16_range) = relative_utf16_range {
17473            let selections = self.selections.all::<OffsetUtf16>(cx);
17474            self.change_selections(None, window, cx, |s| {
17475                let new_ranges = selections.into_iter().map(|range| {
17476                    let start = OffsetUtf16(
17477                        range
17478                            .head()
17479                            .0
17480                            .saturating_add_signed(relative_utf16_range.start),
17481                    );
17482                    let end = OffsetUtf16(
17483                        range
17484                            .head()
17485                            .0
17486                            .saturating_add_signed(relative_utf16_range.end),
17487                    );
17488                    start..end
17489                });
17490                s.select_ranges(new_ranges);
17491            });
17492        }
17493
17494        self.handle_input(text, window, cx);
17495    }
17496
17497    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17498        let Some(provider) = self.semantics_provider.as_ref() else {
17499            return false;
17500        };
17501
17502        let mut supports = false;
17503        self.buffer().update(cx, |this, cx| {
17504            this.for_each_buffer(|buffer| {
17505                supports |= provider.supports_inlay_hints(buffer, cx);
17506            });
17507        });
17508
17509        supports
17510    }
17511
17512    pub fn is_focused(&self, window: &Window) -> bool {
17513        self.focus_handle.is_focused(window)
17514    }
17515
17516    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17517        cx.emit(EditorEvent::Focused);
17518
17519        if let Some(descendant) = self
17520            .last_focused_descendant
17521            .take()
17522            .and_then(|descendant| descendant.upgrade())
17523        {
17524            window.focus(&descendant);
17525        } else {
17526            if let Some(blame) = self.blame.as_ref() {
17527                blame.update(cx, GitBlame::focus)
17528            }
17529
17530            self.blink_manager.update(cx, BlinkManager::enable);
17531            self.show_cursor_names(window, cx);
17532            self.buffer.update(cx, |buffer, cx| {
17533                buffer.finalize_last_transaction(cx);
17534                if self.leader_peer_id.is_none() {
17535                    buffer.set_active_selections(
17536                        &self.selections.disjoint_anchors(),
17537                        self.selections.line_mode,
17538                        self.cursor_shape,
17539                        cx,
17540                    );
17541                }
17542            });
17543        }
17544    }
17545
17546    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17547        cx.emit(EditorEvent::FocusedIn)
17548    }
17549
17550    fn handle_focus_out(
17551        &mut self,
17552        event: FocusOutEvent,
17553        _window: &mut Window,
17554        cx: &mut Context<Self>,
17555    ) {
17556        if event.blurred != self.focus_handle {
17557            self.last_focused_descendant = Some(event.blurred);
17558        }
17559        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17560    }
17561
17562    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17563        self.blink_manager.update(cx, BlinkManager::disable);
17564        self.buffer
17565            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17566
17567        if let Some(blame) = self.blame.as_ref() {
17568            blame.update(cx, GitBlame::blur)
17569        }
17570        if !self.hover_state.focused(window, cx) {
17571            hide_hover(self, cx);
17572        }
17573        if !self
17574            .context_menu
17575            .borrow()
17576            .as_ref()
17577            .is_some_and(|context_menu| context_menu.focused(window, cx))
17578        {
17579            self.hide_context_menu(window, cx);
17580        }
17581        self.discard_inline_completion(false, cx);
17582        cx.emit(EditorEvent::Blurred);
17583        cx.notify();
17584    }
17585
17586    pub fn register_action<A: Action>(
17587        &mut self,
17588        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17589    ) -> Subscription {
17590        let id = self.next_editor_action_id.post_inc();
17591        let listener = Arc::new(listener);
17592        self.editor_actions.borrow_mut().insert(
17593            id,
17594            Box::new(move |window, _| {
17595                let listener = listener.clone();
17596                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17597                    let action = action.downcast_ref().unwrap();
17598                    if phase == DispatchPhase::Bubble {
17599                        listener(action, window, cx)
17600                    }
17601                })
17602            }),
17603        );
17604
17605        let editor_actions = self.editor_actions.clone();
17606        Subscription::new(move || {
17607            editor_actions.borrow_mut().remove(&id);
17608        })
17609    }
17610
17611    pub fn file_header_size(&self) -> u32 {
17612        FILE_HEADER_HEIGHT
17613    }
17614
17615    pub fn restore(
17616        &mut self,
17617        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17618        window: &mut Window,
17619        cx: &mut Context<Self>,
17620    ) {
17621        let workspace = self.workspace();
17622        let project = self.project.as_ref();
17623        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17624            let mut tasks = Vec::new();
17625            for (buffer_id, changes) in revert_changes {
17626                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17627                    buffer.update(cx, |buffer, cx| {
17628                        buffer.edit(
17629                            changes
17630                                .into_iter()
17631                                .map(|(range, text)| (range, text.to_string())),
17632                            None,
17633                            cx,
17634                        );
17635                    });
17636
17637                    if let Some(project) =
17638                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17639                    {
17640                        project.update(cx, |project, cx| {
17641                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17642                        })
17643                    }
17644                }
17645            }
17646            tasks
17647        });
17648        cx.spawn_in(window, async move |_, cx| {
17649            for (buffer, task) in save_tasks {
17650                let result = task.await;
17651                if result.is_err() {
17652                    let Some(path) = buffer
17653                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
17654                        .ok()
17655                    else {
17656                        continue;
17657                    };
17658                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17659                        let Some(task) = cx
17660                            .update_window_entity(&workspace, |workspace, window, cx| {
17661                                workspace
17662                                    .open_path_preview(path, None, false, false, false, window, cx)
17663                            })
17664                            .ok()
17665                        else {
17666                            continue;
17667                        };
17668                        task.await.log_err();
17669                    }
17670                }
17671            }
17672        })
17673        .detach();
17674        self.change_selections(None, window, cx, |selections| selections.refresh());
17675    }
17676
17677    pub fn to_pixel_point(
17678        &self,
17679        source: multi_buffer::Anchor,
17680        editor_snapshot: &EditorSnapshot,
17681        window: &mut Window,
17682    ) -> Option<gpui::Point<Pixels>> {
17683        let source_point = source.to_display_point(editor_snapshot);
17684        self.display_to_pixel_point(source_point, editor_snapshot, window)
17685    }
17686
17687    pub fn display_to_pixel_point(
17688        &self,
17689        source: DisplayPoint,
17690        editor_snapshot: &EditorSnapshot,
17691        window: &mut Window,
17692    ) -> Option<gpui::Point<Pixels>> {
17693        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17694        let text_layout_details = self.text_layout_details(window);
17695        let scroll_top = text_layout_details
17696            .scroll_anchor
17697            .scroll_position(editor_snapshot)
17698            .y;
17699
17700        if source.row().as_f32() < scroll_top.floor() {
17701            return None;
17702        }
17703        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17704        let source_y = line_height * (source.row().as_f32() - scroll_top);
17705        Some(gpui::Point::new(source_x, source_y))
17706    }
17707
17708    pub fn has_visible_completions_menu(&self) -> bool {
17709        !self.edit_prediction_preview_is_active()
17710            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17711                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17712            })
17713    }
17714
17715    pub fn register_addon<T: Addon>(&mut self, instance: T) {
17716        self.addons
17717            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17718    }
17719
17720    pub fn unregister_addon<T: Addon>(&mut self) {
17721        self.addons.remove(&std::any::TypeId::of::<T>());
17722    }
17723
17724    pub fn addon<T: Addon>(&self) -> Option<&T> {
17725        let type_id = std::any::TypeId::of::<T>();
17726        self.addons
17727            .get(&type_id)
17728            .and_then(|item| item.to_any().downcast_ref::<T>())
17729    }
17730
17731    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17732        let text_layout_details = self.text_layout_details(window);
17733        let style = &text_layout_details.editor_style;
17734        let font_id = window.text_system().resolve_font(&style.text.font());
17735        let font_size = style.text.font_size.to_pixels(window.rem_size());
17736        let line_height = style.text.line_height_in_pixels(window.rem_size());
17737        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17738
17739        gpui::Size::new(em_width, line_height)
17740    }
17741
17742    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17743        self.load_diff_task.clone()
17744    }
17745
17746    fn read_metadata_from_db(
17747        &mut self,
17748        item_id: u64,
17749        workspace_id: WorkspaceId,
17750        window: &mut Window,
17751        cx: &mut Context<Editor>,
17752    ) {
17753        if self.is_singleton(cx)
17754            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17755        {
17756            let buffer_snapshot = OnceCell::new();
17757
17758            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17759                if !folds.is_empty() {
17760                    let snapshot =
17761                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17762                    self.fold_ranges(
17763                        folds
17764                            .into_iter()
17765                            .map(|(start, end)| {
17766                                snapshot.clip_offset(start, Bias::Left)
17767                                    ..snapshot.clip_offset(end, Bias::Right)
17768                            })
17769                            .collect(),
17770                        false,
17771                        window,
17772                        cx,
17773                    );
17774                }
17775            }
17776
17777            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17778                if !selections.is_empty() {
17779                    let snapshot =
17780                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17781                    self.change_selections(None, window, cx, |s| {
17782                        s.select_ranges(selections.into_iter().map(|(start, end)| {
17783                            snapshot.clip_offset(start, Bias::Left)
17784                                ..snapshot.clip_offset(end, Bias::Right)
17785                        }));
17786                    });
17787                }
17788            };
17789        }
17790
17791        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17792    }
17793}
17794
17795fn insert_extra_newline_brackets(
17796    buffer: &MultiBufferSnapshot,
17797    range: Range<usize>,
17798    language: &language::LanguageScope,
17799) -> bool {
17800    let leading_whitespace_len = buffer
17801        .reversed_chars_at(range.start)
17802        .take_while(|c| c.is_whitespace() && *c != '\n')
17803        .map(|c| c.len_utf8())
17804        .sum::<usize>();
17805    let trailing_whitespace_len = buffer
17806        .chars_at(range.end)
17807        .take_while(|c| c.is_whitespace() && *c != '\n')
17808        .map(|c| c.len_utf8())
17809        .sum::<usize>();
17810    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17811
17812    language.brackets().any(|(pair, enabled)| {
17813        let pair_start = pair.start.trim_end();
17814        let pair_end = pair.end.trim_start();
17815
17816        enabled
17817            && pair.newline
17818            && buffer.contains_str_at(range.end, pair_end)
17819            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17820    })
17821}
17822
17823fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17824    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17825        [(buffer, range, _)] => (*buffer, range.clone()),
17826        _ => return false,
17827    };
17828    let pair = {
17829        let mut result: Option<BracketMatch> = None;
17830
17831        for pair in buffer
17832            .all_bracket_ranges(range.clone())
17833            .filter(move |pair| {
17834                pair.open_range.start <= range.start && pair.close_range.end >= range.end
17835            })
17836        {
17837            let len = pair.close_range.end - pair.open_range.start;
17838
17839            if let Some(existing) = &result {
17840                let existing_len = existing.close_range.end - existing.open_range.start;
17841                if len > existing_len {
17842                    continue;
17843                }
17844            }
17845
17846            result = Some(pair);
17847        }
17848
17849        result
17850    };
17851    let Some(pair) = pair else {
17852        return false;
17853    };
17854    pair.newline_only
17855        && buffer
17856            .chars_for_range(pair.open_range.end..range.start)
17857            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17858            .all(|c| c.is_whitespace() && c != '\n')
17859}
17860
17861fn get_uncommitted_diff_for_buffer(
17862    project: &Entity<Project>,
17863    buffers: impl IntoIterator<Item = Entity<Buffer>>,
17864    buffer: Entity<MultiBuffer>,
17865    cx: &mut App,
17866) -> Task<()> {
17867    let mut tasks = Vec::new();
17868    project.update(cx, |project, cx| {
17869        for buffer in buffers {
17870            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
17871                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17872            }
17873        }
17874    });
17875    cx.spawn(async move |cx| {
17876        let diffs = future::join_all(tasks).await;
17877        buffer
17878            .update(cx, |buffer, cx| {
17879                for diff in diffs.into_iter().flatten() {
17880                    buffer.add_diff(diff, cx);
17881                }
17882            })
17883            .ok();
17884    })
17885}
17886
17887fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17888    let tab_size = tab_size.get() as usize;
17889    let mut width = offset;
17890
17891    for ch in text.chars() {
17892        width += if ch == '\t' {
17893            tab_size - (width % tab_size)
17894        } else {
17895            1
17896        };
17897    }
17898
17899    width - offset
17900}
17901
17902#[cfg(test)]
17903mod tests {
17904    use super::*;
17905
17906    #[test]
17907    fn test_string_size_with_expanded_tabs() {
17908        let nz = |val| NonZeroU32::new(val).unwrap();
17909        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17910        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17911        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17912        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17913        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17914        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17915        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17916        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17917    }
17918}
17919
17920/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17921struct WordBreakingTokenizer<'a> {
17922    input: &'a str,
17923}
17924
17925impl<'a> WordBreakingTokenizer<'a> {
17926    fn new(input: &'a str) -> Self {
17927        Self { input }
17928    }
17929}
17930
17931fn is_char_ideographic(ch: char) -> bool {
17932    use unicode_script::Script::*;
17933    use unicode_script::UnicodeScript;
17934    matches!(ch.script(), Han | Tangut | Yi)
17935}
17936
17937fn is_grapheme_ideographic(text: &str) -> bool {
17938    text.chars().any(is_char_ideographic)
17939}
17940
17941fn is_grapheme_whitespace(text: &str) -> bool {
17942    text.chars().any(|x| x.is_whitespace())
17943}
17944
17945fn should_stay_with_preceding_ideograph(text: &str) -> bool {
17946    text.chars().next().map_or(false, |ch| {
17947        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
17948    })
17949}
17950
17951#[derive(PartialEq, Eq, Debug, Clone, Copy)]
17952enum WordBreakToken<'a> {
17953    Word { token: &'a str, grapheme_len: usize },
17954    InlineWhitespace { token: &'a str, grapheme_len: usize },
17955    Newline,
17956}
17957
17958impl<'a> Iterator for WordBreakingTokenizer<'a> {
17959    /// Yields a span, the count of graphemes in the token, and whether it was
17960    /// whitespace. Note that it also breaks at word boundaries.
17961    type Item = WordBreakToken<'a>;
17962
17963    fn next(&mut self) -> Option<Self::Item> {
17964        use unicode_segmentation::UnicodeSegmentation;
17965        if self.input.is_empty() {
17966            return None;
17967        }
17968
17969        let mut iter = self.input.graphemes(true).peekable();
17970        let mut offset = 0;
17971        let mut grapheme_len = 0;
17972        if let Some(first_grapheme) = iter.next() {
17973            let is_newline = first_grapheme == "\n";
17974            let is_whitespace = is_grapheme_whitespace(first_grapheme);
17975            offset += first_grapheme.len();
17976            grapheme_len += 1;
17977            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
17978                if let Some(grapheme) = iter.peek().copied() {
17979                    if should_stay_with_preceding_ideograph(grapheme) {
17980                        offset += grapheme.len();
17981                        grapheme_len += 1;
17982                    }
17983                }
17984            } else {
17985                let mut words = self.input[offset..].split_word_bound_indices().peekable();
17986                let mut next_word_bound = words.peek().copied();
17987                if next_word_bound.map_or(false, |(i, _)| i == 0) {
17988                    next_word_bound = words.next();
17989                }
17990                while let Some(grapheme) = iter.peek().copied() {
17991                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
17992                        break;
17993                    };
17994                    if is_grapheme_whitespace(grapheme) != is_whitespace
17995                        || (grapheme == "\n") != is_newline
17996                    {
17997                        break;
17998                    };
17999                    offset += grapheme.len();
18000                    grapheme_len += 1;
18001                    iter.next();
18002                }
18003            }
18004            let token = &self.input[..offset];
18005            self.input = &self.input[offset..];
18006            if token == "\n" {
18007                Some(WordBreakToken::Newline)
18008            } else if is_whitespace {
18009                Some(WordBreakToken::InlineWhitespace {
18010                    token,
18011                    grapheme_len,
18012                })
18013            } else {
18014                Some(WordBreakToken::Word {
18015                    token,
18016                    grapheme_len,
18017                })
18018            }
18019        } else {
18020            None
18021        }
18022    }
18023}
18024
18025#[test]
18026fn test_word_breaking_tokenizer() {
18027    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18028        ("", &[]),
18029        ("  ", &[whitespace("  ", 2)]),
18030        ("Ʒ", &[word("Ʒ", 1)]),
18031        ("Ǽ", &[word("Ǽ", 1)]),
18032        ("", &[word("", 1)]),
18033        ("⋑⋑", &[word("⋑⋑", 2)]),
18034        (
18035            "原理,进而",
18036            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18037        ),
18038        (
18039            "hello world",
18040            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18041        ),
18042        (
18043            "hello, world",
18044            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18045        ),
18046        (
18047            "  hello world",
18048            &[
18049                whitespace("  ", 2),
18050                word("hello", 5),
18051                whitespace(" ", 1),
18052                word("world", 5),
18053            ],
18054        ),
18055        (
18056            "这是什么 \n 钢笔",
18057            &[
18058                word("", 1),
18059                word("", 1),
18060                word("", 1),
18061                word("", 1),
18062                whitespace(" ", 1),
18063                newline(),
18064                whitespace(" ", 1),
18065                word("", 1),
18066                word("", 1),
18067            ],
18068        ),
18069        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18070    ];
18071
18072    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18073        WordBreakToken::Word {
18074            token,
18075            grapheme_len,
18076        }
18077    }
18078
18079    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18080        WordBreakToken::InlineWhitespace {
18081            token,
18082            grapheme_len,
18083        }
18084    }
18085
18086    fn newline() -> WordBreakToken<'static> {
18087        WordBreakToken::Newline
18088    }
18089
18090    for (input, result) in tests {
18091        assert_eq!(
18092            WordBreakingTokenizer::new(input)
18093                .collect::<Vec<_>>()
18094                .as_slice(),
18095            *result,
18096        );
18097    }
18098}
18099
18100fn wrap_with_prefix(
18101    line_prefix: String,
18102    unwrapped_text: String,
18103    wrap_column: usize,
18104    tab_size: NonZeroU32,
18105    preserve_existing_whitespace: bool,
18106) -> String {
18107    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18108    let mut wrapped_text = String::new();
18109    let mut current_line = line_prefix.clone();
18110
18111    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18112    let mut current_line_len = line_prefix_len;
18113    let mut in_whitespace = false;
18114    for token in tokenizer {
18115        let have_preceding_whitespace = in_whitespace;
18116        match token {
18117            WordBreakToken::Word {
18118                token,
18119                grapheme_len,
18120            } => {
18121                in_whitespace = false;
18122                if current_line_len + grapheme_len > wrap_column
18123                    && current_line_len != line_prefix_len
18124                {
18125                    wrapped_text.push_str(current_line.trim_end());
18126                    wrapped_text.push('\n');
18127                    current_line.truncate(line_prefix.len());
18128                    current_line_len = line_prefix_len;
18129                }
18130                current_line.push_str(token);
18131                current_line_len += grapheme_len;
18132            }
18133            WordBreakToken::InlineWhitespace {
18134                mut token,
18135                mut grapheme_len,
18136            } => {
18137                in_whitespace = true;
18138                if have_preceding_whitespace && !preserve_existing_whitespace {
18139                    continue;
18140                }
18141                if !preserve_existing_whitespace {
18142                    token = " ";
18143                    grapheme_len = 1;
18144                }
18145                if current_line_len + grapheme_len > wrap_column {
18146                    wrapped_text.push_str(current_line.trim_end());
18147                    wrapped_text.push('\n');
18148                    current_line.truncate(line_prefix.len());
18149                    current_line_len = line_prefix_len;
18150                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18151                    current_line.push_str(token);
18152                    current_line_len += grapheme_len;
18153                }
18154            }
18155            WordBreakToken::Newline => {
18156                in_whitespace = true;
18157                if preserve_existing_whitespace {
18158                    wrapped_text.push_str(current_line.trim_end());
18159                    wrapped_text.push('\n');
18160                    current_line.truncate(line_prefix.len());
18161                    current_line_len = line_prefix_len;
18162                } else if have_preceding_whitespace {
18163                    continue;
18164                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18165                {
18166                    wrapped_text.push_str(current_line.trim_end());
18167                    wrapped_text.push('\n');
18168                    current_line.truncate(line_prefix.len());
18169                    current_line_len = line_prefix_len;
18170                } else if current_line_len != line_prefix_len {
18171                    current_line.push(' ');
18172                    current_line_len += 1;
18173                }
18174            }
18175        }
18176    }
18177
18178    if !current_line.is_empty() {
18179        wrapped_text.push_str(&current_line);
18180    }
18181    wrapped_text
18182}
18183
18184#[test]
18185fn test_wrap_with_prefix() {
18186    assert_eq!(
18187        wrap_with_prefix(
18188            "# ".to_string(),
18189            "abcdefg".to_string(),
18190            4,
18191            NonZeroU32::new(4).unwrap(),
18192            false,
18193        ),
18194        "# abcdefg"
18195    );
18196    assert_eq!(
18197        wrap_with_prefix(
18198            "".to_string(),
18199            "\thello world".to_string(),
18200            8,
18201            NonZeroU32::new(4).unwrap(),
18202            false,
18203        ),
18204        "hello\nworld"
18205    );
18206    assert_eq!(
18207        wrap_with_prefix(
18208            "// ".to_string(),
18209            "xx \nyy zz aa bb cc".to_string(),
18210            12,
18211            NonZeroU32::new(4).unwrap(),
18212            false,
18213        ),
18214        "// xx yy zz\n// aa bb cc"
18215    );
18216    assert_eq!(
18217        wrap_with_prefix(
18218            String::new(),
18219            "这是什么 \n 钢笔".to_string(),
18220            3,
18221            NonZeroU32::new(4).unwrap(),
18222            false,
18223        ),
18224        "这是什\n么 钢\n"
18225    );
18226}
18227
18228pub trait CollaborationHub {
18229    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18230    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18231    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18232}
18233
18234impl CollaborationHub for Entity<Project> {
18235    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18236        self.read(cx).collaborators()
18237    }
18238
18239    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18240        self.read(cx).user_store().read(cx).participant_indices()
18241    }
18242
18243    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18244        let this = self.read(cx);
18245        let user_ids = this.collaborators().values().map(|c| c.user_id);
18246        this.user_store().read_with(cx, |user_store, cx| {
18247            user_store.participant_names(user_ids, cx)
18248        })
18249    }
18250}
18251
18252pub trait SemanticsProvider {
18253    fn hover(
18254        &self,
18255        buffer: &Entity<Buffer>,
18256        position: text::Anchor,
18257        cx: &mut App,
18258    ) -> Option<Task<Vec<project::Hover>>>;
18259
18260    fn inlay_hints(
18261        &self,
18262        buffer_handle: Entity<Buffer>,
18263        range: Range<text::Anchor>,
18264        cx: &mut App,
18265    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18266
18267    fn resolve_inlay_hint(
18268        &self,
18269        hint: InlayHint,
18270        buffer_handle: Entity<Buffer>,
18271        server_id: LanguageServerId,
18272        cx: &mut App,
18273    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18274
18275    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18276
18277    fn document_highlights(
18278        &self,
18279        buffer: &Entity<Buffer>,
18280        position: text::Anchor,
18281        cx: &mut App,
18282    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18283
18284    fn definitions(
18285        &self,
18286        buffer: &Entity<Buffer>,
18287        position: text::Anchor,
18288        kind: GotoDefinitionKind,
18289        cx: &mut App,
18290    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18291
18292    fn range_for_rename(
18293        &self,
18294        buffer: &Entity<Buffer>,
18295        position: text::Anchor,
18296        cx: &mut App,
18297    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18298
18299    fn perform_rename(
18300        &self,
18301        buffer: &Entity<Buffer>,
18302        position: text::Anchor,
18303        new_name: String,
18304        cx: &mut App,
18305    ) -> Option<Task<Result<ProjectTransaction>>>;
18306}
18307
18308pub trait CompletionProvider {
18309    fn completions(
18310        &self,
18311        excerpt_id: ExcerptId,
18312        buffer: &Entity<Buffer>,
18313        buffer_position: text::Anchor,
18314        trigger: CompletionContext,
18315        window: &mut Window,
18316        cx: &mut Context<Editor>,
18317    ) -> Task<Result<Option<Vec<Completion>>>>;
18318
18319    fn resolve_completions(
18320        &self,
18321        buffer: Entity<Buffer>,
18322        completion_indices: Vec<usize>,
18323        completions: Rc<RefCell<Box<[Completion]>>>,
18324        cx: &mut Context<Editor>,
18325    ) -> Task<Result<bool>>;
18326
18327    fn apply_additional_edits_for_completion(
18328        &self,
18329        _buffer: Entity<Buffer>,
18330        _completions: Rc<RefCell<Box<[Completion]>>>,
18331        _completion_index: usize,
18332        _push_to_history: bool,
18333        _cx: &mut Context<Editor>,
18334    ) -> Task<Result<Option<language::Transaction>>> {
18335        Task::ready(Ok(None))
18336    }
18337
18338    fn is_completion_trigger(
18339        &self,
18340        buffer: &Entity<Buffer>,
18341        position: language::Anchor,
18342        text: &str,
18343        trigger_in_words: bool,
18344        cx: &mut Context<Editor>,
18345    ) -> bool;
18346
18347    fn sort_completions(&self) -> bool {
18348        true
18349    }
18350
18351    fn filter_completions(&self) -> bool {
18352        true
18353    }
18354}
18355
18356pub trait CodeActionProvider {
18357    fn id(&self) -> Arc<str>;
18358
18359    fn code_actions(
18360        &self,
18361        buffer: &Entity<Buffer>,
18362        range: Range<text::Anchor>,
18363        window: &mut Window,
18364        cx: &mut App,
18365    ) -> Task<Result<Vec<CodeAction>>>;
18366
18367    fn apply_code_action(
18368        &self,
18369        buffer_handle: Entity<Buffer>,
18370        action: CodeAction,
18371        excerpt_id: ExcerptId,
18372        push_to_history: bool,
18373        window: &mut Window,
18374        cx: &mut App,
18375    ) -> Task<Result<ProjectTransaction>>;
18376}
18377
18378impl CodeActionProvider for Entity<Project> {
18379    fn id(&self) -> Arc<str> {
18380        "project".into()
18381    }
18382
18383    fn code_actions(
18384        &self,
18385        buffer: &Entity<Buffer>,
18386        range: Range<text::Anchor>,
18387        _window: &mut Window,
18388        cx: &mut App,
18389    ) -> Task<Result<Vec<CodeAction>>> {
18390        self.update(cx, |project, cx| {
18391            let code_lens = project.code_lens(buffer, range.clone(), cx);
18392            let code_actions = project.code_actions(buffer, range, None, cx);
18393            cx.background_spawn(async move {
18394                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18395                Ok(code_lens
18396                    .context("code lens fetch")?
18397                    .into_iter()
18398                    .chain(code_actions.context("code action fetch")?)
18399                    .collect())
18400            })
18401        })
18402    }
18403
18404    fn apply_code_action(
18405        &self,
18406        buffer_handle: Entity<Buffer>,
18407        action: CodeAction,
18408        _excerpt_id: ExcerptId,
18409        push_to_history: bool,
18410        _window: &mut Window,
18411        cx: &mut App,
18412    ) -> Task<Result<ProjectTransaction>> {
18413        self.update(cx, |project, cx| {
18414            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18415        })
18416    }
18417}
18418
18419fn snippet_completions(
18420    project: &Project,
18421    buffer: &Entity<Buffer>,
18422    buffer_position: text::Anchor,
18423    cx: &mut App,
18424) -> Task<Result<Vec<Completion>>> {
18425    let language = buffer.read(cx).language_at(buffer_position);
18426    let language_name = language.as_ref().map(|language| language.lsp_id());
18427    let snippet_store = project.snippets().read(cx);
18428    let snippets = snippet_store.snippets_for(language_name, cx);
18429
18430    if snippets.is_empty() {
18431        return Task::ready(Ok(vec![]));
18432    }
18433    let snapshot = buffer.read(cx).text_snapshot();
18434    let chars: String = snapshot
18435        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18436        .collect();
18437
18438    let scope = language.map(|language| language.default_scope());
18439    let executor = cx.background_executor().clone();
18440
18441    cx.background_spawn(async move {
18442        let classifier = CharClassifier::new(scope).for_completion(true);
18443        let mut last_word = chars
18444            .chars()
18445            .take_while(|c| classifier.is_word(*c))
18446            .collect::<String>();
18447        last_word = last_word.chars().rev().collect();
18448
18449        if last_word.is_empty() {
18450            return Ok(vec![]);
18451        }
18452
18453        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18454        let to_lsp = |point: &text::Anchor| {
18455            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18456            point_to_lsp(end)
18457        };
18458        let lsp_end = to_lsp(&buffer_position);
18459
18460        let candidates = snippets
18461            .iter()
18462            .enumerate()
18463            .flat_map(|(ix, snippet)| {
18464                snippet
18465                    .prefix
18466                    .iter()
18467                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18468            })
18469            .collect::<Vec<StringMatchCandidate>>();
18470
18471        let mut matches = fuzzy::match_strings(
18472            &candidates,
18473            &last_word,
18474            last_word.chars().any(|c| c.is_uppercase()),
18475            100,
18476            &Default::default(),
18477            executor,
18478        )
18479        .await;
18480
18481        // Remove all candidates where the query's start does not match the start of any word in the candidate
18482        if let Some(query_start) = last_word.chars().next() {
18483            matches.retain(|string_match| {
18484                split_words(&string_match.string).any(|word| {
18485                    // Check that the first codepoint of the word as lowercase matches the first
18486                    // codepoint of the query as lowercase
18487                    word.chars()
18488                        .flat_map(|codepoint| codepoint.to_lowercase())
18489                        .zip(query_start.to_lowercase())
18490                        .all(|(word_cp, query_cp)| word_cp == query_cp)
18491                })
18492            });
18493        }
18494
18495        let matched_strings = matches
18496            .into_iter()
18497            .map(|m| m.string)
18498            .collect::<HashSet<_>>();
18499
18500        let result: Vec<Completion> = snippets
18501            .into_iter()
18502            .filter_map(|snippet| {
18503                let matching_prefix = snippet
18504                    .prefix
18505                    .iter()
18506                    .find(|prefix| matched_strings.contains(*prefix))?;
18507                let start = as_offset - last_word.len();
18508                let start = snapshot.anchor_before(start);
18509                let range = start..buffer_position;
18510                let lsp_start = to_lsp(&start);
18511                let lsp_range = lsp::Range {
18512                    start: lsp_start,
18513                    end: lsp_end,
18514                };
18515                Some(Completion {
18516                    old_range: range,
18517                    new_text: snippet.body.clone(),
18518                    source: CompletionSource::Lsp {
18519                        server_id: LanguageServerId(usize::MAX),
18520                        resolved: true,
18521                        lsp_completion: Box::new(lsp::CompletionItem {
18522                            label: snippet.prefix.first().unwrap().clone(),
18523                            kind: Some(CompletionItemKind::SNIPPET),
18524                            label_details: snippet.description.as_ref().map(|description| {
18525                                lsp::CompletionItemLabelDetails {
18526                                    detail: Some(description.clone()),
18527                                    description: None,
18528                                }
18529                            }),
18530                            insert_text_format: Some(InsertTextFormat::SNIPPET),
18531                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18532                                lsp::InsertReplaceEdit {
18533                                    new_text: snippet.body.clone(),
18534                                    insert: lsp_range,
18535                                    replace: lsp_range,
18536                                },
18537                            )),
18538                            filter_text: Some(snippet.body.clone()),
18539                            sort_text: Some(char::MAX.to_string()),
18540                            ..lsp::CompletionItem::default()
18541                        }),
18542                        lsp_defaults: None,
18543                    },
18544                    label: CodeLabel {
18545                        text: matching_prefix.clone(),
18546                        runs: Vec::new(),
18547                        filter_range: 0..matching_prefix.len(),
18548                    },
18549                    icon_path: None,
18550                    documentation: snippet
18551                        .description
18552                        .clone()
18553                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
18554                    confirm: None,
18555                })
18556            })
18557            .collect();
18558
18559        Ok(result)
18560    })
18561}
18562
18563impl CompletionProvider for Entity<Project> {
18564    fn completions(
18565        &self,
18566        _excerpt_id: ExcerptId,
18567        buffer: &Entity<Buffer>,
18568        buffer_position: text::Anchor,
18569        options: CompletionContext,
18570        _window: &mut Window,
18571        cx: &mut Context<Editor>,
18572    ) -> Task<Result<Option<Vec<Completion>>>> {
18573        self.update(cx, |project, cx| {
18574            let snippets = snippet_completions(project, buffer, buffer_position, cx);
18575            let project_completions = project.completions(buffer, buffer_position, options, cx);
18576            cx.background_spawn(async move {
18577                let snippets_completions = snippets.await?;
18578                match project_completions.await? {
18579                    Some(mut completions) => {
18580                        completions.extend(snippets_completions);
18581                        Ok(Some(completions))
18582                    }
18583                    None => {
18584                        if snippets_completions.is_empty() {
18585                            Ok(None)
18586                        } else {
18587                            Ok(Some(snippets_completions))
18588                        }
18589                    }
18590                }
18591            })
18592        })
18593    }
18594
18595    fn resolve_completions(
18596        &self,
18597        buffer: Entity<Buffer>,
18598        completion_indices: Vec<usize>,
18599        completions: Rc<RefCell<Box<[Completion]>>>,
18600        cx: &mut Context<Editor>,
18601    ) -> Task<Result<bool>> {
18602        self.update(cx, |project, cx| {
18603            project.lsp_store().update(cx, |lsp_store, cx| {
18604                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18605            })
18606        })
18607    }
18608
18609    fn apply_additional_edits_for_completion(
18610        &self,
18611        buffer: Entity<Buffer>,
18612        completions: Rc<RefCell<Box<[Completion]>>>,
18613        completion_index: usize,
18614        push_to_history: bool,
18615        cx: &mut Context<Editor>,
18616    ) -> Task<Result<Option<language::Transaction>>> {
18617        self.update(cx, |project, cx| {
18618            project.lsp_store().update(cx, |lsp_store, cx| {
18619                lsp_store.apply_additional_edits_for_completion(
18620                    buffer,
18621                    completions,
18622                    completion_index,
18623                    push_to_history,
18624                    cx,
18625                )
18626            })
18627        })
18628    }
18629
18630    fn is_completion_trigger(
18631        &self,
18632        buffer: &Entity<Buffer>,
18633        position: language::Anchor,
18634        text: &str,
18635        trigger_in_words: bool,
18636        cx: &mut Context<Editor>,
18637    ) -> bool {
18638        let mut chars = text.chars();
18639        let char = if let Some(char) = chars.next() {
18640            char
18641        } else {
18642            return false;
18643        };
18644        if chars.next().is_some() {
18645            return false;
18646        }
18647
18648        let buffer = buffer.read(cx);
18649        let snapshot = buffer.snapshot();
18650        if !snapshot.settings_at(position, cx).show_completions_on_input {
18651            return false;
18652        }
18653        let classifier = snapshot.char_classifier_at(position).for_completion(true);
18654        if trigger_in_words && classifier.is_word(char) {
18655            return true;
18656        }
18657
18658        buffer.completion_triggers().contains(text)
18659    }
18660}
18661
18662impl SemanticsProvider for Entity<Project> {
18663    fn hover(
18664        &self,
18665        buffer: &Entity<Buffer>,
18666        position: text::Anchor,
18667        cx: &mut App,
18668    ) -> Option<Task<Vec<project::Hover>>> {
18669        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18670    }
18671
18672    fn document_highlights(
18673        &self,
18674        buffer: &Entity<Buffer>,
18675        position: text::Anchor,
18676        cx: &mut App,
18677    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18678        Some(self.update(cx, |project, cx| {
18679            project.document_highlights(buffer, position, cx)
18680        }))
18681    }
18682
18683    fn definitions(
18684        &self,
18685        buffer: &Entity<Buffer>,
18686        position: text::Anchor,
18687        kind: GotoDefinitionKind,
18688        cx: &mut App,
18689    ) -> Option<Task<Result<Vec<LocationLink>>>> {
18690        Some(self.update(cx, |project, cx| match kind {
18691            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18692            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18693            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18694            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18695        }))
18696    }
18697
18698    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18699        // TODO: make this work for remote projects
18700        self.update(cx, |this, cx| {
18701            buffer.update(cx, |buffer, cx| {
18702                this.any_language_server_supports_inlay_hints(buffer, cx)
18703            })
18704        })
18705    }
18706
18707    fn inlay_hints(
18708        &self,
18709        buffer_handle: Entity<Buffer>,
18710        range: Range<text::Anchor>,
18711        cx: &mut App,
18712    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18713        Some(self.update(cx, |project, cx| {
18714            project.inlay_hints(buffer_handle, range, cx)
18715        }))
18716    }
18717
18718    fn resolve_inlay_hint(
18719        &self,
18720        hint: InlayHint,
18721        buffer_handle: Entity<Buffer>,
18722        server_id: LanguageServerId,
18723        cx: &mut App,
18724    ) -> Option<Task<anyhow::Result<InlayHint>>> {
18725        Some(self.update(cx, |project, cx| {
18726            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18727        }))
18728    }
18729
18730    fn range_for_rename(
18731        &self,
18732        buffer: &Entity<Buffer>,
18733        position: text::Anchor,
18734        cx: &mut App,
18735    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18736        Some(self.update(cx, |project, cx| {
18737            let buffer = buffer.clone();
18738            let task = project.prepare_rename(buffer.clone(), position, cx);
18739            cx.spawn(async move |_, cx| {
18740                Ok(match task.await? {
18741                    PrepareRenameResponse::Success(range) => Some(range),
18742                    PrepareRenameResponse::InvalidPosition => None,
18743                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18744                        // Fallback on using TreeSitter info to determine identifier range
18745                        buffer.update(cx, |buffer, _| {
18746                            let snapshot = buffer.snapshot();
18747                            let (range, kind) = snapshot.surrounding_word(position);
18748                            if kind != Some(CharKind::Word) {
18749                                return None;
18750                            }
18751                            Some(
18752                                snapshot.anchor_before(range.start)
18753                                    ..snapshot.anchor_after(range.end),
18754                            )
18755                        })?
18756                    }
18757                })
18758            })
18759        }))
18760    }
18761
18762    fn perform_rename(
18763        &self,
18764        buffer: &Entity<Buffer>,
18765        position: text::Anchor,
18766        new_name: String,
18767        cx: &mut App,
18768    ) -> Option<Task<Result<ProjectTransaction>>> {
18769        Some(self.update(cx, |project, cx| {
18770            project.perform_rename(buffer.clone(), position, new_name, cx)
18771        }))
18772    }
18773}
18774
18775fn inlay_hint_settings(
18776    location: Anchor,
18777    snapshot: &MultiBufferSnapshot,
18778    cx: &mut Context<Editor>,
18779) -> InlayHintSettings {
18780    let file = snapshot.file_at(location);
18781    let language = snapshot.language_at(location).map(|l| l.name());
18782    language_settings(language, file, cx).inlay_hints
18783}
18784
18785fn consume_contiguous_rows(
18786    contiguous_row_selections: &mut Vec<Selection<Point>>,
18787    selection: &Selection<Point>,
18788    display_map: &DisplaySnapshot,
18789    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18790) -> (MultiBufferRow, MultiBufferRow) {
18791    contiguous_row_selections.push(selection.clone());
18792    let start_row = MultiBufferRow(selection.start.row);
18793    let mut end_row = ending_row(selection, display_map);
18794
18795    while let Some(next_selection) = selections.peek() {
18796        if next_selection.start.row <= end_row.0 {
18797            end_row = ending_row(next_selection, display_map);
18798            contiguous_row_selections.push(selections.next().unwrap().clone());
18799        } else {
18800            break;
18801        }
18802    }
18803    (start_row, end_row)
18804}
18805
18806fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18807    if next_selection.end.column > 0 || next_selection.is_empty() {
18808        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18809    } else {
18810        MultiBufferRow(next_selection.end.row)
18811    }
18812}
18813
18814impl EditorSnapshot {
18815    pub fn remote_selections_in_range<'a>(
18816        &'a self,
18817        range: &'a Range<Anchor>,
18818        collaboration_hub: &dyn CollaborationHub,
18819        cx: &'a App,
18820    ) -> impl 'a + Iterator<Item = RemoteSelection> {
18821        let participant_names = collaboration_hub.user_names(cx);
18822        let participant_indices = collaboration_hub.user_participant_indices(cx);
18823        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18824        let collaborators_by_replica_id = collaborators_by_peer_id
18825            .iter()
18826            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18827            .collect::<HashMap<_, _>>();
18828        self.buffer_snapshot
18829            .selections_in_range(range, false)
18830            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18831                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18832                let participant_index = participant_indices.get(&collaborator.user_id).copied();
18833                let user_name = participant_names.get(&collaborator.user_id).cloned();
18834                Some(RemoteSelection {
18835                    replica_id,
18836                    selection,
18837                    cursor_shape,
18838                    line_mode,
18839                    participant_index,
18840                    peer_id: collaborator.peer_id,
18841                    user_name,
18842                })
18843            })
18844    }
18845
18846    pub fn hunks_for_ranges(
18847        &self,
18848        ranges: impl IntoIterator<Item = Range<Point>>,
18849    ) -> Vec<MultiBufferDiffHunk> {
18850        let mut hunks = Vec::new();
18851        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18852            HashMap::default();
18853        for query_range in ranges {
18854            let query_rows =
18855                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18856            for hunk in self.buffer_snapshot.diff_hunks_in_range(
18857                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18858            ) {
18859                // Include deleted hunks that are adjacent to the query range, because
18860                // otherwise they would be missed.
18861                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18862                if hunk.status().is_deleted() {
18863                    intersects_range |= hunk.row_range.start == query_rows.end;
18864                    intersects_range |= hunk.row_range.end == query_rows.start;
18865                }
18866                if intersects_range {
18867                    if !processed_buffer_rows
18868                        .entry(hunk.buffer_id)
18869                        .or_default()
18870                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18871                    {
18872                        continue;
18873                    }
18874                    hunks.push(hunk);
18875                }
18876            }
18877        }
18878
18879        hunks
18880    }
18881
18882    fn display_diff_hunks_for_rows<'a>(
18883        &'a self,
18884        display_rows: Range<DisplayRow>,
18885        folded_buffers: &'a HashSet<BufferId>,
18886    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18887        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18888        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18889
18890        self.buffer_snapshot
18891            .diff_hunks_in_range(buffer_start..buffer_end)
18892            .filter_map(|hunk| {
18893                if folded_buffers.contains(&hunk.buffer_id) {
18894                    return None;
18895                }
18896
18897                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18898                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18899
18900                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18901                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18902
18903                let display_hunk = if hunk_display_start.column() != 0 {
18904                    DisplayDiffHunk::Folded {
18905                        display_row: hunk_display_start.row(),
18906                    }
18907                } else {
18908                    let mut end_row = hunk_display_end.row();
18909                    if hunk_display_end.column() > 0 {
18910                        end_row.0 += 1;
18911                    }
18912                    let is_created_file = hunk.is_created_file();
18913                    DisplayDiffHunk::Unfolded {
18914                        status: hunk.status(),
18915                        diff_base_byte_range: hunk.diff_base_byte_range,
18916                        display_row_range: hunk_display_start.row()..end_row,
18917                        multi_buffer_range: Anchor::range_in_buffer(
18918                            hunk.excerpt_id,
18919                            hunk.buffer_id,
18920                            hunk.buffer_range,
18921                        ),
18922                        is_created_file,
18923                    }
18924                };
18925
18926                Some(display_hunk)
18927            })
18928    }
18929
18930    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18931        self.display_snapshot.buffer_snapshot.language_at(position)
18932    }
18933
18934    pub fn is_focused(&self) -> bool {
18935        self.is_focused
18936    }
18937
18938    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
18939        self.placeholder_text.as_ref()
18940    }
18941
18942    pub fn scroll_position(&self) -> gpui::Point<f32> {
18943        self.scroll_anchor.scroll_position(&self.display_snapshot)
18944    }
18945
18946    fn gutter_dimensions(
18947        &self,
18948        font_id: FontId,
18949        font_size: Pixels,
18950        max_line_number_width: Pixels,
18951        cx: &App,
18952    ) -> Option<GutterDimensions> {
18953        if !self.show_gutter {
18954            return None;
18955        }
18956
18957        let descent = cx.text_system().descent(font_id, font_size);
18958        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
18959        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
18960
18961        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
18962            matches!(
18963                ProjectSettings::get_global(cx).git.git_gutter,
18964                Some(GitGutterSetting::TrackedFiles)
18965            )
18966        });
18967        let gutter_settings = EditorSettings::get_global(cx).gutter;
18968        let show_line_numbers = self
18969            .show_line_numbers
18970            .unwrap_or(gutter_settings.line_numbers);
18971        let line_gutter_width = if show_line_numbers {
18972            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
18973            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
18974            max_line_number_width.max(min_width_for_number_on_gutter)
18975        } else {
18976            0.0.into()
18977        };
18978
18979        let show_code_actions = self
18980            .show_code_actions
18981            .unwrap_or(gutter_settings.code_actions);
18982
18983        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
18984        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
18985
18986        let git_blame_entries_width =
18987            self.git_blame_gutter_max_author_length
18988                .map(|max_author_length| {
18989                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
18990                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
18991
18992                    /// The number of characters to dedicate to gaps and margins.
18993                    const SPACING_WIDTH: usize = 4;
18994
18995                    let max_char_count = max_author_length.min(renderer.max_author_length())
18996                        + ::git::SHORT_SHA_LENGTH
18997                        + MAX_RELATIVE_TIMESTAMP.len()
18998                        + SPACING_WIDTH;
18999
19000                    em_advance * max_char_count
19001                });
19002
19003        let is_singleton = self.buffer_snapshot.is_singleton();
19004
19005        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19006        left_padding += if !is_singleton {
19007            em_width * 4.0
19008        } else if show_code_actions || show_runnables || show_breakpoints {
19009            em_width * 3.0
19010        } else if show_git_gutter && show_line_numbers {
19011            em_width * 2.0
19012        } else if show_git_gutter || show_line_numbers {
19013            em_width
19014        } else {
19015            px(0.)
19016        };
19017
19018        let shows_folds = is_singleton && gutter_settings.folds;
19019
19020        let right_padding = if shows_folds && show_line_numbers {
19021            em_width * 4.0
19022        } else if shows_folds || (!is_singleton && show_line_numbers) {
19023            em_width * 3.0
19024        } else if show_line_numbers {
19025            em_width
19026        } else {
19027            px(0.)
19028        };
19029
19030        Some(GutterDimensions {
19031            left_padding,
19032            right_padding,
19033            width: line_gutter_width + left_padding + right_padding,
19034            margin: -descent,
19035            git_blame_entries_width,
19036        })
19037    }
19038
19039    pub fn render_crease_toggle(
19040        &self,
19041        buffer_row: MultiBufferRow,
19042        row_contains_cursor: bool,
19043        editor: Entity<Editor>,
19044        window: &mut Window,
19045        cx: &mut App,
19046    ) -> Option<AnyElement> {
19047        let folded = self.is_line_folded(buffer_row);
19048        let mut is_foldable = false;
19049
19050        if let Some(crease) = self
19051            .crease_snapshot
19052            .query_row(buffer_row, &self.buffer_snapshot)
19053        {
19054            is_foldable = true;
19055            match crease {
19056                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19057                    if let Some(render_toggle) = render_toggle {
19058                        let toggle_callback =
19059                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19060                                if folded {
19061                                    editor.update(cx, |editor, cx| {
19062                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
19063                                    });
19064                                } else {
19065                                    editor.update(cx, |editor, cx| {
19066                                        editor.unfold_at(
19067                                            &crate::UnfoldAt { buffer_row },
19068                                            window,
19069                                            cx,
19070                                        )
19071                                    });
19072                                }
19073                            });
19074                        return Some((render_toggle)(
19075                            buffer_row,
19076                            folded,
19077                            toggle_callback,
19078                            window,
19079                            cx,
19080                        ));
19081                    }
19082                }
19083            }
19084        }
19085
19086        is_foldable |= self.starts_indent(buffer_row);
19087
19088        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19089            Some(
19090                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19091                    .toggle_state(folded)
19092                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19093                        if folded {
19094                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
19095                        } else {
19096                            this.fold_at(&FoldAt { buffer_row }, window, cx);
19097                        }
19098                    }))
19099                    .into_any_element(),
19100            )
19101        } else {
19102            None
19103        }
19104    }
19105
19106    pub fn render_crease_trailer(
19107        &self,
19108        buffer_row: MultiBufferRow,
19109        window: &mut Window,
19110        cx: &mut App,
19111    ) -> Option<AnyElement> {
19112        let folded = self.is_line_folded(buffer_row);
19113        if let Crease::Inline { render_trailer, .. } = self
19114            .crease_snapshot
19115            .query_row(buffer_row, &self.buffer_snapshot)?
19116        {
19117            let render_trailer = render_trailer.as_ref()?;
19118            Some(render_trailer(buffer_row, folded, window, cx))
19119        } else {
19120            None
19121        }
19122    }
19123}
19124
19125impl Deref for EditorSnapshot {
19126    type Target = DisplaySnapshot;
19127
19128    fn deref(&self) -> &Self::Target {
19129        &self.display_snapshot
19130    }
19131}
19132
19133#[derive(Clone, Debug, PartialEq, Eq)]
19134pub enum EditorEvent {
19135    InputIgnored {
19136        text: Arc<str>,
19137    },
19138    InputHandled {
19139        utf16_range_to_replace: Option<Range<isize>>,
19140        text: Arc<str>,
19141    },
19142    ExcerptsAdded {
19143        buffer: Entity<Buffer>,
19144        predecessor: ExcerptId,
19145        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19146    },
19147    ExcerptsRemoved {
19148        ids: Vec<ExcerptId>,
19149    },
19150    BufferFoldToggled {
19151        ids: Vec<ExcerptId>,
19152        folded: bool,
19153    },
19154    ExcerptsEdited {
19155        ids: Vec<ExcerptId>,
19156    },
19157    ExcerptsExpanded {
19158        ids: Vec<ExcerptId>,
19159    },
19160    BufferEdited,
19161    Edited {
19162        transaction_id: clock::Lamport,
19163    },
19164    Reparsed(BufferId),
19165    Focused,
19166    FocusedIn,
19167    Blurred,
19168    DirtyChanged,
19169    Saved,
19170    TitleChanged,
19171    DiffBaseChanged,
19172    SelectionsChanged {
19173        local: bool,
19174    },
19175    ScrollPositionChanged {
19176        local: bool,
19177        autoscroll: bool,
19178    },
19179    Closed,
19180    TransactionUndone {
19181        transaction_id: clock::Lamport,
19182    },
19183    TransactionBegun {
19184        transaction_id: clock::Lamport,
19185    },
19186    Reloaded,
19187    CursorShapeChanged,
19188    PushedToNavHistory {
19189        anchor: Anchor,
19190        is_deactivate: bool,
19191    },
19192}
19193
19194impl EventEmitter<EditorEvent> for Editor {}
19195
19196impl Focusable for Editor {
19197    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19198        self.focus_handle.clone()
19199    }
19200}
19201
19202impl Render for Editor {
19203    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19204        let settings = ThemeSettings::get_global(cx);
19205
19206        let mut text_style = match self.mode {
19207            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19208                color: cx.theme().colors().editor_foreground,
19209                font_family: settings.ui_font.family.clone(),
19210                font_features: settings.ui_font.features.clone(),
19211                font_fallbacks: settings.ui_font.fallbacks.clone(),
19212                font_size: rems(0.875).into(),
19213                font_weight: settings.ui_font.weight,
19214                line_height: relative(settings.buffer_line_height.value()),
19215                ..Default::default()
19216            },
19217            EditorMode::Full => TextStyle {
19218                color: cx.theme().colors().editor_foreground,
19219                font_family: settings.buffer_font.family.clone(),
19220                font_features: settings.buffer_font.features.clone(),
19221                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19222                font_size: settings.buffer_font_size(cx).into(),
19223                font_weight: settings.buffer_font.weight,
19224                line_height: relative(settings.buffer_line_height.value()),
19225                ..Default::default()
19226            },
19227        };
19228        if let Some(text_style_refinement) = &self.text_style_refinement {
19229            text_style.refine(text_style_refinement)
19230        }
19231
19232        let background = match self.mode {
19233            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19234            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19235            EditorMode::Full => cx.theme().colors().editor_background,
19236        };
19237
19238        EditorElement::new(
19239            &cx.entity(),
19240            EditorStyle {
19241                background,
19242                local_player: cx.theme().players().local(),
19243                text: text_style,
19244                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19245                syntax: cx.theme().syntax().clone(),
19246                status: cx.theme().status().clone(),
19247                inlay_hints_style: make_inlay_hints_style(cx),
19248                inline_completion_styles: make_suggestion_styles(cx),
19249                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19250            },
19251        )
19252    }
19253}
19254
19255impl EntityInputHandler for Editor {
19256    fn text_for_range(
19257        &mut self,
19258        range_utf16: Range<usize>,
19259        adjusted_range: &mut Option<Range<usize>>,
19260        _: &mut Window,
19261        cx: &mut Context<Self>,
19262    ) -> Option<String> {
19263        let snapshot = self.buffer.read(cx).read(cx);
19264        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19265        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19266        if (start.0..end.0) != range_utf16 {
19267            adjusted_range.replace(start.0..end.0);
19268        }
19269        Some(snapshot.text_for_range(start..end).collect())
19270    }
19271
19272    fn selected_text_range(
19273        &mut self,
19274        ignore_disabled_input: bool,
19275        _: &mut Window,
19276        cx: &mut Context<Self>,
19277    ) -> Option<UTF16Selection> {
19278        // Prevent the IME menu from appearing when holding down an alphabetic key
19279        // while input is disabled.
19280        if !ignore_disabled_input && !self.input_enabled {
19281            return None;
19282        }
19283
19284        let selection = self.selections.newest::<OffsetUtf16>(cx);
19285        let range = selection.range();
19286
19287        Some(UTF16Selection {
19288            range: range.start.0..range.end.0,
19289            reversed: selection.reversed,
19290        })
19291    }
19292
19293    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19294        let snapshot = self.buffer.read(cx).read(cx);
19295        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19296        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19297    }
19298
19299    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19300        self.clear_highlights::<InputComposition>(cx);
19301        self.ime_transaction.take();
19302    }
19303
19304    fn replace_text_in_range(
19305        &mut self,
19306        range_utf16: Option<Range<usize>>,
19307        text: &str,
19308        window: &mut Window,
19309        cx: &mut Context<Self>,
19310    ) {
19311        if !self.input_enabled {
19312            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19313            return;
19314        }
19315
19316        self.transact(window, cx, |this, window, cx| {
19317            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19318                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19319                Some(this.selection_replacement_ranges(range_utf16, cx))
19320            } else {
19321                this.marked_text_ranges(cx)
19322            };
19323
19324            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19325                let newest_selection_id = this.selections.newest_anchor().id;
19326                this.selections
19327                    .all::<OffsetUtf16>(cx)
19328                    .iter()
19329                    .zip(ranges_to_replace.iter())
19330                    .find_map(|(selection, range)| {
19331                        if selection.id == newest_selection_id {
19332                            Some(
19333                                (range.start.0 as isize - selection.head().0 as isize)
19334                                    ..(range.end.0 as isize - selection.head().0 as isize),
19335                            )
19336                        } else {
19337                            None
19338                        }
19339                    })
19340            });
19341
19342            cx.emit(EditorEvent::InputHandled {
19343                utf16_range_to_replace: range_to_replace,
19344                text: text.into(),
19345            });
19346
19347            if let Some(new_selected_ranges) = new_selected_ranges {
19348                this.change_selections(None, window, cx, |selections| {
19349                    selections.select_ranges(new_selected_ranges)
19350                });
19351                this.backspace(&Default::default(), window, cx);
19352            }
19353
19354            this.handle_input(text, window, cx);
19355        });
19356
19357        if let Some(transaction) = self.ime_transaction {
19358            self.buffer.update(cx, |buffer, cx| {
19359                buffer.group_until_transaction(transaction, cx);
19360            });
19361        }
19362
19363        self.unmark_text(window, cx);
19364    }
19365
19366    fn replace_and_mark_text_in_range(
19367        &mut self,
19368        range_utf16: Option<Range<usize>>,
19369        text: &str,
19370        new_selected_range_utf16: Option<Range<usize>>,
19371        window: &mut Window,
19372        cx: &mut Context<Self>,
19373    ) {
19374        if !self.input_enabled {
19375            return;
19376        }
19377
19378        let transaction = self.transact(window, cx, |this, window, cx| {
19379            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19380                let snapshot = this.buffer.read(cx).read(cx);
19381                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19382                    for marked_range in &mut marked_ranges {
19383                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19384                        marked_range.start.0 += relative_range_utf16.start;
19385                        marked_range.start =
19386                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19387                        marked_range.end =
19388                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19389                    }
19390                }
19391                Some(marked_ranges)
19392            } else if let Some(range_utf16) = range_utf16 {
19393                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19394                Some(this.selection_replacement_ranges(range_utf16, cx))
19395            } else {
19396                None
19397            };
19398
19399            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19400                let newest_selection_id = this.selections.newest_anchor().id;
19401                this.selections
19402                    .all::<OffsetUtf16>(cx)
19403                    .iter()
19404                    .zip(ranges_to_replace.iter())
19405                    .find_map(|(selection, range)| {
19406                        if selection.id == newest_selection_id {
19407                            Some(
19408                                (range.start.0 as isize - selection.head().0 as isize)
19409                                    ..(range.end.0 as isize - selection.head().0 as isize),
19410                            )
19411                        } else {
19412                            None
19413                        }
19414                    })
19415            });
19416
19417            cx.emit(EditorEvent::InputHandled {
19418                utf16_range_to_replace: range_to_replace,
19419                text: text.into(),
19420            });
19421
19422            if let Some(ranges) = ranges_to_replace {
19423                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19424            }
19425
19426            let marked_ranges = {
19427                let snapshot = this.buffer.read(cx).read(cx);
19428                this.selections
19429                    .disjoint_anchors()
19430                    .iter()
19431                    .map(|selection| {
19432                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19433                    })
19434                    .collect::<Vec<_>>()
19435            };
19436
19437            if text.is_empty() {
19438                this.unmark_text(window, cx);
19439            } else {
19440                this.highlight_text::<InputComposition>(
19441                    marked_ranges.clone(),
19442                    HighlightStyle {
19443                        underline: Some(UnderlineStyle {
19444                            thickness: px(1.),
19445                            color: None,
19446                            wavy: false,
19447                        }),
19448                        ..Default::default()
19449                    },
19450                    cx,
19451                );
19452            }
19453
19454            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19455            let use_autoclose = this.use_autoclose;
19456            let use_auto_surround = this.use_auto_surround;
19457            this.set_use_autoclose(false);
19458            this.set_use_auto_surround(false);
19459            this.handle_input(text, window, cx);
19460            this.set_use_autoclose(use_autoclose);
19461            this.set_use_auto_surround(use_auto_surround);
19462
19463            if let Some(new_selected_range) = new_selected_range_utf16 {
19464                let snapshot = this.buffer.read(cx).read(cx);
19465                let new_selected_ranges = marked_ranges
19466                    .into_iter()
19467                    .map(|marked_range| {
19468                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19469                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19470                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19471                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19472                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19473                    })
19474                    .collect::<Vec<_>>();
19475
19476                drop(snapshot);
19477                this.change_selections(None, window, cx, |selections| {
19478                    selections.select_ranges(new_selected_ranges)
19479                });
19480            }
19481        });
19482
19483        self.ime_transaction = self.ime_transaction.or(transaction);
19484        if let Some(transaction) = self.ime_transaction {
19485            self.buffer.update(cx, |buffer, cx| {
19486                buffer.group_until_transaction(transaction, cx);
19487            });
19488        }
19489
19490        if self.text_highlights::<InputComposition>(cx).is_none() {
19491            self.ime_transaction.take();
19492        }
19493    }
19494
19495    fn bounds_for_range(
19496        &mut self,
19497        range_utf16: Range<usize>,
19498        element_bounds: gpui::Bounds<Pixels>,
19499        window: &mut Window,
19500        cx: &mut Context<Self>,
19501    ) -> Option<gpui::Bounds<Pixels>> {
19502        let text_layout_details = self.text_layout_details(window);
19503        let gpui::Size {
19504            width: em_width,
19505            height: line_height,
19506        } = self.character_size(window);
19507
19508        let snapshot = self.snapshot(window, cx);
19509        let scroll_position = snapshot.scroll_position();
19510        let scroll_left = scroll_position.x * em_width;
19511
19512        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19513        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19514            + self.gutter_dimensions.width
19515            + self.gutter_dimensions.margin;
19516        let y = line_height * (start.row().as_f32() - scroll_position.y);
19517
19518        Some(Bounds {
19519            origin: element_bounds.origin + point(x, y),
19520            size: size(em_width, line_height),
19521        })
19522    }
19523
19524    fn character_index_for_point(
19525        &mut self,
19526        point: gpui::Point<Pixels>,
19527        _window: &mut Window,
19528        _cx: &mut Context<Self>,
19529    ) -> Option<usize> {
19530        let position_map = self.last_position_map.as_ref()?;
19531        if !position_map.text_hitbox.contains(&point) {
19532            return None;
19533        }
19534        let display_point = position_map.point_for_position(point).previous_valid;
19535        let anchor = position_map
19536            .snapshot
19537            .display_point_to_anchor(display_point, Bias::Left);
19538        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19539        Some(utf16_offset.0)
19540    }
19541}
19542
19543trait SelectionExt {
19544    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19545    fn spanned_rows(
19546        &self,
19547        include_end_if_at_line_start: bool,
19548        map: &DisplaySnapshot,
19549    ) -> Range<MultiBufferRow>;
19550}
19551
19552impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19553    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19554        let start = self
19555            .start
19556            .to_point(&map.buffer_snapshot)
19557            .to_display_point(map);
19558        let end = self
19559            .end
19560            .to_point(&map.buffer_snapshot)
19561            .to_display_point(map);
19562        if self.reversed {
19563            end..start
19564        } else {
19565            start..end
19566        }
19567    }
19568
19569    fn spanned_rows(
19570        &self,
19571        include_end_if_at_line_start: bool,
19572        map: &DisplaySnapshot,
19573    ) -> Range<MultiBufferRow> {
19574        let start = self.start.to_point(&map.buffer_snapshot);
19575        let mut end = self.end.to_point(&map.buffer_snapshot);
19576        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19577            end.row -= 1;
19578        }
19579
19580        let buffer_start = map.prev_line_boundary(start).0;
19581        let buffer_end = map.next_line_boundary(end).0;
19582        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19583    }
19584}
19585
19586impl<T: InvalidationRegion> InvalidationStack<T> {
19587    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19588    where
19589        S: Clone + ToOffset,
19590    {
19591        while let Some(region) = self.last() {
19592            let all_selections_inside_invalidation_ranges =
19593                if selections.len() == region.ranges().len() {
19594                    selections
19595                        .iter()
19596                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19597                        .all(|(selection, invalidation_range)| {
19598                            let head = selection.head().to_offset(buffer);
19599                            invalidation_range.start <= head && invalidation_range.end >= head
19600                        })
19601                } else {
19602                    false
19603                };
19604
19605            if all_selections_inside_invalidation_ranges {
19606                break;
19607            } else {
19608                self.pop();
19609            }
19610        }
19611    }
19612}
19613
19614impl<T> Default for InvalidationStack<T> {
19615    fn default() -> Self {
19616        Self(Default::default())
19617    }
19618}
19619
19620impl<T> Deref for InvalidationStack<T> {
19621    type Target = Vec<T>;
19622
19623    fn deref(&self) -> &Self::Target {
19624        &self.0
19625    }
19626}
19627
19628impl<T> DerefMut for InvalidationStack<T> {
19629    fn deref_mut(&mut self) -> &mut Self::Target {
19630        &mut self.0
19631    }
19632}
19633
19634impl InvalidationRegion for SnippetState {
19635    fn ranges(&self) -> &[Range<Anchor>] {
19636        &self.ranges[self.active_index]
19637    }
19638}
19639
19640pub fn diagnostic_block_renderer(
19641    diagnostic: Diagnostic,
19642    max_message_rows: Option<u8>,
19643    allow_closing: bool,
19644) -> RenderBlock {
19645    let (text_without_backticks, code_ranges) =
19646        highlight_diagnostic_message(&diagnostic, max_message_rows);
19647
19648    Arc::new(move |cx: &mut BlockContext| {
19649        let group_id: SharedString = cx.block_id.to_string().into();
19650
19651        let mut text_style = cx.window.text_style().clone();
19652        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19653        let theme_settings = ThemeSettings::get_global(cx);
19654        text_style.font_family = theme_settings.buffer_font.family.clone();
19655        text_style.font_style = theme_settings.buffer_font.style;
19656        text_style.font_features = theme_settings.buffer_font.features.clone();
19657        text_style.font_weight = theme_settings.buffer_font.weight;
19658
19659        let multi_line_diagnostic = diagnostic.message.contains('\n');
19660
19661        let buttons = |diagnostic: &Diagnostic| {
19662            if multi_line_diagnostic {
19663                v_flex()
19664            } else {
19665                h_flex()
19666            }
19667            .when(allow_closing, |div| {
19668                div.children(diagnostic.is_primary.then(|| {
19669                    IconButton::new("close-block", IconName::XCircle)
19670                        .icon_color(Color::Muted)
19671                        .size(ButtonSize::Compact)
19672                        .style(ButtonStyle::Transparent)
19673                        .visible_on_hover(group_id.clone())
19674                        .on_click(move |_click, window, cx| {
19675                            window.dispatch_action(Box::new(Cancel), cx)
19676                        })
19677                        .tooltip(|window, cx| {
19678                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19679                        })
19680                }))
19681            })
19682            .child(
19683                IconButton::new("copy-block", IconName::Copy)
19684                    .icon_color(Color::Muted)
19685                    .size(ButtonSize::Compact)
19686                    .style(ButtonStyle::Transparent)
19687                    .visible_on_hover(group_id.clone())
19688                    .on_click({
19689                        let message = diagnostic.message.clone();
19690                        move |_click, _, cx| {
19691                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19692                        }
19693                    })
19694                    .tooltip(Tooltip::text("Copy diagnostic message")),
19695            )
19696        };
19697
19698        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19699            AvailableSpace::min_size(),
19700            cx.window,
19701            cx.app,
19702        );
19703
19704        h_flex()
19705            .id(cx.block_id)
19706            .group(group_id.clone())
19707            .relative()
19708            .size_full()
19709            .block_mouse_down()
19710            .pl(cx.gutter_dimensions.width)
19711            .w(cx.max_width - cx.gutter_dimensions.full_width())
19712            .child(
19713                div()
19714                    .flex()
19715                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19716                    .flex_shrink(),
19717            )
19718            .child(buttons(&diagnostic))
19719            .child(div().flex().flex_shrink_0().child(
19720                StyledText::new(text_without_backticks.clone()).with_default_highlights(
19721                    &text_style,
19722                    code_ranges.iter().map(|range| {
19723                        (
19724                            range.clone(),
19725                            HighlightStyle {
19726                                font_weight: Some(FontWeight::BOLD),
19727                                ..Default::default()
19728                            },
19729                        )
19730                    }),
19731                ),
19732            ))
19733            .into_any_element()
19734    })
19735}
19736
19737fn inline_completion_edit_text(
19738    current_snapshot: &BufferSnapshot,
19739    edits: &[(Range<Anchor>, String)],
19740    edit_preview: &EditPreview,
19741    include_deletions: bool,
19742    cx: &App,
19743) -> HighlightedText {
19744    let edits = edits
19745        .iter()
19746        .map(|(anchor, text)| {
19747            (
19748                anchor.start.text_anchor..anchor.end.text_anchor,
19749                text.clone(),
19750            )
19751        })
19752        .collect::<Vec<_>>();
19753
19754    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19755}
19756
19757pub fn highlight_diagnostic_message(
19758    diagnostic: &Diagnostic,
19759    mut max_message_rows: Option<u8>,
19760) -> (SharedString, Vec<Range<usize>>) {
19761    let mut text_without_backticks = String::new();
19762    let mut code_ranges = Vec::new();
19763
19764    if let Some(source) = &diagnostic.source {
19765        text_without_backticks.push_str(source);
19766        code_ranges.push(0..source.len());
19767        text_without_backticks.push_str(": ");
19768    }
19769
19770    let mut prev_offset = 0;
19771    let mut in_code_block = false;
19772    let has_row_limit = max_message_rows.is_some();
19773    let mut newline_indices = diagnostic
19774        .message
19775        .match_indices('\n')
19776        .filter(|_| has_row_limit)
19777        .map(|(ix, _)| ix)
19778        .fuse()
19779        .peekable();
19780
19781    for (quote_ix, _) in diagnostic
19782        .message
19783        .match_indices('`')
19784        .chain([(diagnostic.message.len(), "")])
19785    {
19786        let mut first_newline_ix = None;
19787        let mut last_newline_ix = None;
19788        while let Some(newline_ix) = newline_indices.peek() {
19789            if *newline_ix < quote_ix {
19790                if first_newline_ix.is_none() {
19791                    first_newline_ix = Some(*newline_ix);
19792                }
19793                last_newline_ix = Some(*newline_ix);
19794
19795                if let Some(rows_left) = &mut max_message_rows {
19796                    if *rows_left == 0 {
19797                        break;
19798                    } else {
19799                        *rows_left -= 1;
19800                    }
19801                }
19802                let _ = newline_indices.next();
19803            } else {
19804                break;
19805            }
19806        }
19807        let prev_len = text_without_backticks.len();
19808        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19809        text_without_backticks.push_str(new_text);
19810        if in_code_block {
19811            code_ranges.push(prev_len..text_without_backticks.len());
19812        }
19813        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19814        in_code_block = !in_code_block;
19815        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19816            text_without_backticks.push_str("...");
19817            break;
19818        }
19819    }
19820
19821    (text_without_backticks.into(), code_ranges)
19822}
19823
19824fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19825    match severity {
19826        DiagnosticSeverity::ERROR => colors.error,
19827        DiagnosticSeverity::WARNING => colors.warning,
19828        DiagnosticSeverity::INFORMATION => colors.info,
19829        DiagnosticSeverity::HINT => colors.info,
19830        _ => colors.ignored,
19831    }
19832}
19833
19834pub fn styled_runs_for_code_label<'a>(
19835    label: &'a CodeLabel,
19836    syntax_theme: &'a theme::SyntaxTheme,
19837) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19838    let fade_out = HighlightStyle {
19839        fade_out: Some(0.35),
19840        ..Default::default()
19841    };
19842
19843    let mut prev_end = label.filter_range.end;
19844    label
19845        .runs
19846        .iter()
19847        .enumerate()
19848        .flat_map(move |(ix, (range, highlight_id))| {
19849            let style = if let Some(style) = highlight_id.style(syntax_theme) {
19850                style
19851            } else {
19852                return Default::default();
19853            };
19854            let mut muted_style = style;
19855            muted_style.highlight(fade_out);
19856
19857            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19858            if range.start >= label.filter_range.end {
19859                if range.start > prev_end {
19860                    runs.push((prev_end..range.start, fade_out));
19861                }
19862                runs.push((range.clone(), muted_style));
19863            } else if range.end <= label.filter_range.end {
19864                runs.push((range.clone(), style));
19865            } else {
19866                runs.push((range.start..label.filter_range.end, style));
19867                runs.push((label.filter_range.end..range.end, muted_style));
19868            }
19869            prev_end = cmp::max(prev_end, range.end);
19870
19871            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19872                runs.push((prev_end..label.text.len(), fade_out));
19873            }
19874
19875            runs
19876        })
19877}
19878
19879pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19880    let mut prev_index = 0;
19881    let mut prev_codepoint: Option<char> = None;
19882    text.char_indices()
19883        .chain([(text.len(), '\0')])
19884        .filter_map(move |(index, codepoint)| {
19885            let prev_codepoint = prev_codepoint.replace(codepoint)?;
19886            let is_boundary = index == text.len()
19887                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19888                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19889            if is_boundary {
19890                let chunk = &text[prev_index..index];
19891                prev_index = index;
19892                Some(chunk)
19893            } else {
19894                None
19895            }
19896        })
19897}
19898
19899pub trait RangeToAnchorExt: Sized {
19900    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19901
19902    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19903        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19904        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19905    }
19906}
19907
19908impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19909    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19910        let start_offset = self.start.to_offset(snapshot);
19911        let end_offset = self.end.to_offset(snapshot);
19912        if start_offset == end_offset {
19913            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19914        } else {
19915            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19916        }
19917    }
19918}
19919
19920pub trait RowExt {
19921    fn as_f32(&self) -> f32;
19922
19923    fn next_row(&self) -> Self;
19924
19925    fn previous_row(&self) -> Self;
19926
19927    fn minus(&self, other: Self) -> u32;
19928}
19929
19930impl RowExt for DisplayRow {
19931    fn as_f32(&self) -> f32 {
19932        self.0 as f32
19933    }
19934
19935    fn next_row(&self) -> Self {
19936        Self(self.0 + 1)
19937    }
19938
19939    fn previous_row(&self) -> Self {
19940        Self(self.0.saturating_sub(1))
19941    }
19942
19943    fn minus(&self, other: Self) -> u32 {
19944        self.0 - other.0
19945    }
19946}
19947
19948impl RowExt for MultiBufferRow {
19949    fn as_f32(&self) -> f32 {
19950        self.0 as f32
19951    }
19952
19953    fn next_row(&self) -> Self {
19954        Self(self.0 + 1)
19955    }
19956
19957    fn previous_row(&self) -> Self {
19958        Self(self.0.saturating_sub(1))
19959    }
19960
19961    fn minus(&self, other: Self) -> u32 {
19962        self.0 - other.0
19963    }
19964}
19965
19966trait RowRangeExt {
19967    type Row;
19968
19969    fn len(&self) -> usize;
19970
19971    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
19972}
19973
19974impl RowRangeExt for Range<MultiBufferRow> {
19975    type Row = MultiBufferRow;
19976
19977    fn len(&self) -> usize {
19978        (self.end.0 - self.start.0) as usize
19979    }
19980
19981    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
19982        (self.start.0..self.end.0).map(MultiBufferRow)
19983    }
19984}
19985
19986impl RowRangeExt for Range<DisplayRow> {
19987    type Row = DisplayRow;
19988
19989    fn len(&self) -> usize {
19990        (self.end.0 - self.start.0) as usize
19991    }
19992
19993    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
19994        (self.start.0..self.end.0).map(DisplayRow)
19995    }
19996}
19997
19998/// If select range has more than one line, we
19999/// just point the cursor to range.start.
20000fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20001    if range.start.row == range.end.row {
20002        range
20003    } else {
20004        range.start..range.start
20005    }
20006}
20007pub struct KillRing(ClipboardItem);
20008impl Global for KillRing {}
20009
20010const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20011
20012enum BreakpointPromptEditAction {
20013    Log,
20014    Condition,
20015    HitCondition,
20016}
20017
20018struct BreakpointPromptEditor {
20019    pub(crate) prompt: Entity<Editor>,
20020    editor: WeakEntity<Editor>,
20021    breakpoint_anchor: Anchor,
20022    breakpoint: Breakpoint,
20023    edit_action: BreakpointPromptEditAction,
20024    block_ids: HashSet<CustomBlockId>,
20025    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20026    _subscriptions: Vec<Subscription>,
20027}
20028
20029impl BreakpointPromptEditor {
20030    const MAX_LINES: u8 = 4;
20031
20032    fn new(
20033        editor: WeakEntity<Editor>,
20034        breakpoint_anchor: Anchor,
20035        breakpoint: Breakpoint,
20036        edit_action: BreakpointPromptEditAction,
20037        window: &mut Window,
20038        cx: &mut Context<Self>,
20039    ) -> Self {
20040        let base_text = match edit_action {
20041            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20042            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20043            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20044        }
20045        .map(|msg| msg.to_string())
20046        .unwrap_or_default();
20047
20048        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20049        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20050
20051        let prompt = cx.new(|cx| {
20052            let mut prompt = Editor::new(
20053                EditorMode::AutoHeight {
20054                    max_lines: Self::MAX_LINES as usize,
20055                },
20056                buffer,
20057                None,
20058                window,
20059                cx,
20060            );
20061            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20062            prompt.set_show_cursor_when_unfocused(false, cx);
20063            prompt.set_placeholder_text(
20064                match edit_action {
20065                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20066                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20067                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20068                },
20069                cx,
20070            );
20071
20072            prompt
20073        });
20074
20075        Self {
20076            prompt,
20077            editor,
20078            breakpoint_anchor,
20079            breakpoint,
20080            edit_action,
20081            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20082            block_ids: Default::default(),
20083            _subscriptions: vec![],
20084        }
20085    }
20086
20087    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20088        self.block_ids.extend(block_ids)
20089    }
20090
20091    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20092        if let Some(editor) = self.editor.upgrade() {
20093            let message = self
20094                .prompt
20095                .read(cx)
20096                .buffer
20097                .read(cx)
20098                .as_singleton()
20099                .expect("A multi buffer in breakpoint prompt isn't possible")
20100                .read(cx)
20101                .as_rope()
20102                .to_string();
20103
20104            editor.update(cx, |editor, cx| {
20105                editor.edit_breakpoint_at_anchor(
20106                    self.breakpoint_anchor,
20107                    self.breakpoint.clone(),
20108                    match self.edit_action {
20109                        BreakpointPromptEditAction::Log => {
20110                            BreakpointEditAction::EditLogMessage(message.into())
20111                        }
20112                        BreakpointPromptEditAction::Condition => {
20113                            BreakpointEditAction::EditCondition(message.into())
20114                        }
20115                        BreakpointPromptEditAction::HitCondition => {
20116                            BreakpointEditAction::EditHitCondition(message.into())
20117                        }
20118                    },
20119                    cx,
20120                );
20121
20122                editor.remove_blocks(self.block_ids.clone(), None, cx);
20123                cx.focus_self(window);
20124            });
20125        }
20126    }
20127
20128    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20129        self.editor
20130            .update(cx, |editor, cx| {
20131                editor.remove_blocks(self.block_ids.clone(), None, cx);
20132                window.focus(&editor.focus_handle);
20133            })
20134            .log_err();
20135    }
20136
20137    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20138        let settings = ThemeSettings::get_global(cx);
20139        let text_style = TextStyle {
20140            color: if self.prompt.read(cx).read_only(cx) {
20141                cx.theme().colors().text_disabled
20142            } else {
20143                cx.theme().colors().text
20144            },
20145            font_family: settings.buffer_font.family.clone(),
20146            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20147            font_size: settings.buffer_font_size(cx).into(),
20148            font_weight: settings.buffer_font.weight,
20149            line_height: relative(settings.buffer_line_height.value()),
20150            ..Default::default()
20151        };
20152        EditorElement::new(
20153            &self.prompt,
20154            EditorStyle {
20155                background: cx.theme().colors().editor_background,
20156                local_player: cx.theme().players().local(),
20157                text: text_style,
20158                ..Default::default()
20159            },
20160        )
20161    }
20162}
20163
20164impl Render for BreakpointPromptEditor {
20165    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20166        let gutter_dimensions = *self.gutter_dimensions.lock();
20167        h_flex()
20168            .key_context("Editor")
20169            .bg(cx.theme().colors().editor_background)
20170            .border_y_1()
20171            .border_color(cx.theme().status().info_border)
20172            .size_full()
20173            .py(window.line_height() / 2.5)
20174            .on_action(cx.listener(Self::confirm))
20175            .on_action(cx.listener(Self::cancel))
20176            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20177            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20178    }
20179}
20180
20181impl Focusable for BreakpointPromptEditor {
20182    fn focus_handle(&self, cx: &App) -> FocusHandle {
20183        self.prompt.focus_handle(cx)
20184    }
20185}
20186
20187fn all_edits_insertions_or_deletions(
20188    edits: &Vec<(Range<Anchor>, String)>,
20189    snapshot: &MultiBufferSnapshot,
20190) -> bool {
20191    let mut all_insertions = true;
20192    let mut all_deletions = true;
20193
20194    for (range, new_text) in edits.iter() {
20195        let range_is_empty = range.to_offset(&snapshot).is_empty();
20196        let text_is_empty = new_text.is_empty();
20197
20198        if range_is_empty != text_is_empty {
20199            if range_is_empty {
20200                all_deletions = false;
20201            } else {
20202                all_insertions = false;
20203            }
20204        } else {
20205            return false;
20206        }
20207
20208        if !all_insertions && !all_deletions {
20209            return false;
20210        }
20211    }
20212    all_insertions || all_deletions
20213}
20214
20215struct MissingEditPredictionKeybindingTooltip;
20216
20217impl Render for MissingEditPredictionKeybindingTooltip {
20218    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20219        ui::tooltip_container(window, cx, |container, _, cx| {
20220            container
20221                .flex_shrink_0()
20222                .max_w_80()
20223                .min_h(rems_from_px(124.))
20224                .justify_between()
20225                .child(
20226                    v_flex()
20227                        .flex_1()
20228                        .text_ui_sm(cx)
20229                        .child(Label::new("Conflict with Accept Keybinding"))
20230                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20231                )
20232                .child(
20233                    h_flex()
20234                        .pb_1()
20235                        .gap_1()
20236                        .items_end()
20237                        .w_full()
20238                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20239                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20240                        }))
20241                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20242                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20243                        })),
20244                )
20245        })
20246    }
20247}
20248
20249#[derive(Debug, Clone, Copy, PartialEq)]
20250pub struct LineHighlight {
20251    pub background: Background,
20252    pub border: Option<gpui::Hsla>,
20253}
20254
20255impl From<Hsla> for LineHighlight {
20256    fn from(hsla: Hsla) -> Self {
20257        Self {
20258            background: hsla.into(),
20259            border: None,
20260        }
20261    }
20262}
20263
20264impl From<Background> for LineHighlight {
20265    fn from(background: Background) -> Self {
20266        Self {
20267            background,
20268            border: None,
20269        }
20270    }
20271}
20272
20273fn render_diff_hunk_controls(
20274    row: u32,
20275    status: &DiffHunkStatus,
20276    hunk_range: Range<Anchor>,
20277    is_created_file: bool,
20278    line_height: Pixels,
20279    editor: &Entity<Editor>,
20280    _window: &mut Window,
20281    cx: &mut App,
20282) -> AnyElement {
20283    h_flex()
20284        .h(line_height)
20285        .mr_1()
20286        .gap_1()
20287        .px_0p5()
20288        .pb_1()
20289        .border_x_1()
20290        .border_b_1()
20291        .border_color(cx.theme().colors().border_variant)
20292        .rounded_b_lg()
20293        .bg(cx.theme().colors().editor_background)
20294        .gap_1()
20295        .occlude()
20296        .shadow_md()
20297        .child(if status.has_secondary_hunk() {
20298            Button::new(("stage", row as u64), "Stage")
20299                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20300                .tooltip({
20301                    let focus_handle = editor.focus_handle(cx);
20302                    move |window, cx| {
20303                        Tooltip::for_action_in(
20304                            "Stage Hunk",
20305                            &::git::ToggleStaged,
20306                            &focus_handle,
20307                            window,
20308                            cx,
20309                        )
20310                    }
20311                })
20312                .on_click({
20313                    let editor = editor.clone();
20314                    move |_event, _window, cx| {
20315                        editor.update(cx, |editor, cx| {
20316                            editor.stage_or_unstage_diff_hunks(
20317                                true,
20318                                vec![hunk_range.start..hunk_range.start],
20319                                cx,
20320                            );
20321                        });
20322                    }
20323                })
20324        } else {
20325            Button::new(("unstage", row as u64), "Unstage")
20326                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20327                .tooltip({
20328                    let focus_handle = editor.focus_handle(cx);
20329                    move |window, cx| {
20330                        Tooltip::for_action_in(
20331                            "Unstage Hunk",
20332                            &::git::ToggleStaged,
20333                            &focus_handle,
20334                            window,
20335                            cx,
20336                        )
20337                    }
20338                })
20339                .on_click({
20340                    let editor = editor.clone();
20341                    move |_event, _window, cx| {
20342                        editor.update(cx, |editor, cx| {
20343                            editor.stage_or_unstage_diff_hunks(
20344                                false,
20345                                vec![hunk_range.start..hunk_range.start],
20346                                cx,
20347                            );
20348                        });
20349                    }
20350                })
20351        })
20352        .child(
20353            Button::new("restore", "Restore")
20354                .tooltip({
20355                    let focus_handle = editor.focus_handle(cx);
20356                    move |window, cx| {
20357                        Tooltip::for_action_in(
20358                            "Restore Hunk",
20359                            &::git::Restore,
20360                            &focus_handle,
20361                            window,
20362                            cx,
20363                        )
20364                    }
20365                })
20366                .on_click({
20367                    let editor = editor.clone();
20368                    move |_event, window, cx| {
20369                        editor.update(cx, |editor, cx| {
20370                            let snapshot = editor.snapshot(window, cx);
20371                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20372                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20373                        });
20374                    }
20375                })
20376                .disabled(is_created_file),
20377        )
20378        .when(
20379            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20380            |el| {
20381                el.child(
20382                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20383                        .shape(IconButtonShape::Square)
20384                        .icon_size(IconSize::Small)
20385                        // .disabled(!has_multiple_hunks)
20386                        .tooltip({
20387                            let focus_handle = editor.focus_handle(cx);
20388                            move |window, cx| {
20389                                Tooltip::for_action_in(
20390                                    "Next Hunk",
20391                                    &GoToHunk,
20392                                    &focus_handle,
20393                                    window,
20394                                    cx,
20395                                )
20396                            }
20397                        })
20398                        .on_click({
20399                            let editor = editor.clone();
20400                            move |_event, window, cx| {
20401                                editor.update(cx, |editor, cx| {
20402                                    let snapshot = editor.snapshot(window, cx);
20403                                    let position =
20404                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20405                                    editor.go_to_hunk_before_or_after_position(
20406                                        &snapshot,
20407                                        position,
20408                                        Direction::Next,
20409                                        window,
20410                                        cx,
20411                                    );
20412                                    editor.expand_selected_diff_hunks(cx);
20413                                });
20414                            }
20415                        }),
20416                )
20417                .child(
20418                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20419                        .shape(IconButtonShape::Square)
20420                        .icon_size(IconSize::Small)
20421                        // .disabled(!has_multiple_hunks)
20422                        .tooltip({
20423                            let focus_handle = editor.focus_handle(cx);
20424                            move |window, cx| {
20425                                Tooltip::for_action_in(
20426                                    "Previous Hunk",
20427                                    &GoToPreviousHunk,
20428                                    &focus_handle,
20429                                    window,
20430                                    cx,
20431                                )
20432                            }
20433                        })
20434                        .on_click({
20435                            let editor = editor.clone();
20436                            move |_event, window, cx| {
20437                                editor.update(cx, |editor, cx| {
20438                                    let snapshot = editor.snapshot(window, cx);
20439                                    let point =
20440                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20441                                    editor.go_to_hunk_before_or_after_position(
20442                                        &snapshot,
20443                                        point,
20444                                        Direction::Prev,
20445                                        window,
20446                                        cx,
20447                                    );
20448                                    editor.expand_selected_diff_hunks(cx);
20449                                });
20450                            }
20451                        }),
20452                )
20453            },
20454        )
20455        .into_any_element()
20456}