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::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
   62use editor_settings::GoToDefinitionFallback;
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
   65    ShowScrollbar,
   66};
   67pub use editor_settings_controls::*;
   68use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
   69pub use element::{
   70    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   71};
   72use feature_flags::{Debugger, FeatureFlagAppExt};
   73use futures::{
   74    FutureExt,
   75    future::{self, Shared, join},
   76};
   77use fuzzy::StringMatchCandidate;
   78
   79use ::git::Restore;
   80use code_context_menus::{
   81    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   82    CompletionsMenu, ContextMenuOrigin,
   83};
   84use git::blame::{GitBlame, GlobalBlameRenderer};
   85use gpui::{
   86    Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
   87    AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
   88    ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
   89    FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
   90    KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
   91    SharedString, Size, Stateful, Styled, 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, PathKey, 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    FitSelection,
 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(BTreeMap::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(false, |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(BTreeMap::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 edited_ranges = buffer_handle
 5039                    .read(cx)
 5040                    .edited_ranges_for_transaction::<Point>(transaction)
 5041                    .collect::<Vec<_>>();
 5042                let (ranges, _) = multibuffer.set_excerpts_for_path(
 5043                    PathKey::for_buffer(buffer_handle, cx),
 5044                    buffer_handle.clone(),
 5045                    edited_ranges,
 5046                    DEFAULT_MULTIBUFFER_CONTEXT,
 5047                    cx,
 5048                );
 5049
 5050                ranges_to_highlight.extend(ranges);
 5051            }
 5052            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 5053            multibuffer
 5054        })?;
 5055
 5056        workspace.update_in(cx, |workspace, window, cx| {
 5057            let project = workspace.project().clone();
 5058            let editor =
 5059                cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
 5060            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 5061            editor.update(cx, |editor, cx| {
 5062                editor.highlight_background::<Self>(
 5063                    &ranges_to_highlight,
 5064                    |theme| theme.editor_highlighted_line_background,
 5065                    cx,
 5066                );
 5067            });
 5068        })?;
 5069
 5070        Ok(())
 5071    }
 5072
 5073    pub fn clear_code_action_providers(&mut self) {
 5074        self.code_action_providers.clear();
 5075        self.available_code_actions.take();
 5076    }
 5077
 5078    pub fn add_code_action_provider(
 5079        &mut self,
 5080        provider: Rc<dyn CodeActionProvider>,
 5081        window: &mut Window,
 5082        cx: &mut Context<Self>,
 5083    ) {
 5084        if self
 5085            .code_action_providers
 5086            .iter()
 5087            .any(|existing_provider| existing_provider.id() == provider.id())
 5088        {
 5089            return;
 5090        }
 5091
 5092        self.code_action_providers.push(provider);
 5093        self.refresh_code_actions(window, cx);
 5094    }
 5095
 5096    pub fn remove_code_action_provider(
 5097        &mut self,
 5098        id: Arc<str>,
 5099        window: &mut Window,
 5100        cx: &mut Context<Self>,
 5101    ) {
 5102        self.code_action_providers
 5103            .retain(|provider| provider.id() != id);
 5104        self.refresh_code_actions(window, cx);
 5105    }
 5106
 5107    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 5108        let buffer = self.buffer.read(cx);
 5109        let newest_selection = self.selections.newest_anchor().clone();
 5110        if newest_selection.head().diff_base_anchor.is_some() {
 5111            return None;
 5112        }
 5113        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 5114        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 5115        if start_buffer != end_buffer {
 5116            return None;
 5117        }
 5118
 5119        self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
 5120            cx.background_executor()
 5121                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 5122                .await;
 5123
 5124            let (providers, tasks) = this.update_in(cx, |this, window, cx| {
 5125                let providers = this.code_action_providers.clone();
 5126                let tasks = this
 5127                    .code_action_providers
 5128                    .iter()
 5129                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 5130                    .collect::<Vec<_>>();
 5131                (providers, tasks)
 5132            })?;
 5133
 5134            let mut actions = Vec::new();
 5135            for (provider, provider_actions) in
 5136                providers.into_iter().zip(future::join_all(tasks).await)
 5137            {
 5138                if let Some(provider_actions) = provider_actions.log_err() {
 5139                    actions.extend(provider_actions.into_iter().map(|action| {
 5140                        AvailableCodeAction {
 5141                            excerpt_id: newest_selection.start.excerpt_id,
 5142                            action,
 5143                            provider: provider.clone(),
 5144                        }
 5145                    }));
 5146                }
 5147            }
 5148
 5149            this.update(cx, |this, cx| {
 5150                this.available_code_actions = if actions.is_empty() {
 5151                    None
 5152                } else {
 5153                    Some((
 5154                        Location {
 5155                            buffer: start_buffer,
 5156                            range: start..end,
 5157                        },
 5158                        actions.into(),
 5159                    ))
 5160                };
 5161                cx.notify();
 5162            })
 5163        }));
 5164        None
 5165    }
 5166
 5167    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5168        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 5169            self.show_git_blame_inline = false;
 5170
 5171            self.show_git_blame_inline_delay_task =
 5172                Some(cx.spawn_in(window, async move |this, cx| {
 5173                    cx.background_executor().timer(delay).await;
 5174
 5175                    this.update(cx, |this, cx| {
 5176                        this.show_git_blame_inline = true;
 5177                        cx.notify();
 5178                    })
 5179                    .log_err();
 5180                }));
 5181        }
 5182    }
 5183
 5184    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 5185        if self.pending_rename.is_some() {
 5186            return None;
 5187        }
 5188
 5189        let provider = self.semantics_provider.clone()?;
 5190        let buffer = self.buffer.read(cx);
 5191        let newest_selection = self.selections.newest_anchor().clone();
 5192        let cursor_position = newest_selection.head();
 5193        let (cursor_buffer, cursor_buffer_position) =
 5194            buffer.text_anchor_for_position(cursor_position, cx)?;
 5195        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 5196        if cursor_buffer != tail_buffer {
 5197            return None;
 5198        }
 5199        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 5200        self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
 5201            cx.background_executor()
 5202                .timer(Duration::from_millis(debounce))
 5203                .await;
 5204
 5205            let highlights = if let Some(highlights) = cx
 5206                .update(|cx| {
 5207                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 5208                })
 5209                .ok()
 5210                .flatten()
 5211            {
 5212                highlights.await.log_err()
 5213            } else {
 5214                None
 5215            };
 5216
 5217            if let Some(highlights) = highlights {
 5218                this.update(cx, |this, cx| {
 5219                    if this.pending_rename.is_some() {
 5220                        return;
 5221                    }
 5222
 5223                    let buffer_id = cursor_position.buffer_id;
 5224                    let buffer = this.buffer.read(cx);
 5225                    if !buffer
 5226                        .text_anchor_for_position(cursor_position, cx)
 5227                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 5228                    {
 5229                        return;
 5230                    }
 5231
 5232                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 5233                    let mut write_ranges = Vec::new();
 5234                    let mut read_ranges = Vec::new();
 5235                    for highlight in highlights {
 5236                        for (excerpt_id, excerpt_range) in
 5237                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 5238                        {
 5239                            let start = highlight
 5240                                .range
 5241                                .start
 5242                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 5243                            let end = highlight
 5244                                .range
 5245                                .end
 5246                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 5247                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 5248                                continue;
 5249                            }
 5250
 5251                            let range = Anchor {
 5252                                buffer_id,
 5253                                excerpt_id,
 5254                                text_anchor: start,
 5255                                diff_base_anchor: None,
 5256                            }..Anchor {
 5257                                buffer_id,
 5258                                excerpt_id,
 5259                                text_anchor: end,
 5260                                diff_base_anchor: None,
 5261                            };
 5262                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 5263                                write_ranges.push(range);
 5264                            } else {
 5265                                read_ranges.push(range);
 5266                            }
 5267                        }
 5268                    }
 5269
 5270                    this.highlight_background::<DocumentHighlightRead>(
 5271                        &read_ranges,
 5272                        |theme| theme.editor_document_highlight_read_background,
 5273                        cx,
 5274                    );
 5275                    this.highlight_background::<DocumentHighlightWrite>(
 5276                        &write_ranges,
 5277                        |theme| theme.editor_document_highlight_write_background,
 5278                        cx,
 5279                    );
 5280                    cx.notify();
 5281                })
 5282                .log_err();
 5283            }
 5284        }));
 5285        None
 5286    }
 5287
 5288    pub fn refresh_selected_text_highlights(
 5289        &mut self,
 5290        window: &mut Window,
 5291        cx: &mut Context<Editor>,
 5292    ) {
 5293        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 5294            return;
 5295        }
 5296        self.selection_highlight_task.take();
 5297        if !EditorSettings::get_global(cx).selection_highlight {
 5298            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5299            return;
 5300        }
 5301        if self.selections.count() != 1 || self.selections.line_mode {
 5302            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5303            return;
 5304        }
 5305        let selection = self.selections.newest::<Point>(cx);
 5306        if selection.is_empty() || selection.start.row != selection.end.row {
 5307            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 5308            return;
 5309        }
 5310        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 5311        self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
 5312            cx.background_executor()
 5313                .timer(Duration::from_millis(debounce))
 5314                .await;
 5315            let Some(Some(matches_task)) = editor
 5316                .update_in(cx, |editor, _, cx| {
 5317                    if editor.selections.count() != 1 || editor.selections.line_mode {
 5318                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5319                        return None;
 5320                    }
 5321                    let selection = editor.selections.newest::<Point>(cx);
 5322                    if selection.is_empty() || selection.start.row != selection.end.row {
 5323                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5324                        return None;
 5325                    }
 5326                    let buffer = editor.buffer().read(cx).snapshot(cx);
 5327                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 5328                    if query.trim().is_empty() {
 5329                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5330                        return None;
 5331                    }
 5332                    Some(cx.background_spawn(async move {
 5333                        let mut ranges = Vec::new();
 5334                        let selection_anchors = selection.range().to_anchors(&buffer);
 5335                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 5336                            for (search_buffer, search_range, excerpt_id) in
 5337                                buffer.range_to_buffer_ranges(range)
 5338                            {
 5339                                ranges.extend(
 5340                                    project::search::SearchQuery::text(
 5341                                        query.clone(),
 5342                                        false,
 5343                                        false,
 5344                                        false,
 5345                                        Default::default(),
 5346                                        Default::default(),
 5347                                        None,
 5348                                    )
 5349                                    .unwrap()
 5350                                    .search(search_buffer, Some(search_range.clone()))
 5351                                    .await
 5352                                    .into_iter()
 5353                                    .filter_map(
 5354                                        |match_range| {
 5355                                            let start = search_buffer.anchor_after(
 5356                                                search_range.start + match_range.start,
 5357                                            );
 5358                                            let end = search_buffer.anchor_before(
 5359                                                search_range.start + match_range.end,
 5360                                            );
 5361                                            let range = Anchor::range_in_buffer(
 5362                                                excerpt_id,
 5363                                                search_buffer.remote_id(),
 5364                                                start..end,
 5365                                            );
 5366                                            (range != selection_anchors).then_some(range)
 5367                                        },
 5368                                    ),
 5369                                );
 5370                            }
 5371                        }
 5372                        ranges
 5373                    }))
 5374                })
 5375                .log_err()
 5376            else {
 5377                return;
 5378            };
 5379            let matches = matches_task.await;
 5380            editor
 5381                .update_in(cx, |editor, _, cx| {
 5382                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 5383                    if !matches.is_empty() {
 5384                        editor.highlight_background::<SelectedTextHighlight>(
 5385                            &matches,
 5386                            |theme| theme.editor_document_highlight_bracket_background,
 5387                            cx,
 5388                        )
 5389                    }
 5390                })
 5391                .log_err();
 5392        }));
 5393    }
 5394
 5395    pub fn refresh_inline_completion(
 5396        &mut self,
 5397        debounce: bool,
 5398        user_requested: bool,
 5399        window: &mut Window,
 5400        cx: &mut Context<Self>,
 5401    ) -> Option<()> {
 5402        let provider = self.edit_prediction_provider()?;
 5403        let cursor = self.selections.newest_anchor().head();
 5404        let (buffer, cursor_buffer_position) =
 5405            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5406
 5407        if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 5408            self.discard_inline_completion(false, cx);
 5409            return None;
 5410        }
 5411
 5412        if !user_requested
 5413            && (!self.should_show_edit_predictions()
 5414                || !self.is_focused(window)
 5415                || buffer.read(cx).is_empty())
 5416        {
 5417            self.discard_inline_completion(false, cx);
 5418            return None;
 5419        }
 5420
 5421        self.update_visible_inline_completion(window, cx);
 5422        provider.refresh(
 5423            self.project.clone(),
 5424            buffer,
 5425            cursor_buffer_position,
 5426            debounce,
 5427            cx,
 5428        );
 5429        Some(())
 5430    }
 5431
 5432    fn show_edit_predictions_in_menu(&self) -> bool {
 5433        match self.edit_prediction_settings {
 5434            EditPredictionSettings::Disabled => false,
 5435            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 5436        }
 5437    }
 5438
 5439    pub fn edit_predictions_enabled(&self) -> bool {
 5440        match self.edit_prediction_settings {
 5441            EditPredictionSettings::Disabled => false,
 5442            EditPredictionSettings::Enabled { .. } => true,
 5443        }
 5444    }
 5445
 5446    fn edit_prediction_requires_modifier(&self) -> bool {
 5447        match self.edit_prediction_settings {
 5448            EditPredictionSettings::Disabled => false,
 5449            EditPredictionSettings::Enabled {
 5450                preview_requires_modifier,
 5451                ..
 5452            } => preview_requires_modifier,
 5453        }
 5454    }
 5455
 5456    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 5457        if self.edit_prediction_provider.is_none() {
 5458            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5459        } else {
 5460            let selection = self.selections.newest_anchor();
 5461            let cursor = selection.head();
 5462
 5463            if let Some((buffer, cursor_buffer_position)) =
 5464                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5465            {
 5466                self.edit_prediction_settings =
 5467                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5468            }
 5469        }
 5470    }
 5471
 5472    fn edit_prediction_settings_at_position(
 5473        &self,
 5474        buffer: &Entity<Buffer>,
 5475        buffer_position: language::Anchor,
 5476        cx: &App,
 5477    ) -> EditPredictionSettings {
 5478        if self.mode != EditorMode::Full
 5479            || !self.show_inline_completions_override.unwrap_or(true)
 5480            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 5481        {
 5482            return EditPredictionSettings::Disabled;
 5483        }
 5484
 5485        let buffer = buffer.read(cx);
 5486
 5487        let file = buffer.file();
 5488
 5489        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 5490            return EditPredictionSettings::Disabled;
 5491        };
 5492
 5493        let by_provider = matches!(
 5494            self.menu_inline_completions_policy,
 5495            MenuInlineCompletionsPolicy::ByProvider
 5496        );
 5497
 5498        let show_in_menu = by_provider
 5499            && self
 5500                .edit_prediction_provider
 5501                .as_ref()
 5502                .map_or(false, |provider| {
 5503                    provider.provider.show_completions_in_menu()
 5504                });
 5505
 5506        let preview_requires_modifier =
 5507            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
 5508
 5509        EditPredictionSettings::Enabled {
 5510            show_in_menu,
 5511            preview_requires_modifier,
 5512        }
 5513    }
 5514
 5515    fn should_show_edit_predictions(&self) -> bool {
 5516        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 5517    }
 5518
 5519    pub fn edit_prediction_preview_is_active(&self) -> bool {
 5520        matches!(
 5521            self.edit_prediction_preview,
 5522            EditPredictionPreview::Active { .. }
 5523        )
 5524    }
 5525
 5526    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 5527        let cursor = self.selections.newest_anchor().head();
 5528        if let Some((buffer, cursor_position)) =
 5529            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5530        {
 5531            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 5532        } else {
 5533            false
 5534        }
 5535    }
 5536
 5537    fn edit_predictions_enabled_in_buffer(
 5538        &self,
 5539        buffer: &Entity<Buffer>,
 5540        buffer_position: language::Anchor,
 5541        cx: &App,
 5542    ) -> bool {
 5543        maybe!({
 5544            if self.read_only(cx) {
 5545                return Some(false);
 5546            }
 5547            let provider = self.edit_prediction_provider()?;
 5548            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5549                return Some(false);
 5550            }
 5551            let buffer = buffer.read(cx);
 5552            let Some(file) = buffer.file() else {
 5553                return Some(true);
 5554            };
 5555            let settings = all_language_settings(Some(file), cx);
 5556            Some(settings.edit_predictions_enabled_for_file(file, cx))
 5557        })
 5558        .unwrap_or(false)
 5559    }
 5560
 5561    fn cycle_inline_completion(
 5562        &mut self,
 5563        direction: Direction,
 5564        window: &mut Window,
 5565        cx: &mut Context<Self>,
 5566    ) -> Option<()> {
 5567        let provider = self.edit_prediction_provider()?;
 5568        let cursor = self.selections.newest_anchor().head();
 5569        let (buffer, cursor_buffer_position) =
 5570            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5571        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5572            return None;
 5573        }
 5574
 5575        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5576        self.update_visible_inline_completion(window, cx);
 5577
 5578        Some(())
 5579    }
 5580
 5581    pub fn show_inline_completion(
 5582        &mut self,
 5583        _: &ShowEditPrediction,
 5584        window: &mut Window,
 5585        cx: &mut Context<Self>,
 5586    ) {
 5587        if !self.has_active_inline_completion() {
 5588            self.refresh_inline_completion(false, true, window, cx);
 5589            return;
 5590        }
 5591
 5592        self.update_visible_inline_completion(window, cx);
 5593    }
 5594
 5595    pub fn display_cursor_names(
 5596        &mut self,
 5597        _: &DisplayCursorNames,
 5598        window: &mut Window,
 5599        cx: &mut Context<Self>,
 5600    ) {
 5601        self.show_cursor_names(window, cx);
 5602    }
 5603
 5604    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5605        self.show_cursor_names = true;
 5606        cx.notify();
 5607        cx.spawn_in(window, async move |this, cx| {
 5608            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5609            this.update(cx, |this, cx| {
 5610                this.show_cursor_names = false;
 5611                cx.notify()
 5612            })
 5613            .ok()
 5614        })
 5615        .detach();
 5616    }
 5617
 5618    pub fn next_edit_prediction(
 5619        &mut self,
 5620        _: &NextEditPrediction,
 5621        window: &mut Window,
 5622        cx: &mut Context<Self>,
 5623    ) {
 5624        if self.has_active_inline_completion() {
 5625            self.cycle_inline_completion(Direction::Next, window, cx);
 5626        } else {
 5627            let is_copilot_disabled = self
 5628                .refresh_inline_completion(false, true, window, cx)
 5629                .is_none();
 5630            if is_copilot_disabled {
 5631                cx.propagate();
 5632            }
 5633        }
 5634    }
 5635
 5636    pub fn previous_edit_prediction(
 5637        &mut self,
 5638        _: &PreviousEditPrediction,
 5639        window: &mut Window,
 5640        cx: &mut Context<Self>,
 5641    ) {
 5642        if self.has_active_inline_completion() {
 5643            self.cycle_inline_completion(Direction::Prev, window, cx);
 5644        } else {
 5645            let is_copilot_disabled = self
 5646                .refresh_inline_completion(false, true, window, cx)
 5647                .is_none();
 5648            if is_copilot_disabled {
 5649                cx.propagate();
 5650            }
 5651        }
 5652    }
 5653
 5654    pub fn accept_edit_prediction(
 5655        &mut self,
 5656        _: &AcceptEditPrediction,
 5657        window: &mut Window,
 5658        cx: &mut Context<Self>,
 5659    ) {
 5660        if self.show_edit_predictions_in_menu() {
 5661            self.hide_context_menu(window, cx);
 5662        }
 5663
 5664        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5665            return;
 5666        };
 5667
 5668        self.report_inline_completion_event(
 5669            active_inline_completion.completion_id.clone(),
 5670            true,
 5671            cx,
 5672        );
 5673
 5674        match &active_inline_completion.completion {
 5675            InlineCompletion::Move { target, .. } => {
 5676                let target = *target;
 5677
 5678                if let Some(position_map) = &self.last_position_map {
 5679                    if position_map
 5680                        .visible_row_range
 5681                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5682                        || !self.edit_prediction_requires_modifier()
 5683                    {
 5684                        self.unfold_ranges(&[target..target], true, false, cx);
 5685                        // Note that this is also done in vim's handler of the Tab action.
 5686                        self.change_selections(
 5687                            Some(Autoscroll::newest()),
 5688                            window,
 5689                            cx,
 5690                            |selections| {
 5691                                selections.select_anchor_ranges([target..target]);
 5692                            },
 5693                        );
 5694                        self.clear_row_highlights::<EditPredictionPreview>();
 5695
 5696                        self.edit_prediction_preview
 5697                            .set_previous_scroll_position(None);
 5698                    } else {
 5699                        self.edit_prediction_preview
 5700                            .set_previous_scroll_position(Some(
 5701                                position_map.snapshot.scroll_anchor,
 5702                            ));
 5703
 5704                        self.highlight_rows::<EditPredictionPreview>(
 5705                            target..target,
 5706                            cx.theme().colors().editor_highlighted_line_background,
 5707                            true,
 5708                            cx,
 5709                        );
 5710                        self.request_autoscroll(Autoscroll::fit(), cx);
 5711                    }
 5712                }
 5713            }
 5714            InlineCompletion::Edit { edits, .. } => {
 5715                if let Some(provider) = self.edit_prediction_provider() {
 5716                    provider.accept(cx);
 5717                }
 5718
 5719                let snapshot = self.buffer.read(cx).snapshot(cx);
 5720                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5721
 5722                self.buffer.update(cx, |buffer, cx| {
 5723                    buffer.edit(edits.iter().cloned(), None, cx)
 5724                });
 5725
 5726                self.change_selections(None, window, cx, |s| {
 5727                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5728                });
 5729
 5730                self.update_visible_inline_completion(window, cx);
 5731                if self.active_inline_completion.is_none() {
 5732                    self.refresh_inline_completion(true, true, window, cx);
 5733                }
 5734
 5735                cx.notify();
 5736            }
 5737        }
 5738
 5739        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5740    }
 5741
 5742    pub fn accept_partial_inline_completion(
 5743        &mut self,
 5744        _: &AcceptPartialEditPrediction,
 5745        window: &mut Window,
 5746        cx: &mut Context<Self>,
 5747    ) {
 5748        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5749            return;
 5750        };
 5751        if self.selections.count() != 1 {
 5752            return;
 5753        }
 5754
 5755        self.report_inline_completion_event(
 5756            active_inline_completion.completion_id.clone(),
 5757            true,
 5758            cx,
 5759        );
 5760
 5761        match &active_inline_completion.completion {
 5762            InlineCompletion::Move { target, .. } => {
 5763                let target = *target;
 5764                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5765                    selections.select_anchor_ranges([target..target]);
 5766                });
 5767            }
 5768            InlineCompletion::Edit { edits, .. } => {
 5769                // Find an insertion that starts at the cursor position.
 5770                let snapshot = self.buffer.read(cx).snapshot(cx);
 5771                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5772                let insertion = edits.iter().find_map(|(range, text)| {
 5773                    let range = range.to_offset(&snapshot);
 5774                    if range.is_empty() && range.start == cursor_offset {
 5775                        Some(text)
 5776                    } else {
 5777                        None
 5778                    }
 5779                });
 5780
 5781                if let Some(text) = insertion {
 5782                    let mut partial_completion = text
 5783                        .chars()
 5784                        .by_ref()
 5785                        .take_while(|c| c.is_alphabetic())
 5786                        .collect::<String>();
 5787                    if partial_completion.is_empty() {
 5788                        partial_completion = text
 5789                            .chars()
 5790                            .by_ref()
 5791                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5792                            .collect::<String>();
 5793                    }
 5794
 5795                    cx.emit(EditorEvent::InputHandled {
 5796                        utf16_range_to_replace: None,
 5797                        text: partial_completion.clone().into(),
 5798                    });
 5799
 5800                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5801
 5802                    self.refresh_inline_completion(true, true, window, cx);
 5803                    cx.notify();
 5804                } else {
 5805                    self.accept_edit_prediction(&Default::default(), window, cx);
 5806                }
 5807            }
 5808        }
 5809    }
 5810
 5811    fn discard_inline_completion(
 5812        &mut self,
 5813        should_report_inline_completion_event: bool,
 5814        cx: &mut Context<Self>,
 5815    ) -> bool {
 5816        if should_report_inline_completion_event {
 5817            let completion_id = self
 5818                .active_inline_completion
 5819                .as_ref()
 5820                .and_then(|active_completion| active_completion.completion_id.clone());
 5821
 5822            self.report_inline_completion_event(completion_id, false, cx);
 5823        }
 5824
 5825        if let Some(provider) = self.edit_prediction_provider() {
 5826            provider.discard(cx);
 5827        }
 5828
 5829        self.take_active_inline_completion(cx)
 5830    }
 5831
 5832    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5833        let Some(provider) = self.edit_prediction_provider() else {
 5834            return;
 5835        };
 5836
 5837        let Some((_, buffer, _)) = self
 5838            .buffer
 5839            .read(cx)
 5840            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5841        else {
 5842            return;
 5843        };
 5844
 5845        let extension = buffer
 5846            .read(cx)
 5847            .file()
 5848            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5849
 5850        let event_type = match accepted {
 5851            true => "Edit Prediction Accepted",
 5852            false => "Edit Prediction Discarded",
 5853        };
 5854        telemetry::event!(
 5855            event_type,
 5856            provider = provider.name(),
 5857            prediction_id = id,
 5858            suggestion_accepted = accepted,
 5859            file_extension = extension,
 5860        );
 5861    }
 5862
 5863    pub fn has_active_inline_completion(&self) -> bool {
 5864        self.active_inline_completion.is_some()
 5865    }
 5866
 5867    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5868        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5869            return false;
 5870        };
 5871
 5872        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5873        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5874        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5875        true
 5876    }
 5877
 5878    /// Returns true when we're displaying the edit prediction popover below the cursor
 5879    /// like we are not previewing and the LSP autocomplete menu is visible
 5880    /// or we are in `when_holding_modifier` mode.
 5881    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5882        if self.edit_prediction_preview_is_active()
 5883            || !self.show_edit_predictions_in_menu()
 5884            || !self.edit_predictions_enabled()
 5885        {
 5886            return false;
 5887        }
 5888
 5889        if self.has_visible_completions_menu() {
 5890            return true;
 5891        }
 5892
 5893        has_completion && self.edit_prediction_requires_modifier()
 5894    }
 5895
 5896    fn handle_modifiers_changed(
 5897        &mut self,
 5898        modifiers: Modifiers,
 5899        position_map: &PositionMap,
 5900        window: &mut Window,
 5901        cx: &mut Context<Self>,
 5902    ) {
 5903        if self.show_edit_predictions_in_menu() {
 5904            self.update_edit_prediction_preview(&modifiers, window, cx);
 5905        }
 5906
 5907        self.update_selection_mode(&modifiers, position_map, window, cx);
 5908
 5909        let mouse_position = window.mouse_position();
 5910        if !position_map.text_hitbox.is_hovered(window) {
 5911            return;
 5912        }
 5913
 5914        self.update_hovered_link(
 5915            position_map.point_for_position(mouse_position),
 5916            &position_map.snapshot,
 5917            modifiers,
 5918            window,
 5919            cx,
 5920        )
 5921    }
 5922
 5923    fn update_selection_mode(
 5924        &mut self,
 5925        modifiers: &Modifiers,
 5926        position_map: &PositionMap,
 5927        window: &mut Window,
 5928        cx: &mut Context<Self>,
 5929    ) {
 5930        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5931            return;
 5932        }
 5933
 5934        let mouse_position = window.mouse_position();
 5935        let point_for_position = position_map.point_for_position(mouse_position);
 5936        let position = point_for_position.previous_valid;
 5937
 5938        self.select(
 5939            SelectPhase::BeginColumnar {
 5940                position,
 5941                reset: false,
 5942                goal_column: point_for_position.exact_unclipped.column(),
 5943            },
 5944            window,
 5945            cx,
 5946        );
 5947    }
 5948
 5949    fn update_edit_prediction_preview(
 5950        &mut self,
 5951        modifiers: &Modifiers,
 5952        window: &mut Window,
 5953        cx: &mut Context<Self>,
 5954    ) {
 5955        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5956        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5957            return;
 5958        };
 5959
 5960        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5961            if matches!(
 5962                self.edit_prediction_preview,
 5963                EditPredictionPreview::Inactive { .. }
 5964            ) {
 5965                self.edit_prediction_preview = EditPredictionPreview::Active {
 5966                    previous_scroll_position: None,
 5967                    since: Instant::now(),
 5968                };
 5969
 5970                self.update_visible_inline_completion(window, cx);
 5971                cx.notify();
 5972            }
 5973        } else if let EditPredictionPreview::Active {
 5974            previous_scroll_position,
 5975            since,
 5976        } = self.edit_prediction_preview
 5977        {
 5978            if let (Some(previous_scroll_position), Some(position_map)) =
 5979                (previous_scroll_position, self.last_position_map.as_ref())
 5980            {
 5981                self.set_scroll_position(
 5982                    previous_scroll_position
 5983                        .scroll_position(&position_map.snapshot.display_snapshot),
 5984                    window,
 5985                    cx,
 5986                );
 5987            }
 5988
 5989            self.edit_prediction_preview = EditPredictionPreview::Inactive {
 5990                released_too_fast: since.elapsed() < Duration::from_millis(200),
 5991            };
 5992            self.clear_row_highlights::<EditPredictionPreview>();
 5993            self.update_visible_inline_completion(window, cx);
 5994            cx.notify();
 5995        }
 5996    }
 5997
 5998    fn update_visible_inline_completion(
 5999        &mut self,
 6000        _window: &mut Window,
 6001        cx: &mut Context<Self>,
 6002    ) -> Option<()> {
 6003        let selection = self.selections.newest_anchor();
 6004        let cursor = selection.head();
 6005        let multibuffer = self.buffer.read(cx).snapshot(cx);
 6006        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 6007        let excerpt_id = cursor.excerpt_id;
 6008
 6009        let show_in_menu = self.show_edit_predictions_in_menu();
 6010        let completions_menu_has_precedence = !show_in_menu
 6011            && (self.context_menu.borrow().is_some()
 6012                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 6013
 6014        if completions_menu_has_precedence
 6015            || !offset_selection.is_empty()
 6016            || self
 6017                .active_inline_completion
 6018                .as_ref()
 6019                .map_or(false, |completion| {
 6020                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 6021                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 6022                    !invalidation_range.contains(&offset_selection.head())
 6023                })
 6024        {
 6025            self.discard_inline_completion(false, cx);
 6026            return None;
 6027        }
 6028
 6029        self.take_active_inline_completion(cx);
 6030        let Some(provider) = self.edit_prediction_provider() else {
 6031            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 6032            return None;
 6033        };
 6034
 6035        let (buffer, cursor_buffer_position) =
 6036            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 6037
 6038        self.edit_prediction_settings =
 6039            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 6040
 6041        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 6042
 6043        if self.edit_prediction_indent_conflict {
 6044            let cursor_point = cursor.to_point(&multibuffer);
 6045
 6046            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 6047
 6048            if let Some((_, indent)) = indents.iter().next() {
 6049                if indent.len == cursor_point.column {
 6050                    self.edit_prediction_indent_conflict = false;
 6051                }
 6052            }
 6053        }
 6054
 6055        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 6056        let edits = inline_completion
 6057            .edits
 6058            .into_iter()
 6059            .flat_map(|(range, new_text)| {
 6060                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 6061                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 6062                Some((start..end, new_text))
 6063            })
 6064            .collect::<Vec<_>>();
 6065        if edits.is_empty() {
 6066            return None;
 6067        }
 6068
 6069        let first_edit_start = edits.first().unwrap().0.start;
 6070        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 6071        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 6072
 6073        let last_edit_end = edits.last().unwrap().0.end;
 6074        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 6075        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 6076
 6077        let cursor_row = cursor.to_point(&multibuffer).row;
 6078
 6079        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 6080
 6081        let mut inlay_ids = Vec::new();
 6082        let invalidation_row_range;
 6083        let move_invalidation_row_range = if cursor_row < edit_start_row {
 6084            Some(cursor_row..edit_end_row)
 6085        } else if cursor_row > edit_end_row {
 6086            Some(edit_start_row..cursor_row)
 6087        } else {
 6088            None
 6089        };
 6090        let is_move =
 6091            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 6092        let completion = if is_move {
 6093            invalidation_row_range =
 6094                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 6095            let target = first_edit_start;
 6096            InlineCompletion::Move { target, snapshot }
 6097        } else {
 6098            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 6099                && !self.inline_completions_hidden_for_vim_mode;
 6100
 6101            if show_completions_in_buffer {
 6102                if edits
 6103                    .iter()
 6104                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 6105                {
 6106                    let mut inlays = Vec::new();
 6107                    for (range, new_text) in &edits {
 6108                        let inlay = Inlay::inline_completion(
 6109                            post_inc(&mut self.next_inlay_id),
 6110                            range.start,
 6111                            new_text.as_str(),
 6112                        );
 6113                        inlay_ids.push(inlay.id);
 6114                        inlays.push(inlay);
 6115                    }
 6116
 6117                    self.splice_inlays(&[], inlays, cx);
 6118                } else {
 6119                    let background_color = cx.theme().status().deleted_background;
 6120                    self.highlight_text::<InlineCompletionHighlight>(
 6121                        edits.iter().map(|(range, _)| range.clone()).collect(),
 6122                        HighlightStyle {
 6123                            background_color: Some(background_color),
 6124                            ..Default::default()
 6125                        },
 6126                        cx,
 6127                    );
 6128                }
 6129            }
 6130
 6131            invalidation_row_range = edit_start_row..edit_end_row;
 6132
 6133            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 6134                if provider.show_tab_accept_marker() {
 6135                    EditDisplayMode::TabAccept
 6136                } else {
 6137                    EditDisplayMode::Inline
 6138                }
 6139            } else {
 6140                EditDisplayMode::DiffPopover
 6141            };
 6142
 6143            InlineCompletion::Edit {
 6144                edits,
 6145                edit_preview: inline_completion.edit_preview,
 6146                display_mode,
 6147                snapshot,
 6148            }
 6149        };
 6150
 6151        let invalidation_range = multibuffer
 6152            .anchor_before(Point::new(invalidation_row_range.start, 0))
 6153            ..multibuffer.anchor_after(Point::new(
 6154                invalidation_row_range.end,
 6155                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 6156            ));
 6157
 6158        self.stale_inline_completion_in_menu = None;
 6159        self.active_inline_completion = Some(InlineCompletionState {
 6160            inlay_ids,
 6161            completion,
 6162            completion_id: inline_completion.id,
 6163            invalidation_range,
 6164        });
 6165
 6166        cx.notify();
 6167
 6168        Some(())
 6169    }
 6170
 6171    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 6172        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 6173    }
 6174
 6175    fn render_code_actions_indicator(
 6176        &self,
 6177        _style: &EditorStyle,
 6178        row: DisplayRow,
 6179        is_active: bool,
 6180        breakpoint: Option<&(Anchor, Breakpoint)>,
 6181        cx: &mut Context<Self>,
 6182    ) -> Option<IconButton> {
 6183        let color = Color::Muted;
 6184        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6185        let show_tooltip = !self.context_menu_visible();
 6186
 6187        if self.available_code_actions.is_some() {
 6188            Some(
 6189                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 6190                    .shape(ui::IconButtonShape::Square)
 6191                    .icon_size(IconSize::XSmall)
 6192                    .icon_color(color)
 6193                    .toggle_state(is_active)
 6194                    .when(show_tooltip, |this| {
 6195                        this.tooltip({
 6196                            let focus_handle = self.focus_handle.clone();
 6197                            move |window, cx| {
 6198                                Tooltip::for_action_in(
 6199                                    "Toggle Code Actions",
 6200                                    &ToggleCodeActions {
 6201                                        deployed_from_indicator: None,
 6202                                    },
 6203                                    &focus_handle,
 6204                                    window,
 6205                                    cx,
 6206                                )
 6207                            }
 6208                        })
 6209                    })
 6210                    .on_click(cx.listener(move |editor, _e, window, cx| {
 6211                        window.focus(&editor.focus_handle(cx));
 6212                        editor.toggle_code_actions(
 6213                            &ToggleCodeActions {
 6214                                deployed_from_indicator: Some(row),
 6215                            },
 6216                            window,
 6217                            cx,
 6218                        );
 6219                    }))
 6220                    .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6221                        editor.set_breakpoint_context_menu(
 6222                            row,
 6223                            position,
 6224                            event.down.position,
 6225                            window,
 6226                            cx,
 6227                        );
 6228                    })),
 6229            )
 6230        } else {
 6231            None
 6232        }
 6233    }
 6234
 6235    fn clear_tasks(&mut self) {
 6236        self.tasks.clear()
 6237    }
 6238
 6239    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 6240        if self.tasks.insert(key, value).is_some() {
 6241            // This case should hopefully be rare, but just in case...
 6242            log::error!(
 6243                "multiple different run targets found on a single line, only the last target will be rendered"
 6244            )
 6245        }
 6246    }
 6247
 6248    /// Get all display points of breakpoints that will be rendered within editor
 6249    ///
 6250    /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
 6251    /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
 6252    /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
 6253    fn active_breakpoints(
 6254        &self,
 6255        range: Range<DisplayRow>,
 6256        window: &mut Window,
 6257        cx: &mut Context<Self>,
 6258    ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
 6259        let mut breakpoint_display_points = HashMap::default();
 6260
 6261        let Some(breakpoint_store) = self.breakpoint_store.clone() else {
 6262            return breakpoint_display_points;
 6263        };
 6264
 6265        let snapshot = self.snapshot(window, cx);
 6266
 6267        let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
 6268        let Some(project) = self.project.as_ref() else {
 6269            return breakpoint_display_points;
 6270        };
 6271
 6272        let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
 6273            ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
 6274
 6275        for (buffer_snapshot, range, excerpt_id) in
 6276            multi_buffer_snapshot.range_to_buffer_ranges(range)
 6277        {
 6278            let Some(buffer) = project.read_with(cx, |this, cx| {
 6279                this.buffer_for_id(buffer_snapshot.remote_id(), cx)
 6280            }) else {
 6281                continue;
 6282            };
 6283            let breakpoints = breakpoint_store.read(cx).breakpoints(
 6284                &buffer,
 6285                Some(
 6286                    buffer_snapshot.anchor_before(range.start)
 6287                        ..buffer_snapshot.anchor_after(range.end),
 6288                ),
 6289                buffer_snapshot,
 6290                cx,
 6291            );
 6292            for (anchor, breakpoint) in breakpoints {
 6293                let multi_buffer_anchor =
 6294                    Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
 6295                let position = multi_buffer_anchor
 6296                    .to_point(&multi_buffer_snapshot)
 6297                    .to_display_point(&snapshot);
 6298
 6299                breakpoint_display_points
 6300                    .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
 6301            }
 6302        }
 6303
 6304        breakpoint_display_points
 6305    }
 6306
 6307    fn breakpoint_context_menu(
 6308        &self,
 6309        anchor: Anchor,
 6310        window: &mut Window,
 6311        cx: &mut Context<Self>,
 6312    ) -> Entity<ui::ContextMenu> {
 6313        let weak_editor = cx.weak_entity();
 6314        let focus_handle = self.focus_handle(cx);
 6315
 6316        let row = self
 6317            .buffer
 6318            .read(cx)
 6319            .snapshot(cx)
 6320            .summary_for_anchor::<Point>(&anchor)
 6321            .row;
 6322
 6323        let breakpoint = self
 6324            .breakpoint_at_row(row, window, cx)
 6325            .map(|(anchor, bp)| (anchor, Arc::from(bp)));
 6326
 6327        let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
 6328            "Edit Log Breakpoint"
 6329        } else {
 6330            "Set Log Breakpoint"
 6331        };
 6332
 6333        let condition_breakpoint_msg = if breakpoint
 6334            .as_ref()
 6335            .is_some_and(|bp| bp.1.condition.is_some())
 6336        {
 6337            "Edit Condition Breakpoint"
 6338        } else {
 6339            "Set Condition Breakpoint"
 6340        };
 6341
 6342        let hit_condition_breakpoint_msg = if breakpoint
 6343            .as_ref()
 6344            .is_some_and(|bp| bp.1.hit_condition.is_some())
 6345        {
 6346            "Edit Hit Condition Breakpoint"
 6347        } else {
 6348            "Set Hit Condition Breakpoint"
 6349        };
 6350
 6351        let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
 6352            "Unset Breakpoint"
 6353        } else {
 6354            "Set Breakpoint"
 6355        };
 6356
 6357        let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
 6358            BreakpointState::Enabled => Some("Disable"),
 6359            BreakpointState::Disabled => Some("Enable"),
 6360        });
 6361
 6362        let (anchor, breakpoint) =
 6363            breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
 6364
 6365        ui::ContextMenu::build(window, cx, |menu, _, _cx| {
 6366            menu.on_blur_subscription(Subscription::new(|| {}))
 6367                .context(focus_handle)
 6368                .when_some(toggle_state_msg, |this, msg| {
 6369                    this.entry(msg, None, {
 6370                        let weak_editor = weak_editor.clone();
 6371                        let breakpoint = breakpoint.clone();
 6372                        move |_window, cx| {
 6373                            weak_editor
 6374                                .update(cx, |this, cx| {
 6375                                    this.edit_breakpoint_at_anchor(
 6376                                        anchor,
 6377                                        breakpoint.as_ref().clone(),
 6378                                        BreakpointEditAction::InvertState,
 6379                                        cx,
 6380                                    );
 6381                                })
 6382                                .log_err();
 6383                        }
 6384                    })
 6385                })
 6386                .entry(set_breakpoint_msg, None, {
 6387                    let weak_editor = weak_editor.clone();
 6388                    let breakpoint = breakpoint.clone();
 6389                    move |_window, cx| {
 6390                        weak_editor
 6391                            .update(cx, |this, cx| {
 6392                                this.edit_breakpoint_at_anchor(
 6393                                    anchor,
 6394                                    breakpoint.as_ref().clone(),
 6395                                    BreakpointEditAction::Toggle,
 6396                                    cx,
 6397                                );
 6398                            })
 6399                            .log_err();
 6400                    }
 6401                })
 6402                .entry(log_breakpoint_msg, None, {
 6403                    let breakpoint = breakpoint.clone();
 6404                    let weak_editor = weak_editor.clone();
 6405                    move |window, cx| {
 6406                        weak_editor
 6407                            .update(cx, |this, cx| {
 6408                                this.add_edit_breakpoint_block(
 6409                                    anchor,
 6410                                    breakpoint.as_ref(),
 6411                                    BreakpointPromptEditAction::Log,
 6412                                    window,
 6413                                    cx,
 6414                                );
 6415                            })
 6416                            .log_err();
 6417                    }
 6418                })
 6419                .entry(condition_breakpoint_msg, None, {
 6420                    let breakpoint = breakpoint.clone();
 6421                    let weak_editor = weak_editor.clone();
 6422                    move |window, cx| {
 6423                        weak_editor
 6424                            .update(cx, |this, cx| {
 6425                                this.add_edit_breakpoint_block(
 6426                                    anchor,
 6427                                    breakpoint.as_ref(),
 6428                                    BreakpointPromptEditAction::Condition,
 6429                                    window,
 6430                                    cx,
 6431                                );
 6432                            })
 6433                            .log_err();
 6434                    }
 6435                })
 6436                .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
 6437                    weak_editor
 6438                        .update(cx, |this, cx| {
 6439                            this.add_edit_breakpoint_block(
 6440                                anchor,
 6441                                breakpoint.as_ref(),
 6442                                BreakpointPromptEditAction::HitCondition,
 6443                                window,
 6444                                cx,
 6445                            );
 6446                        })
 6447                        .log_err();
 6448                })
 6449        })
 6450    }
 6451
 6452    fn render_breakpoint(
 6453        &self,
 6454        position: Anchor,
 6455        row: DisplayRow,
 6456        breakpoint: &Breakpoint,
 6457        cx: &mut Context<Self>,
 6458    ) -> IconButton {
 6459        let (color, icon) = {
 6460            let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
 6461                (false, false) => ui::IconName::DebugBreakpoint,
 6462                (true, false) => ui::IconName::DebugLogBreakpoint,
 6463                (false, true) => ui::IconName::DebugDisabledBreakpoint,
 6464                (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
 6465            };
 6466
 6467            let color = if self
 6468                .gutter_breakpoint_indicator
 6469                .0
 6470                .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
 6471            {
 6472                Color::Hint
 6473            } else {
 6474                Color::Debugger
 6475            };
 6476
 6477            (color, icon)
 6478        };
 6479
 6480        let breakpoint = Arc::from(breakpoint.clone());
 6481
 6482        IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
 6483            .icon_size(IconSize::XSmall)
 6484            .size(ui::ButtonSize::None)
 6485            .icon_color(color)
 6486            .style(ButtonStyle::Transparent)
 6487            .on_click(cx.listener({
 6488                let breakpoint = breakpoint.clone();
 6489
 6490                move |editor, event: &ClickEvent, window, cx| {
 6491                    let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
 6492                        BreakpointEditAction::InvertState
 6493                    } else {
 6494                        BreakpointEditAction::Toggle
 6495                    };
 6496
 6497                    window.focus(&editor.focus_handle(cx));
 6498                    editor.edit_breakpoint_at_anchor(
 6499                        position,
 6500                        breakpoint.as_ref().clone(),
 6501                        edit_action,
 6502                        cx,
 6503                    );
 6504                }
 6505            }))
 6506            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6507                editor.set_breakpoint_context_menu(
 6508                    row,
 6509                    Some(position),
 6510                    event.down.position,
 6511                    window,
 6512                    cx,
 6513                );
 6514            }))
 6515    }
 6516
 6517    fn build_tasks_context(
 6518        project: &Entity<Project>,
 6519        buffer: &Entity<Buffer>,
 6520        buffer_row: u32,
 6521        tasks: &Arc<RunnableTasks>,
 6522        cx: &mut Context<Self>,
 6523    ) -> Task<Option<task::TaskContext>> {
 6524        let position = Point::new(buffer_row, tasks.column);
 6525        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 6526        let location = Location {
 6527            buffer: buffer.clone(),
 6528            range: range_start..range_start,
 6529        };
 6530        // Fill in the environmental variables from the tree-sitter captures
 6531        let mut captured_task_variables = TaskVariables::default();
 6532        for (capture_name, value) in tasks.extra_variables.clone() {
 6533            captured_task_variables.insert(
 6534                task::VariableName::Custom(capture_name.into()),
 6535                value.clone(),
 6536            );
 6537        }
 6538        project.update(cx, |project, cx| {
 6539            project.task_store().update(cx, |task_store, cx| {
 6540                task_store.task_context_for_location(captured_task_variables, location, cx)
 6541            })
 6542        })
 6543    }
 6544
 6545    pub fn spawn_nearest_task(
 6546        &mut self,
 6547        action: &SpawnNearestTask,
 6548        window: &mut Window,
 6549        cx: &mut Context<Self>,
 6550    ) {
 6551        let Some((workspace, _)) = self.workspace.clone() else {
 6552            return;
 6553        };
 6554        let Some(project) = self.project.clone() else {
 6555            return;
 6556        };
 6557
 6558        // Try to find a closest, enclosing node using tree-sitter that has a
 6559        // task
 6560        let Some((buffer, buffer_row, tasks)) = self
 6561            .find_enclosing_node_task(cx)
 6562            // Or find the task that's closest in row-distance.
 6563            .or_else(|| self.find_closest_task(cx))
 6564        else {
 6565            return;
 6566        };
 6567
 6568        let reveal_strategy = action.reveal;
 6569        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 6570        cx.spawn_in(window, async move |_, cx| {
 6571            let context = task_context.await?;
 6572            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 6573
 6574            let resolved = resolved_task.resolved.as_mut()?;
 6575            resolved.reveal = reveal_strategy;
 6576
 6577            workspace
 6578                .update(cx, |workspace, cx| {
 6579                    workspace::tasks::schedule_resolved_task(
 6580                        workspace,
 6581                        task_source_kind,
 6582                        resolved_task,
 6583                        false,
 6584                        cx,
 6585                    );
 6586                })
 6587                .ok()
 6588        })
 6589        .detach();
 6590    }
 6591
 6592    fn find_closest_task(
 6593        &mut self,
 6594        cx: &mut Context<Self>,
 6595    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6596        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 6597
 6598        let ((buffer_id, row), tasks) = self
 6599            .tasks
 6600            .iter()
 6601            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 6602
 6603        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 6604        let tasks = Arc::new(tasks.to_owned());
 6605        Some((buffer, *row, tasks))
 6606    }
 6607
 6608    fn find_enclosing_node_task(
 6609        &mut self,
 6610        cx: &mut Context<Self>,
 6611    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 6612        let snapshot = self.buffer.read(cx).snapshot(cx);
 6613        let offset = self.selections.newest::<usize>(cx).head();
 6614        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 6615        let buffer_id = excerpt.buffer().remote_id();
 6616
 6617        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 6618        let mut cursor = layer.node().walk();
 6619
 6620        while cursor.goto_first_child_for_byte(offset).is_some() {
 6621            if cursor.node().end_byte() == offset {
 6622                cursor.goto_next_sibling();
 6623            }
 6624        }
 6625
 6626        // Ascend to the smallest ancestor that contains the range and has a task.
 6627        loop {
 6628            let node = cursor.node();
 6629            let node_range = node.byte_range();
 6630            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 6631
 6632            // Check if this node contains our offset
 6633            if node_range.start <= offset && node_range.end >= offset {
 6634                // If it contains offset, check for task
 6635                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 6636                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 6637                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 6638                }
 6639            }
 6640
 6641            if !cursor.goto_parent() {
 6642                break;
 6643            }
 6644        }
 6645        None
 6646    }
 6647
 6648    fn render_run_indicator(
 6649        &self,
 6650        _style: &EditorStyle,
 6651        is_active: bool,
 6652        row: DisplayRow,
 6653        breakpoint: Option<(Anchor, Breakpoint)>,
 6654        cx: &mut Context<Self>,
 6655    ) -> IconButton {
 6656        let color = Color::Muted;
 6657        let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
 6658
 6659        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 6660            .shape(ui::IconButtonShape::Square)
 6661            .icon_size(IconSize::XSmall)
 6662            .icon_color(color)
 6663            .toggle_state(is_active)
 6664            .on_click(cx.listener(move |editor, _e, window, cx| {
 6665                window.focus(&editor.focus_handle(cx));
 6666                editor.toggle_code_actions(
 6667                    &ToggleCodeActions {
 6668                        deployed_from_indicator: Some(row),
 6669                    },
 6670                    window,
 6671                    cx,
 6672                );
 6673            }))
 6674            .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
 6675                editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
 6676            }))
 6677    }
 6678
 6679    pub fn context_menu_visible(&self) -> bool {
 6680        !self.edit_prediction_preview_is_active()
 6681            && self
 6682                .context_menu
 6683                .borrow()
 6684                .as_ref()
 6685                .map_or(false, |menu| menu.visible())
 6686    }
 6687
 6688    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 6689        self.context_menu
 6690            .borrow()
 6691            .as_ref()
 6692            .map(|menu| menu.origin())
 6693    }
 6694
 6695    pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
 6696        self.context_menu_options = Some(options);
 6697    }
 6698
 6699    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 6700    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 6701
 6702    fn render_edit_prediction_popover(
 6703        &mut self,
 6704        text_bounds: &Bounds<Pixels>,
 6705        content_origin: gpui::Point<Pixels>,
 6706        editor_snapshot: &EditorSnapshot,
 6707        visible_row_range: Range<DisplayRow>,
 6708        scroll_top: f32,
 6709        scroll_bottom: f32,
 6710        line_layouts: &[LineWithInvisibles],
 6711        line_height: Pixels,
 6712        scroll_pixel_position: gpui::Point<Pixels>,
 6713        newest_selection_head: Option<DisplayPoint>,
 6714        editor_width: Pixels,
 6715        style: &EditorStyle,
 6716        window: &mut Window,
 6717        cx: &mut App,
 6718    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6719        let active_inline_completion = self.active_inline_completion.as_ref()?;
 6720
 6721        if self.edit_prediction_visible_in_cursor_popover(true) {
 6722            return None;
 6723        }
 6724
 6725        match &active_inline_completion.completion {
 6726            InlineCompletion::Move { target, .. } => {
 6727                let target_display_point = target.to_display_point(editor_snapshot);
 6728
 6729                if self.edit_prediction_requires_modifier() {
 6730                    if !self.edit_prediction_preview_is_active() {
 6731                        return None;
 6732                    }
 6733
 6734                    self.render_edit_prediction_modifier_jump_popover(
 6735                        text_bounds,
 6736                        content_origin,
 6737                        visible_row_range,
 6738                        line_layouts,
 6739                        line_height,
 6740                        scroll_pixel_position,
 6741                        newest_selection_head,
 6742                        target_display_point,
 6743                        window,
 6744                        cx,
 6745                    )
 6746                } else {
 6747                    self.render_edit_prediction_eager_jump_popover(
 6748                        text_bounds,
 6749                        content_origin,
 6750                        editor_snapshot,
 6751                        visible_row_range,
 6752                        scroll_top,
 6753                        scroll_bottom,
 6754                        line_height,
 6755                        scroll_pixel_position,
 6756                        target_display_point,
 6757                        editor_width,
 6758                        window,
 6759                        cx,
 6760                    )
 6761                }
 6762            }
 6763            InlineCompletion::Edit {
 6764                display_mode: EditDisplayMode::Inline,
 6765                ..
 6766            } => None,
 6767            InlineCompletion::Edit {
 6768                display_mode: EditDisplayMode::TabAccept,
 6769                edits,
 6770                ..
 6771            } => {
 6772                let range = &edits.first()?.0;
 6773                let target_display_point = range.end.to_display_point(editor_snapshot);
 6774
 6775                self.render_edit_prediction_end_of_line_popover(
 6776                    "Accept",
 6777                    editor_snapshot,
 6778                    visible_row_range,
 6779                    target_display_point,
 6780                    line_height,
 6781                    scroll_pixel_position,
 6782                    content_origin,
 6783                    editor_width,
 6784                    window,
 6785                    cx,
 6786                )
 6787            }
 6788            InlineCompletion::Edit {
 6789                edits,
 6790                edit_preview,
 6791                display_mode: EditDisplayMode::DiffPopover,
 6792                snapshot,
 6793            } => self.render_edit_prediction_diff_popover(
 6794                text_bounds,
 6795                content_origin,
 6796                editor_snapshot,
 6797                visible_row_range,
 6798                line_layouts,
 6799                line_height,
 6800                scroll_pixel_position,
 6801                newest_selection_head,
 6802                editor_width,
 6803                style,
 6804                edits,
 6805                edit_preview,
 6806                snapshot,
 6807                window,
 6808                cx,
 6809            ),
 6810        }
 6811    }
 6812
 6813    fn render_edit_prediction_modifier_jump_popover(
 6814        &mut self,
 6815        text_bounds: &Bounds<Pixels>,
 6816        content_origin: gpui::Point<Pixels>,
 6817        visible_row_range: Range<DisplayRow>,
 6818        line_layouts: &[LineWithInvisibles],
 6819        line_height: Pixels,
 6820        scroll_pixel_position: gpui::Point<Pixels>,
 6821        newest_selection_head: Option<DisplayPoint>,
 6822        target_display_point: DisplayPoint,
 6823        window: &mut Window,
 6824        cx: &mut App,
 6825    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6826        let scrolled_content_origin =
 6827            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 6828
 6829        const SCROLL_PADDING_Y: Pixels = px(12.);
 6830
 6831        if target_display_point.row() < visible_row_range.start {
 6832            return self.render_edit_prediction_scroll_popover(
 6833                |_| SCROLL_PADDING_Y,
 6834                IconName::ArrowUp,
 6835                visible_row_range,
 6836                line_layouts,
 6837                newest_selection_head,
 6838                scrolled_content_origin,
 6839                window,
 6840                cx,
 6841            );
 6842        } else if target_display_point.row() >= visible_row_range.end {
 6843            return self.render_edit_prediction_scroll_popover(
 6844                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 6845                IconName::ArrowDown,
 6846                visible_row_range,
 6847                line_layouts,
 6848                newest_selection_head,
 6849                scrolled_content_origin,
 6850                window,
 6851                cx,
 6852            );
 6853        }
 6854
 6855        const POLE_WIDTH: Pixels = px(2.);
 6856
 6857        let line_layout =
 6858            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 6859        let target_column = target_display_point.column() as usize;
 6860
 6861        let target_x = line_layout.x_for_index(target_column);
 6862        let target_y =
 6863            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 6864
 6865        let flag_on_right = target_x < text_bounds.size.width / 2.;
 6866
 6867        let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
 6868        border_color.l += 0.001;
 6869
 6870        let mut element = v_flex()
 6871            .items_end()
 6872            .when(flag_on_right, |el| el.items_start())
 6873            .child(if flag_on_right {
 6874                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6875                    .rounded_bl(px(0.))
 6876                    .rounded_tl(px(0.))
 6877                    .border_l_2()
 6878                    .border_color(border_color)
 6879            } else {
 6880                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 6881                    .rounded_br(px(0.))
 6882                    .rounded_tr(px(0.))
 6883                    .border_r_2()
 6884                    .border_color(border_color)
 6885            })
 6886            .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
 6887            .into_any();
 6888
 6889        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6890
 6891        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6892            - point(
 6893                if flag_on_right {
 6894                    POLE_WIDTH
 6895                } else {
 6896                    size.width - POLE_WIDTH
 6897                },
 6898                size.height - line_height,
 6899            );
 6900
 6901        origin.x = origin.x.max(content_origin.x);
 6902
 6903        element.prepaint_at(origin, window, cx);
 6904
 6905        Some((element, origin))
 6906    }
 6907
 6908    fn render_edit_prediction_scroll_popover(
 6909        &mut self,
 6910        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6911        scroll_icon: IconName,
 6912        visible_row_range: Range<DisplayRow>,
 6913        line_layouts: &[LineWithInvisibles],
 6914        newest_selection_head: Option<DisplayPoint>,
 6915        scrolled_content_origin: gpui::Point<Pixels>,
 6916        window: &mut Window,
 6917        cx: &mut App,
 6918    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6919        let mut element = self
 6920            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6921            .into_any();
 6922
 6923        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6924
 6925        let cursor = newest_selection_head?;
 6926        let cursor_row_layout =
 6927            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6928        let cursor_column = cursor.column() as usize;
 6929
 6930        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6931
 6932        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6933
 6934        element.prepaint_at(origin, window, cx);
 6935        Some((element, origin))
 6936    }
 6937
 6938    fn render_edit_prediction_eager_jump_popover(
 6939        &mut self,
 6940        text_bounds: &Bounds<Pixels>,
 6941        content_origin: gpui::Point<Pixels>,
 6942        editor_snapshot: &EditorSnapshot,
 6943        visible_row_range: Range<DisplayRow>,
 6944        scroll_top: f32,
 6945        scroll_bottom: f32,
 6946        line_height: Pixels,
 6947        scroll_pixel_position: gpui::Point<Pixels>,
 6948        target_display_point: DisplayPoint,
 6949        editor_width: Pixels,
 6950        window: &mut Window,
 6951        cx: &mut App,
 6952    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6953        if target_display_point.row().as_f32() < scroll_top {
 6954            let mut element = self
 6955                .render_edit_prediction_line_popover(
 6956                    "Jump to Edit",
 6957                    Some(IconName::ArrowUp),
 6958                    window,
 6959                    cx,
 6960                )?
 6961                .into_any();
 6962
 6963            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6964            let offset = point(
 6965                (text_bounds.size.width - size.width) / 2.,
 6966                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6967            );
 6968
 6969            let origin = text_bounds.origin + offset;
 6970            element.prepaint_at(origin, window, cx);
 6971            Some((element, origin))
 6972        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6973            let mut element = self
 6974                .render_edit_prediction_line_popover(
 6975                    "Jump to Edit",
 6976                    Some(IconName::ArrowDown),
 6977                    window,
 6978                    cx,
 6979                )?
 6980                .into_any();
 6981
 6982            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6983            let offset = point(
 6984                (text_bounds.size.width - size.width) / 2.,
 6985                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6986            );
 6987
 6988            let origin = text_bounds.origin + offset;
 6989            element.prepaint_at(origin, window, cx);
 6990            Some((element, origin))
 6991        } else {
 6992            self.render_edit_prediction_end_of_line_popover(
 6993                "Jump to Edit",
 6994                editor_snapshot,
 6995                visible_row_range,
 6996                target_display_point,
 6997                line_height,
 6998                scroll_pixel_position,
 6999                content_origin,
 7000                editor_width,
 7001                window,
 7002                cx,
 7003            )
 7004        }
 7005    }
 7006
 7007    fn render_edit_prediction_end_of_line_popover(
 7008        self: &mut Editor,
 7009        label: &'static str,
 7010        editor_snapshot: &EditorSnapshot,
 7011        visible_row_range: Range<DisplayRow>,
 7012        target_display_point: DisplayPoint,
 7013        line_height: Pixels,
 7014        scroll_pixel_position: gpui::Point<Pixels>,
 7015        content_origin: gpui::Point<Pixels>,
 7016        editor_width: Pixels,
 7017        window: &mut Window,
 7018        cx: &mut App,
 7019    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7020        let target_line_end = DisplayPoint::new(
 7021            target_display_point.row(),
 7022            editor_snapshot.line_len(target_display_point.row()),
 7023        );
 7024
 7025        let mut element = self
 7026            .render_edit_prediction_line_popover(label, None, window, cx)?
 7027            .into_any();
 7028
 7029        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7030
 7031        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 7032
 7033        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 7034        let mut origin = start_point
 7035            + line_origin
 7036            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 7037        origin.x = origin.x.max(content_origin.x);
 7038
 7039        let max_x = content_origin.x + editor_width - size.width;
 7040
 7041        if origin.x > max_x {
 7042            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 7043
 7044            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 7045                origin.y += offset;
 7046                IconName::ArrowUp
 7047            } else {
 7048                origin.y -= offset;
 7049                IconName::ArrowDown
 7050            };
 7051
 7052            element = self
 7053                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 7054                .into_any();
 7055
 7056            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7057
 7058            origin.x = content_origin.x + editor_width - size.width - px(2.);
 7059        }
 7060
 7061        element.prepaint_at(origin, window, cx);
 7062        Some((element, origin))
 7063    }
 7064
 7065    fn render_edit_prediction_diff_popover(
 7066        self: &Editor,
 7067        text_bounds: &Bounds<Pixels>,
 7068        content_origin: gpui::Point<Pixels>,
 7069        editor_snapshot: &EditorSnapshot,
 7070        visible_row_range: Range<DisplayRow>,
 7071        line_layouts: &[LineWithInvisibles],
 7072        line_height: Pixels,
 7073        scroll_pixel_position: gpui::Point<Pixels>,
 7074        newest_selection_head: Option<DisplayPoint>,
 7075        editor_width: Pixels,
 7076        style: &EditorStyle,
 7077        edits: &Vec<(Range<Anchor>, String)>,
 7078        edit_preview: &Option<language::EditPreview>,
 7079        snapshot: &language::BufferSnapshot,
 7080        window: &mut Window,
 7081        cx: &mut App,
 7082    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 7083        let edit_start = edits
 7084            .first()
 7085            .unwrap()
 7086            .0
 7087            .start
 7088            .to_display_point(editor_snapshot);
 7089        let edit_end = edits
 7090            .last()
 7091            .unwrap()
 7092            .0
 7093            .end
 7094            .to_display_point(editor_snapshot);
 7095
 7096        let is_visible = visible_row_range.contains(&edit_start.row())
 7097            || visible_row_range.contains(&edit_end.row());
 7098        if !is_visible {
 7099            return None;
 7100        }
 7101
 7102        let highlighted_edits =
 7103            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 7104
 7105        let styled_text = highlighted_edits.to_styled_text(&style.text);
 7106        let line_count = highlighted_edits.text.lines().count();
 7107
 7108        const BORDER_WIDTH: Pixels = px(1.);
 7109
 7110        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7111        let has_keybind = keybind.is_some();
 7112
 7113        let mut element = h_flex()
 7114            .items_start()
 7115            .child(
 7116                h_flex()
 7117                    .bg(cx.theme().colors().editor_background)
 7118                    .border(BORDER_WIDTH)
 7119                    .shadow_sm()
 7120                    .border_color(cx.theme().colors().border)
 7121                    .rounded_l_lg()
 7122                    .when(line_count > 1, |el| el.rounded_br_lg())
 7123                    .pr_1()
 7124                    .child(styled_text),
 7125            )
 7126            .child(
 7127                h_flex()
 7128                    .h(line_height + BORDER_WIDTH * 2.)
 7129                    .px_1p5()
 7130                    .gap_1()
 7131                    // Workaround: For some reason, there's a gap if we don't do this
 7132                    .ml(-BORDER_WIDTH)
 7133                    .shadow(smallvec![gpui::BoxShadow {
 7134                        color: gpui::black().opacity(0.05),
 7135                        offset: point(px(1.), px(1.)),
 7136                        blur_radius: px(2.),
 7137                        spread_radius: px(0.),
 7138                    }])
 7139                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 7140                    .border(BORDER_WIDTH)
 7141                    .border_color(cx.theme().colors().border)
 7142                    .rounded_r_lg()
 7143                    .id("edit_prediction_diff_popover_keybind")
 7144                    .when(!has_keybind, |el| {
 7145                        let status_colors = cx.theme().status();
 7146
 7147                        el.bg(status_colors.error_background)
 7148                            .border_color(status_colors.error.opacity(0.6))
 7149                            .child(Icon::new(IconName::Info).color(Color::Error))
 7150                            .cursor_default()
 7151                            .hoverable_tooltip(move |_window, cx| {
 7152                                cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7153                            })
 7154                    })
 7155                    .children(keybind),
 7156            )
 7157            .into_any();
 7158
 7159        let longest_row =
 7160            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 7161        let longest_line_width = if visible_row_range.contains(&longest_row) {
 7162            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 7163        } else {
 7164            layout_line(
 7165                longest_row,
 7166                editor_snapshot,
 7167                style,
 7168                editor_width,
 7169                |_| false,
 7170                window,
 7171                cx,
 7172            )
 7173            .width
 7174        };
 7175
 7176        let viewport_bounds =
 7177            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 7178                right: -EditorElement::SCROLLBAR_WIDTH,
 7179                ..Default::default()
 7180            });
 7181
 7182        let x_after_longest =
 7183            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 7184                - scroll_pixel_position.x;
 7185
 7186        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 7187
 7188        // Fully visible if it can be displayed within the window (allow overlapping other
 7189        // panes). However, this is only allowed if the popover starts within text_bounds.
 7190        let can_position_to_the_right = x_after_longest < text_bounds.right()
 7191            && x_after_longest + element_bounds.width < viewport_bounds.right();
 7192
 7193        let mut origin = if can_position_to_the_right {
 7194            point(
 7195                x_after_longest,
 7196                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 7197                    - scroll_pixel_position.y,
 7198            )
 7199        } else {
 7200            let cursor_row = newest_selection_head.map(|head| head.row());
 7201            let above_edit = edit_start
 7202                .row()
 7203                .0
 7204                .checked_sub(line_count as u32)
 7205                .map(DisplayRow);
 7206            let below_edit = Some(edit_end.row() + 1);
 7207            let above_cursor =
 7208                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 7209            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 7210
 7211            // Place the edit popover adjacent to the edit if there is a location
 7212            // available that is onscreen and does not obscure the cursor. Otherwise,
 7213            // place it adjacent to the cursor.
 7214            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 7215                .into_iter()
 7216                .flatten()
 7217                .find(|&start_row| {
 7218                    let end_row = start_row + line_count as u32;
 7219                    visible_row_range.contains(&start_row)
 7220                        && visible_row_range.contains(&end_row)
 7221                        && cursor_row.map_or(true, |cursor_row| {
 7222                            !((start_row..end_row).contains(&cursor_row))
 7223                        })
 7224                })?;
 7225
 7226            content_origin
 7227                + point(
 7228                    -scroll_pixel_position.x,
 7229                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 7230                )
 7231        };
 7232
 7233        origin.x -= BORDER_WIDTH;
 7234
 7235        window.defer_draw(element, origin, 1);
 7236
 7237        // Do not return an element, since it will already be drawn due to defer_draw.
 7238        None
 7239    }
 7240
 7241    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 7242        px(30.)
 7243    }
 7244
 7245    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 7246        if self.read_only(cx) {
 7247            cx.theme().players().read_only()
 7248        } else {
 7249            self.style.as_ref().unwrap().local_player
 7250        }
 7251    }
 7252
 7253    fn render_edit_prediction_accept_keybind(
 7254        &self,
 7255        window: &mut Window,
 7256        cx: &App,
 7257    ) -> Option<AnyElement> {
 7258        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 7259        let accept_keystroke = accept_binding.keystroke()?;
 7260
 7261        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7262
 7263        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 7264            Color::Accent
 7265        } else {
 7266            Color::Muted
 7267        };
 7268
 7269        h_flex()
 7270            .px_0p5()
 7271            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 7272            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7273            .text_size(TextSize::XSmall.rems(cx))
 7274            .child(h_flex().children(ui::render_modifiers(
 7275                &accept_keystroke.modifiers,
 7276                PlatformStyle::platform(),
 7277                Some(modifiers_color),
 7278                Some(IconSize::XSmall.rems().into()),
 7279                true,
 7280            )))
 7281            .when(is_platform_style_mac, |parent| {
 7282                parent.child(accept_keystroke.key.clone())
 7283            })
 7284            .when(!is_platform_style_mac, |parent| {
 7285                parent.child(
 7286                    Key::new(
 7287                        util::capitalize(&accept_keystroke.key),
 7288                        Some(Color::Default),
 7289                    )
 7290                    .size(Some(IconSize::XSmall.rems().into())),
 7291                )
 7292            })
 7293            .into_any()
 7294            .into()
 7295    }
 7296
 7297    fn render_edit_prediction_line_popover(
 7298        &self,
 7299        label: impl Into<SharedString>,
 7300        icon: Option<IconName>,
 7301        window: &mut Window,
 7302        cx: &App,
 7303    ) -> Option<Stateful<Div>> {
 7304        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 7305
 7306        let keybind = self.render_edit_prediction_accept_keybind(window, cx);
 7307        let has_keybind = keybind.is_some();
 7308
 7309        let result = h_flex()
 7310            .id("ep-line-popover")
 7311            .py_0p5()
 7312            .pl_1()
 7313            .pr(padding_right)
 7314            .gap_1()
 7315            .rounded_md()
 7316            .border_1()
 7317            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7318            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 7319            .shadow_sm()
 7320            .when(!has_keybind, |el| {
 7321                let status_colors = cx.theme().status();
 7322
 7323                el.bg(status_colors.error_background)
 7324                    .border_color(status_colors.error.opacity(0.6))
 7325                    .pl_2()
 7326                    .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
 7327                    .cursor_default()
 7328                    .hoverable_tooltip(move |_window, cx| {
 7329                        cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
 7330                    })
 7331            })
 7332            .children(keybind)
 7333            .child(
 7334                Label::new(label)
 7335                    .size(LabelSize::Small)
 7336                    .when(!has_keybind, |el| {
 7337                        el.color(cx.theme().status().error.into()).strikethrough()
 7338                    }),
 7339            )
 7340            .when(!has_keybind, |el| {
 7341                el.child(
 7342                    h_flex().ml_1().child(
 7343                        Icon::new(IconName::Info)
 7344                            .size(IconSize::Small)
 7345                            .color(cx.theme().status().error.into()),
 7346                    ),
 7347                )
 7348            })
 7349            .when_some(icon, |element, icon| {
 7350                element.child(
 7351                    div()
 7352                        .mt(px(1.5))
 7353                        .child(Icon::new(icon).size(IconSize::Small)),
 7354                )
 7355            });
 7356
 7357        Some(result)
 7358    }
 7359
 7360    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 7361        let accent_color = cx.theme().colors().text_accent;
 7362        let editor_bg_color = cx.theme().colors().editor_background;
 7363        editor_bg_color.blend(accent_color.opacity(0.1))
 7364    }
 7365
 7366    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 7367        let accent_color = cx.theme().colors().text_accent;
 7368        let editor_bg_color = cx.theme().colors().editor_background;
 7369        editor_bg_color.blend(accent_color.opacity(0.6))
 7370    }
 7371
 7372    fn render_edit_prediction_cursor_popover(
 7373        &self,
 7374        min_width: Pixels,
 7375        max_width: Pixels,
 7376        cursor_point: Point,
 7377        style: &EditorStyle,
 7378        accept_keystroke: Option<&gpui::Keystroke>,
 7379        _window: &Window,
 7380        cx: &mut Context<Editor>,
 7381    ) -> Option<AnyElement> {
 7382        let provider = self.edit_prediction_provider.as_ref()?;
 7383
 7384        if provider.provider.needs_terms_acceptance(cx) {
 7385            return Some(
 7386                h_flex()
 7387                    .min_w(min_width)
 7388                    .flex_1()
 7389                    .px_2()
 7390                    .py_1()
 7391                    .gap_3()
 7392                    .elevation_2(cx)
 7393                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 7394                    .id("accept-terms")
 7395                    .cursor_pointer()
 7396                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 7397                    .on_click(cx.listener(|this, _event, window, cx| {
 7398                        cx.stop_propagation();
 7399                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 7400                        window.dispatch_action(
 7401                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 7402                            cx,
 7403                        );
 7404                    }))
 7405                    .child(
 7406                        h_flex()
 7407                            .flex_1()
 7408                            .gap_2()
 7409                            .child(Icon::new(IconName::ZedPredict))
 7410                            .child(Label::new("Accept Terms of Service"))
 7411                            .child(div().w_full())
 7412                            .child(
 7413                                Icon::new(IconName::ArrowUpRight)
 7414                                    .color(Color::Muted)
 7415                                    .size(IconSize::Small),
 7416                            )
 7417                            .into_any_element(),
 7418                    )
 7419                    .into_any(),
 7420            );
 7421        }
 7422
 7423        let is_refreshing = provider.provider.is_refreshing(cx);
 7424
 7425        fn pending_completion_container() -> Div {
 7426            h_flex()
 7427                .h_full()
 7428                .flex_1()
 7429                .gap_2()
 7430                .child(Icon::new(IconName::ZedPredict))
 7431        }
 7432
 7433        let completion = match &self.active_inline_completion {
 7434            Some(prediction) => {
 7435                if !self.has_visible_completions_menu() {
 7436                    const RADIUS: Pixels = px(6.);
 7437                    const BORDER_WIDTH: Pixels = px(1.);
 7438
 7439                    return Some(
 7440                        h_flex()
 7441                            .elevation_2(cx)
 7442                            .border(BORDER_WIDTH)
 7443                            .border_color(cx.theme().colors().border)
 7444                            .when(accept_keystroke.is_none(), |el| {
 7445                                el.border_color(cx.theme().status().error)
 7446                            })
 7447                            .rounded(RADIUS)
 7448                            .rounded_tl(px(0.))
 7449                            .overflow_hidden()
 7450                            .child(div().px_1p5().child(match &prediction.completion {
 7451                                InlineCompletion::Move { target, snapshot } => {
 7452                                    use text::ToPoint as _;
 7453                                    if target.text_anchor.to_point(&snapshot).row > cursor_point.row
 7454                                    {
 7455                                        Icon::new(IconName::ZedPredictDown)
 7456                                    } else {
 7457                                        Icon::new(IconName::ZedPredictUp)
 7458                                    }
 7459                                }
 7460                                InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
 7461                            }))
 7462                            .child(
 7463                                h_flex()
 7464                                    .gap_1()
 7465                                    .py_1()
 7466                                    .px_2()
 7467                                    .rounded_r(RADIUS - BORDER_WIDTH)
 7468                                    .border_l_1()
 7469                                    .border_color(cx.theme().colors().border)
 7470                                    .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7471                                    .when(self.edit_prediction_preview.released_too_fast(), |el| {
 7472                                        el.child(
 7473                                            Label::new("Hold")
 7474                                                .size(LabelSize::Small)
 7475                                                .when(accept_keystroke.is_none(), |el| {
 7476                                                    el.strikethrough()
 7477                                                })
 7478                                                .line_height_style(LineHeightStyle::UiLabel),
 7479                                        )
 7480                                    })
 7481                                    .id("edit_prediction_cursor_popover_keybind")
 7482                                    .when(accept_keystroke.is_none(), |el| {
 7483                                        let status_colors = cx.theme().status();
 7484
 7485                                        el.bg(status_colors.error_background)
 7486                                            .border_color(status_colors.error.opacity(0.6))
 7487                                            .child(Icon::new(IconName::Info).color(Color::Error))
 7488                                            .cursor_default()
 7489                                            .hoverable_tooltip(move |_window, cx| {
 7490                                                cx.new(|_| MissingEditPredictionKeybindingTooltip)
 7491                                                    .into()
 7492                                            })
 7493                                    })
 7494                                    .when_some(
 7495                                        accept_keystroke.as_ref(),
 7496                                        |el, accept_keystroke| {
 7497                                            el.child(h_flex().children(ui::render_modifiers(
 7498                                                &accept_keystroke.modifiers,
 7499                                                PlatformStyle::platform(),
 7500                                                Some(Color::Default),
 7501                                                Some(IconSize::XSmall.rems().into()),
 7502                                                false,
 7503                                            )))
 7504                                        },
 7505                                    ),
 7506                            )
 7507                            .into_any(),
 7508                    );
 7509                }
 7510
 7511                self.render_edit_prediction_cursor_popover_preview(
 7512                    prediction,
 7513                    cursor_point,
 7514                    style,
 7515                    cx,
 7516                )?
 7517            }
 7518
 7519            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 7520                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 7521                    stale_completion,
 7522                    cursor_point,
 7523                    style,
 7524                    cx,
 7525                )?,
 7526
 7527                None => {
 7528                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 7529                }
 7530            },
 7531
 7532            None => pending_completion_container().child(Label::new("No Prediction")),
 7533        };
 7534
 7535        let completion = if is_refreshing {
 7536            completion
 7537                .with_animation(
 7538                    "loading-completion",
 7539                    Animation::new(Duration::from_secs(2))
 7540                        .repeat()
 7541                        .with_easing(pulsating_between(0.4, 0.8)),
 7542                    |label, delta| label.opacity(delta),
 7543                )
 7544                .into_any_element()
 7545        } else {
 7546            completion.into_any_element()
 7547        };
 7548
 7549        let has_completion = self.active_inline_completion.is_some();
 7550
 7551        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 7552        Some(
 7553            h_flex()
 7554                .min_w(min_width)
 7555                .max_w(max_width)
 7556                .flex_1()
 7557                .elevation_2(cx)
 7558                .border_color(cx.theme().colors().border)
 7559                .child(
 7560                    div()
 7561                        .flex_1()
 7562                        .py_1()
 7563                        .px_2()
 7564                        .overflow_hidden()
 7565                        .child(completion),
 7566                )
 7567                .when_some(accept_keystroke, |el, accept_keystroke| {
 7568                    if !accept_keystroke.modifiers.modified() {
 7569                        return el;
 7570                    }
 7571
 7572                    el.child(
 7573                        h_flex()
 7574                            .h_full()
 7575                            .border_l_1()
 7576                            .rounded_r_lg()
 7577                            .border_color(cx.theme().colors().border)
 7578                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 7579                            .gap_1()
 7580                            .py_1()
 7581                            .px_2()
 7582                            .child(
 7583                                h_flex()
 7584                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7585                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 7586                                    .child(h_flex().children(ui::render_modifiers(
 7587                                        &accept_keystroke.modifiers,
 7588                                        PlatformStyle::platform(),
 7589                                        Some(if !has_completion {
 7590                                            Color::Muted
 7591                                        } else {
 7592                                            Color::Default
 7593                                        }),
 7594                                        None,
 7595                                        false,
 7596                                    ))),
 7597                            )
 7598                            .child(Label::new("Preview").into_any_element())
 7599                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 7600                    )
 7601                })
 7602                .into_any(),
 7603        )
 7604    }
 7605
 7606    fn render_edit_prediction_cursor_popover_preview(
 7607        &self,
 7608        completion: &InlineCompletionState,
 7609        cursor_point: Point,
 7610        style: &EditorStyle,
 7611        cx: &mut Context<Editor>,
 7612    ) -> Option<Div> {
 7613        use text::ToPoint as _;
 7614
 7615        fn render_relative_row_jump(
 7616            prefix: impl Into<String>,
 7617            current_row: u32,
 7618            target_row: u32,
 7619        ) -> Div {
 7620            let (row_diff, arrow) = if target_row < current_row {
 7621                (current_row - target_row, IconName::ArrowUp)
 7622            } else {
 7623                (target_row - current_row, IconName::ArrowDown)
 7624            };
 7625
 7626            h_flex()
 7627                .child(
 7628                    Label::new(format!("{}{}", prefix.into(), row_diff))
 7629                        .color(Color::Muted)
 7630                        .size(LabelSize::Small),
 7631                )
 7632                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 7633        }
 7634
 7635        match &completion.completion {
 7636            InlineCompletion::Move {
 7637                target, snapshot, ..
 7638            } => Some(
 7639                h_flex()
 7640                    .px_2()
 7641                    .gap_2()
 7642                    .flex_1()
 7643                    .child(
 7644                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 7645                            Icon::new(IconName::ZedPredictDown)
 7646                        } else {
 7647                            Icon::new(IconName::ZedPredictUp)
 7648                        },
 7649                    )
 7650                    .child(Label::new("Jump to Edit")),
 7651            ),
 7652
 7653            InlineCompletion::Edit {
 7654                edits,
 7655                edit_preview,
 7656                snapshot,
 7657                display_mode: _,
 7658            } => {
 7659                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 7660
 7661                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 7662                    &snapshot,
 7663                    &edits,
 7664                    edit_preview.as_ref()?,
 7665                    true,
 7666                    cx,
 7667                )
 7668                .first_line_preview();
 7669
 7670                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 7671                    .with_default_highlights(&style.text, highlighted_edits.highlights);
 7672
 7673                let preview = h_flex()
 7674                    .gap_1()
 7675                    .min_w_16()
 7676                    .child(styled_text)
 7677                    .when(has_more_lines, |parent| parent.child(""));
 7678
 7679                let left = if first_edit_row != cursor_point.row {
 7680                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 7681                        .into_any_element()
 7682                } else {
 7683                    Icon::new(IconName::ZedPredict).into_any_element()
 7684                };
 7685
 7686                Some(
 7687                    h_flex()
 7688                        .h_full()
 7689                        .flex_1()
 7690                        .gap_2()
 7691                        .pr_1()
 7692                        .overflow_x_hidden()
 7693                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 7694                        .child(left)
 7695                        .child(preview),
 7696                )
 7697            }
 7698        }
 7699    }
 7700
 7701    fn render_context_menu(
 7702        &self,
 7703        style: &EditorStyle,
 7704        max_height_in_lines: u32,
 7705        window: &mut Window,
 7706        cx: &mut Context<Editor>,
 7707    ) -> Option<AnyElement> {
 7708        let menu = self.context_menu.borrow();
 7709        let menu = menu.as_ref()?;
 7710        if !menu.visible() {
 7711            return None;
 7712        };
 7713        Some(menu.render(style, max_height_in_lines, window, cx))
 7714    }
 7715
 7716    fn render_context_menu_aside(
 7717        &mut self,
 7718        max_size: Size<Pixels>,
 7719        window: &mut Window,
 7720        cx: &mut Context<Editor>,
 7721    ) -> Option<AnyElement> {
 7722        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 7723            if menu.visible() {
 7724                menu.render_aside(self, max_size, window, cx)
 7725            } else {
 7726                None
 7727            }
 7728        })
 7729    }
 7730
 7731    fn hide_context_menu(
 7732        &mut self,
 7733        window: &mut Window,
 7734        cx: &mut Context<Self>,
 7735    ) -> Option<CodeContextMenu> {
 7736        cx.notify();
 7737        self.completion_tasks.clear();
 7738        let context_menu = self.context_menu.borrow_mut().take();
 7739        self.stale_inline_completion_in_menu.take();
 7740        self.update_visible_inline_completion(window, cx);
 7741        context_menu
 7742    }
 7743
 7744    fn show_snippet_choices(
 7745        &mut self,
 7746        choices: &Vec<String>,
 7747        selection: Range<Anchor>,
 7748        cx: &mut Context<Self>,
 7749    ) {
 7750        if selection.start.buffer_id.is_none() {
 7751            return;
 7752        }
 7753        let buffer_id = selection.start.buffer_id.unwrap();
 7754        let buffer = self.buffer().read(cx).buffer(buffer_id);
 7755        let id = post_inc(&mut self.next_completion_id);
 7756
 7757        if let Some(buffer) = buffer {
 7758            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 7759                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 7760            ));
 7761        }
 7762    }
 7763
 7764    pub fn insert_snippet(
 7765        &mut self,
 7766        insertion_ranges: &[Range<usize>],
 7767        snippet: Snippet,
 7768        window: &mut Window,
 7769        cx: &mut Context<Self>,
 7770    ) -> Result<()> {
 7771        struct Tabstop<T> {
 7772            is_end_tabstop: bool,
 7773            ranges: Vec<Range<T>>,
 7774            choices: Option<Vec<String>>,
 7775        }
 7776
 7777        let tabstops = self.buffer.update(cx, |buffer, cx| {
 7778            let snippet_text: Arc<str> = snippet.text.clone().into();
 7779            let edits = insertion_ranges
 7780                .iter()
 7781                .cloned()
 7782                .map(|range| (range, snippet_text.clone()));
 7783            buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
 7784
 7785            let snapshot = &*buffer.read(cx);
 7786            let snippet = &snippet;
 7787            snippet
 7788                .tabstops
 7789                .iter()
 7790                .map(|tabstop| {
 7791                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 7792                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 7793                    });
 7794                    let mut tabstop_ranges = tabstop
 7795                        .ranges
 7796                        .iter()
 7797                        .flat_map(|tabstop_range| {
 7798                            let mut delta = 0_isize;
 7799                            insertion_ranges.iter().map(move |insertion_range| {
 7800                                let insertion_start = insertion_range.start as isize + delta;
 7801                                delta +=
 7802                                    snippet.text.len() as isize - insertion_range.len() as isize;
 7803
 7804                                let start = ((insertion_start + tabstop_range.start) as usize)
 7805                                    .min(snapshot.len());
 7806                                let end = ((insertion_start + tabstop_range.end) as usize)
 7807                                    .min(snapshot.len());
 7808                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 7809                            })
 7810                        })
 7811                        .collect::<Vec<_>>();
 7812                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 7813
 7814                    Tabstop {
 7815                        is_end_tabstop,
 7816                        ranges: tabstop_ranges,
 7817                        choices: tabstop.choices.clone(),
 7818                    }
 7819                })
 7820                .collect::<Vec<_>>()
 7821        });
 7822        if let Some(tabstop) = tabstops.first() {
 7823            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7824                s.select_ranges(tabstop.ranges.iter().cloned());
 7825            });
 7826
 7827            if let Some(choices) = &tabstop.choices {
 7828                if let Some(selection) = tabstop.ranges.first() {
 7829                    self.show_snippet_choices(choices, selection.clone(), cx)
 7830                }
 7831            }
 7832
 7833            // If we're already at the last tabstop and it's at the end of the snippet,
 7834            // we're done, we don't need to keep the state around.
 7835            if !tabstop.is_end_tabstop {
 7836                let choices = tabstops
 7837                    .iter()
 7838                    .map(|tabstop| tabstop.choices.clone())
 7839                    .collect();
 7840
 7841                let ranges = tabstops
 7842                    .into_iter()
 7843                    .map(|tabstop| tabstop.ranges)
 7844                    .collect::<Vec<_>>();
 7845
 7846                self.snippet_stack.push(SnippetState {
 7847                    active_index: 0,
 7848                    ranges,
 7849                    choices,
 7850                });
 7851            }
 7852
 7853            // Check whether the just-entered snippet ends with an auto-closable bracket.
 7854            if self.autoclose_regions.is_empty() {
 7855                let snapshot = self.buffer.read(cx).snapshot(cx);
 7856                for selection in &mut self.selections.all::<Point>(cx) {
 7857                    let selection_head = selection.head();
 7858                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 7859                        continue;
 7860                    };
 7861
 7862                    let mut bracket_pair = None;
 7863                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 7864                    let prev_chars = snapshot
 7865                        .reversed_chars_at(selection_head)
 7866                        .collect::<String>();
 7867                    for (pair, enabled) in scope.brackets() {
 7868                        if enabled
 7869                            && pair.close
 7870                            && prev_chars.starts_with(pair.start.as_str())
 7871                            && next_chars.starts_with(pair.end.as_str())
 7872                        {
 7873                            bracket_pair = Some(pair.clone());
 7874                            break;
 7875                        }
 7876                    }
 7877                    if let Some(pair) = bracket_pair {
 7878                        let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
 7879                        let autoclose_enabled =
 7880                            self.use_autoclose && snapshot_settings.use_autoclose;
 7881                        if autoclose_enabled {
 7882                            let start = snapshot.anchor_after(selection_head);
 7883                            let end = snapshot.anchor_after(selection_head);
 7884                            self.autoclose_regions.push(AutocloseRegion {
 7885                                selection_id: selection.id,
 7886                                range: start..end,
 7887                                pair,
 7888                            });
 7889                        }
 7890                    }
 7891                }
 7892            }
 7893        }
 7894        Ok(())
 7895    }
 7896
 7897    pub fn move_to_next_snippet_tabstop(
 7898        &mut self,
 7899        window: &mut Window,
 7900        cx: &mut Context<Self>,
 7901    ) -> bool {
 7902        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 7903    }
 7904
 7905    pub fn move_to_prev_snippet_tabstop(
 7906        &mut self,
 7907        window: &mut Window,
 7908        cx: &mut Context<Self>,
 7909    ) -> bool {
 7910        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 7911    }
 7912
 7913    pub fn move_to_snippet_tabstop(
 7914        &mut self,
 7915        bias: Bias,
 7916        window: &mut Window,
 7917        cx: &mut Context<Self>,
 7918    ) -> bool {
 7919        if let Some(mut snippet) = self.snippet_stack.pop() {
 7920            match bias {
 7921                Bias::Left => {
 7922                    if snippet.active_index > 0 {
 7923                        snippet.active_index -= 1;
 7924                    } else {
 7925                        self.snippet_stack.push(snippet);
 7926                        return false;
 7927                    }
 7928                }
 7929                Bias::Right => {
 7930                    if snippet.active_index + 1 < snippet.ranges.len() {
 7931                        snippet.active_index += 1;
 7932                    } else {
 7933                        self.snippet_stack.push(snippet);
 7934                        return false;
 7935                    }
 7936                }
 7937            }
 7938            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 7939                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7940                    s.select_anchor_ranges(current_ranges.iter().cloned())
 7941                });
 7942
 7943                if let Some(choices) = &snippet.choices[snippet.active_index] {
 7944                    if let Some(selection) = current_ranges.first() {
 7945                        self.show_snippet_choices(&choices, selection.clone(), cx);
 7946                    }
 7947                }
 7948
 7949                // If snippet state is not at the last tabstop, push it back on the stack
 7950                if snippet.active_index + 1 < snippet.ranges.len() {
 7951                    self.snippet_stack.push(snippet);
 7952                }
 7953                return true;
 7954            }
 7955        }
 7956
 7957        false
 7958    }
 7959
 7960    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 7961        self.transact(window, cx, |this, window, cx| {
 7962            this.select_all(&SelectAll, window, cx);
 7963            this.insert("", window, cx);
 7964        });
 7965    }
 7966
 7967    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 7968        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 7969        self.transact(window, cx, |this, window, cx| {
 7970            this.select_autoclose_pair(window, cx);
 7971            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 7972            if !this.linked_edit_ranges.is_empty() {
 7973                let selections = this.selections.all::<MultiBufferPoint>(cx);
 7974                let snapshot = this.buffer.read(cx).snapshot(cx);
 7975
 7976                for selection in selections.iter() {
 7977                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 7978                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 7979                    if selection_start.buffer_id != selection_end.buffer_id {
 7980                        continue;
 7981                    }
 7982                    if let Some(ranges) =
 7983                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 7984                    {
 7985                        for (buffer, entries) in ranges {
 7986                            linked_ranges.entry(buffer).or_default().extend(entries);
 7987                        }
 7988                    }
 7989                }
 7990            }
 7991
 7992            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7993            let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7994            for selection in &mut selections {
 7995                if selection.is_empty() {
 7996                    let old_head = selection.head();
 7997                    let mut new_head =
 7998                        movement::left(&display_map, old_head.to_display_point(&display_map))
 7999                            .to_point(&display_map);
 8000                    if let Some((buffer, line_buffer_range)) = display_map
 8001                        .buffer_snapshot
 8002                        .buffer_line_for_row(MultiBufferRow(old_head.row))
 8003                    {
 8004                        let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
 8005                        let indent_len = match indent_size.kind {
 8006                            IndentKind::Space => {
 8007                                buffer.settings_at(line_buffer_range.start, cx).tab_size
 8008                            }
 8009                            IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 8010                        };
 8011                        if old_head.column <= indent_size.len && old_head.column > 0 {
 8012                            let indent_len = indent_len.get();
 8013                            new_head = cmp::min(
 8014                                new_head,
 8015                                MultiBufferPoint::new(
 8016                                    old_head.row,
 8017                                    ((old_head.column - 1) / indent_len) * indent_len,
 8018                                ),
 8019                            );
 8020                        }
 8021                    }
 8022
 8023                    selection.set_head(new_head, SelectionGoal::None);
 8024                }
 8025            }
 8026
 8027            this.signature_help_state.set_backspace_pressed(true);
 8028            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8029                s.select(selections)
 8030            });
 8031            this.insert("", window, cx);
 8032            let empty_str: Arc<str> = Arc::from("");
 8033            for (buffer, edits) in linked_ranges {
 8034                let snapshot = buffer.read(cx).snapshot();
 8035                use text::ToPoint as TP;
 8036
 8037                let edits = edits
 8038                    .into_iter()
 8039                    .map(|range| {
 8040                        let end_point = TP::to_point(&range.end, &snapshot);
 8041                        let mut start_point = TP::to_point(&range.start, &snapshot);
 8042
 8043                        if end_point == start_point {
 8044                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 8045                                .saturating_sub(1);
 8046                            start_point =
 8047                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 8048                        };
 8049
 8050                        (start_point..end_point, empty_str.clone())
 8051                    })
 8052                    .sorted_by_key(|(range, _)| range.start)
 8053                    .collect::<Vec<_>>();
 8054                buffer.update(cx, |this, cx| {
 8055                    this.edit(edits, None, cx);
 8056                })
 8057            }
 8058            this.refresh_inline_completion(true, false, window, cx);
 8059            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 8060        });
 8061    }
 8062
 8063    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 8064        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8065        self.transact(window, cx, |this, window, cx| {
 8066            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8067                s.move_with(|map, selection| {
 8068                    if selection.is_empty() {
 8069                        let cursor = movement::right(map, selection.head());
 8070                        selection.end = cursor;
 8071                        selection.reversed = true;
 8072                        selection.goal = SelectionGoal::None;
 8073                    }
 8074                })
 8075            });
 8076            this.insert("", window, cx);
 8077            this.refresh_inline_completion(true, false, window, cx);
 8078        });
 8079    }
 8080
 8081    pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
 8082        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8083        if self.move_to_prev_snippet_tabstop(window, cx) {
 8084            return;
 8085        }
 8086        self.outdent(&Outdent, window, cx);
 8087    }
 8088
 8089    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 8090        if self.move_to_next_snippet_tabstop(window, cx) {
 8091            self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8092            return;
 8093        }
 8094        if self.read_only(cx) {
 8095            return;
 8096        }
 8097        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8098        let mut selections = self.selections.all_adjusted(cx);
 8099        let buffer = self.buffer.read(cx);
 8100        let snapshot = buffer.snapshot(cx);
 8101        let rows_iter = selections.iter().map(|s| s.head().row);
 8102        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 8103
 8104        let mut edits = Vec::new();
 8105        let mut prev_edited_row = 0;
 8106        let mut row_delta = 0;
 8107        for selection in &mut selections {
 8108            if selection.start.row != prev_edited_row {
 8109                row_delta = 0;
 8110            }
 8111            prev_edited_row = selection.end.row;
 8112
 8113            // If the selection is non-empty, then increase the indentation of the selected lines.
 8114            if !selection.is_empty() {
 8115                row_delta =
 8116                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8117                continue;
 8118            }
 8119
 8120            // If the selection is empty and the cursor is in the leading whitespace before the
 8121            // suggested indentation, then auto-indent the line.
 8122            let cursor = selection.head();
 8123            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 8124            if let Some(suggested_indent) =
 8125                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 8126            {
 8127                if cursor.column < suggested_indent.len
 8128                    && cursor.column <= current_indent.len
 8129                    && current_indent.len <= suggested_indent.len
 8130                {
 8131                    selection.start = Point::new(cursor.row, suggested_indent.len);
 8132                    selection.end = selection.start;
 8133                    if row_delta == 0 {
 8134                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 8135                            cursor.row,
 8136                            current_indent,
 8137                            suggested_indent,
 8138                        ));
 8139                        row_delta = suggested_indent.len - current_indent.len;
 8140                    }
 8141                    continue;
 8142                }
 8143            }
 8144
 8145            // Otherwise, insert a hard or soft tab.
 8146            let settings = buffer.language_settings_at(cursor, cx);
 8147            let tab_size = if settings.hard_tabs {
 8148                IndentSize::tab()
 8149            } else {
 8150                let tab_size = settings.tab_size.get();
 8151                let char_column = snapshot
 8152                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 8153                    .flat_map(str::chars)
 8154                    .count()
 8155                    + row_delta as usize;
 8156                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 8157                IndentSize::spaces(chars_to_next_tab_stop)
 8158            };
 8159            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 8160            selection.end = selection.start;
 8161            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 8162            row_delta += tab_size.len;
 8163        }
 8164
 8165        self.transact(window, cx, |this, window, cx| {
 8166            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8167            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8168                s.select(selections)
 8169            });
 8170            this.refresh_inline_completion(true, false, window, cx);
 8171        });
 8172    }
 8173
 8174    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 8175        if self.read_only(cx) {
 8176            return;
 8177        }
 8178        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8179        let mut selections = self.selections.all::<Point>(cx);
 8180        let mut prev_edited_row = 0;
 8181        let mut row_delta = 0;
 8182        let mut edits = Vec::new();
 8183        let buffer = self.buffer.read(cx);
 8184        let snapshot = buffer.snapshot(cx);
 8185        for selection in &mut selections {
 8186            if selection.start.row != prev_edited_row {
 8187                row_delta = 0;
 8188            }
 8189            prev_edited_row = selection.end.row;
 8190
 8191            row_delta =
 8192                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 8193        }
 8194
 8195        self.transact(window, cx, |this, window, cx| {
 8196            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 8197            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8198                s.select(selections)
 8199            });
 8200        });
 8201    }
 8202
 8203    fn indent_selection(
 8204        buffer: &MultiBuffer,
 8205        snapshot: &MultiBufferSnapshot,
 8206        selection: &mut Selection<Point>,
 8207        edits: &mut Vec<(Range<Point>, String)>,
 8208        delta_for_start_row: u32,
 8209        cx: &App,
 8210    ) -> u32 {
 8211        let settings = buffer.language_settings_at(selection.start, cx);
 8212        let tab_size = settings.tab_size.get();
 8213        let indent_kind = if settings.hard_tabs {
 8214            IndentKind::Tab
 8215        } else {
 8216            IndentKind::Space
 8217        };
 8218        let mut start_row = selection.start.row;
 8219        let mut end_row = selection.end.row + 1;
 8220
 8221        // If a selection ends at the beginning of a line, don't indent
 8222        // that last line.
 8223        if selection.end.column == 0 && selection.end.row > selection.start.row {
 8224            end_row -= 1;
 8225        }
 8226
 8227        // Avoid re-indenting a row that has already been indented by a
 8228        // previous selection, but still update this selection's column
 8229        // to reflect that indentation.
 8230        if delta_for_start_row > 0 {
 8231            start_row += 1;
 8232            selection.start.column += delta_for_start_row;
 8233            if selection.end.row == selection.start.row {
 8234                selection.end.column += delta_for_start_row;
 8235            }
 8236        }
 8237
 8238        let mut delta_for_end_row = 0;
 8239        let has_multiple_rows = start_row + 1 != end_row;
 8240        for row in start_row..end_row {
 8241            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 8242            let indent_delta = match (current_indent.kind, indent_kind) {
 8243                (IndentKind::Space, IndentKind::Space) => {
 8244                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 8245                    IndentSize::spaces(columns_to_next_tab_stop)
 8246                }
 8247                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 8248                (_, IndentKind::Tab) => IndentSize::tab(),
 8249            };
 8250
 8251            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 8252                0
 8253            } else {
 8254                selection.start.column
 8255            };
 8256            let row_start = Point::new(row, start);
 8257            edits.push((
 8258                row_start..row_start,
 8259                indent_delta.chars().collect::<String>(),
 8260            ));
 8261
 8262            // Update this selection's endpoints to reflect the indentation.
 8263            if row == selection.start.row {
 8264                selection.start.column += indent_delta.len;
 8265            }
 8266            if row == selection.end.row {
 8267                selection.end.column += indent_delta.len;
 8268                delta_for_end_row = indent_delta.len;
 8269            }
 8270        }
 8271
 8272        if selection.start.row == selection.end.row {
 8273            delta_for_start_row + delta_for_end_row
 8274        } else {
 8275            delta_for_end_row
 8276        }
 8277    }
 8278
 8279    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 8280        if self.read_only(cx) {
 8281            return;
 8282        }
 8283        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8284        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8285        let selections = self.selections.all::<Point>(cx);
 8286        let mut deletion_ranges = Vec::new();
 8287        let mut last_outdent = None;
 8288        {
 8289            let buffer = self.buffer.read(cx);
 8290            let snapshot = buffer.snapshot(cx);
 8291            for selection in &selections {
 8292                let settings = buffer.language_settings_at(selection.start, cx);
 8293                let tab_size = settings.tab_size.get();
 8294                let mut rows = selection.spanned_rows(false, &display_map);
 8295
 8296                // Avoid re-outdenting a row that has already been outdented by a
 8297                // previous selection.
 8298                if let Some(last_row) = last_outdent {
 8299                    if last_row == rows.start {
 8300                        rows.start = rows.start.next_row();
 8301                    }
 8302                }
 8303                let has_multiple_rows = rows.len() > 1;
 8304                for row in rows.iter_rows() {
 8305                    let indent_size = snapshot.indent_size_for_line(row);
 8306                    if indent_size.len > 0 {
 8307                        let deletion_len = match indent_size.kind {
 8308                            IndentKind::Space => {
 8309                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 8310                                if columns_to_prev_tab_stop == 0 {
 8311                                    tab_size
 8312                                } else {
 8313                                    columns_to_prev_tab_stop
 8314                                }
 8315                            }
 8316                            IndentKind::Tab => 1,
 8317                        };
 8318                        let start = if has_multiple_rows
 8319                            || deletion_len > selection.start.column
 8320                            || indent_size.len < selection.start.column
 8321                        {
 8322                            0
 8323                        } else {
 8324                            selection.start.column - deletion_len
 8325                        };
 8326                        deletion_ranges.push(
 8327                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 8328                        );
 8329                        last_outdent = Some(row);
 8330                    }
 8331                }
 8332            }
 8333        }
 8334
 8335        self.transact(window, cx, |this, window, cx| {
 8336            this.buffer.update(cx, |buffer, cx| {
 8337                let empty_str: Arc<str> = Arc::default();
 8338                buffer.edit(
 8339                    deletion_ranges
 8340                        .into_iter()
 8341                        .map(|range| (range, empty_str.clone())),
 8342                    None,
 8343                    cx,
 8344                );
 8345            });
 8346            let selections = this.selections.all::<usize>(cx);
 8347            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8348                s.select(selections)
 8349            });
 8350        });
 8351    }
 8352
 8353    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 8354        if self.read_only(cx) {
 8355            return;
 8356        }
 8357        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8358        let selections = self
 8359            .selections
 8360            .all::<usize>(cx)
 8361            .into_iter()
 8362            .map(|s| s.range());
 8363
 8364        self.transact(window, cx, |this, window, cx| {
 8365            this.buffer.update(cx, |buffer, cx| {
 8366                buffer.autoindent_ranges(selections, cx);
 8367            });
 8368            let selections = this.selections.all::<usize>(cx);
 8369            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8370                s.select(selections)
 8371            });
 8372        });
 8373    }
 8374
 8375    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 8376        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8377        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8378        let selections = self.selections.all::<Point>(cx);
 8379
 8380        let mut new_cursors = Vec::new();
 8381        let mut edit_ranges = Vec::new();
 8382        let mut selections = selections.iter().peekable();
 8383        while let Some(selection) = selections.next() {
 8384            let mut rows = selection.spanned_rows(false, &display_map);
 8385            let goal_display_column = selection.head().to_display_point(&display_map).column();
 8386
 8387            // Accumulate contiguous regions of rows that we want to delete.
 8388            while let Some(next_selection) = selections.peek() {
 8389                let next_rows = next_selection.spanned_rows(false, &display_map);
 8390                if next_rows.start <= rows.end {
 8391                    rows.end = next_rows.end;
 8392                    selections.next().unwrap();
 8393                } else {
 8394                    break;
 8395                }
 8396            }
 8397
 8398            let buffer = &display_map.buffer_snapshot;
 8399            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 8400            let edit_end;
 8401            let cursor_buffer_row;
 8402            if buffer.max_point().row >= rows.end.0 {
 8403                // If there's a line after the range, delete the \n from the end of the row range
 8404                // and position the cursor on the next line.
 8405                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 8406                cursor_buffer_row = rows.end;
 8407            } else {
 8408                // If there isn't a line after the range, delete the \n from the line before the
 8409                // start of the row range and position the cursor there.
 8410                edit_start = edit_start.saturating_sub(1);
 8411                edit_end = buffer.len();
 8412                cursor_buffer_row = rows.start.previous_row();
 8413            }
 8414
 8415            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 8416            *cursor.column_mut() =
 8417                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 8418
 8419            new_cursors.push((
 8420                selection.id,
 8421                buffer.anchor_after(cursor.to_point(&display_map)),
 8422            ));
 8423            edit_ranges.push(edit_start..edit_end);
 8424        }
 8425
 8426        self.transact(window, cx, |this, window, cx| {
 8427            let buffer = this.buffer.update(cx, |buffer, cx| {
 8428                let empty_str: Arc<str> = Arc::default();
 8429                buffer.edit(
 8430                    edit_ranges
 8431                        .into_iter()
 8432                        .map(|range| (range, empty_str.clone())),
 8433                    None,
 8434                    cx,
 8435                );
 8436                buffer.snapshot(cx)
 8437            });
 8438            let new_selections = new_cursors
 8439                .into_iter()
 8440                .map(|(id, cursor)| {
 8441                    let cursor = cursor.to_point(&buffer);
 8442                    Selection {
 8443                        id,
 8444                        start: cursor,
 8445                        end: cursor,
 8446                        reversed: false,
 8447                        goal: SelectionGoal::None,
 8448                    }
 8449                })
 8450                .collect();
 8451
 8452            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8453                s.select(new_selections);
 8454            });
 8455        });
 8456    }
 8457
 8458    pub fn join_lines_impl(
 8459        &mut self,
 8460        insert_whitespace: bool,
 8461        window: &mut Window,
 8462        cx: &mut Context<Self>,
 8463    ) {
 8464        if self.read_only(cx) {
 8465            return;
 8466        }
 8467        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 8468        for selection in self.selections.all::<Point>(cx) {
 8469            let start = MultiBufferRow(selection.start.row);
 8470            // Treat single line selections as if they include the next line. Otherwise this action
 8471            // would do nothing for single line selections individual cursors.
 8472            let end = if selection.start.row == selection.end.row {
 8473                MultiBufferRow(selection.start.row + 1)
 8474            } else {
 8475                MultiBufferRow(selection.end.row)
 8476            };
 8477
 8478            if let Some(last_row_range) = row_ranges.last_mut() {
 8479                if start <= last_row_range.end {
 8480                    last_row_range.end = end;
 8481                    continue;
 8482                }
 8483            }
 8484            row_ranges.push(start..end);
 8485        }
 8486
 8487        let snapshot = self.buffer.read(cx).snapshot(cx);
 8488        let mut cursor_positions = Vec::new();
 8489        for row_range in &row_ranges {
 8490            let anchor = snapshot.anchor_before(Point::new(
 8491                row_range.end.previous_row().0,
 8492                snapshot.line_len(row_range.end.previous_row()),
 8493            ));
 8494            cursor_positions.push(anchor..anchor);
 8495        }
 8496
 8497        self.transact(window, cx, |this, window, cx| {
 8498            for row_range in row_ranges.into_iter().rev() {
 8499                for row in row_range.iter_rows().rev() {
 8500                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 8501                    let next_line_row = row.next_row();
 8502                    let indent = snapshot.indent_size_for_line(next_line_row);
 8503                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 8504
 8505                    let replace =
 8506                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 8507                            " "
 8508                        } else {
 8509                            ""
 8510                        };
 8511
 8512                    this.buffer.update(cx, |buffer, cx| {
 8513                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 8514                    });
 8515                }
 8516            }
 8517
 8518            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8519                s.select_anchor_ranges(cursor_positions)
 8520            });
 8521        });
 8522    }
 8523
 8524    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 8525        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8526        self.join_lines_impl(true, window, cx);
 8527    }
 8528
 8529    pub fn sort_lines_case_sensitive(
 8530        &mut self,
 8531        _: &SortLinesCaseSensitive,
 8532        window: &mut Window,
 8533        cx: &mut Context<Self>,
 8534    ) {
 8535        self.manipulate_lines(window, cx, |lines| lines.sort())
 8536    }
 8537
 8538    pub fn sort_lines_case_insensitive(
 8539        &mut self,
 8540        _: &SortLinesCaseInsensitive,
 8541        window: &mut Window,
 8542        cx: &mut Context<Self>,
 8543    ) {
 8544        self.manipulate_lines(window, cx, |lines| {
 8545            lines.sort_by_key(|line| line.to_lowercase())
 8546        })
 8547    }
 8548
 8549    pub fn unique_lines_case_insensitive(
 8550        &mut self,
 8551        _: &UniqueLinesCaseInsensitive,
 8552        window: &mut Window,
 8553        cx: &mut Context<Self>,
 8554    ) {
 8555        self.manipulate_lines(window, cx, |lines| {
 8556            let mut seen = HashSet::default();
 8557            lines.retain(|line| seen.insert(line.to_lowercase()));
 8558        })
 8559    }
 8560
 8561    pub fn unique_lines_case_sensitive(
 8562        &mut self,
 8563        _: &UniqueLinesCaseSensitive,
 8564        window: &mut Window,
 8565        cx: &mut Context<Self>,
 8566    ) {
 8567        self.manipulate_lines(window, cx, |lines| {
 8568            let mut seen = HashSet::default();
 8569            lines.retain(|line| seen.insert(*line));
 8570        })
 8571    }
 8572
 8573    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 8574        let Some(project) = self.project.clone() else {
 8575            return;
 8576        };
 8577        self.reload(project, window, cx)
 8578            .detach_and_notify_err(window, cx);
 8579    }
 8580
 8581    pub fn restore_file(
 8582        &mut self,
 8583        _: &::git::RestoreFile,
 8584        window: &mut Window,
 8585        cx: &mut Context<Self>,
 8586    ) {
 8587        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8588        let mut buffer_ids = HashSet::default();
 8589        let snapshot = self.buffer().read(cx).snapshot(cx);
 8590        for selection in self.selections.all::<usize>(cx) {
 8591            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 8592        }
 8593
 8594        let buffer = self.buffer().read(cx);
 8595        let ranges = buffer_ids
 8596            .into_iter()
 8597            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 8598            .collect::<Vec<_>>();
 8599
 8600        self.restore_hunks_in_ranges(ranges, window, cx);
 8601    }
 8602
 8603    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 8604        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8605        let selections = self
 8606            .selections
 8607            .all(cx)
 8608            .into_iter()
 8609            .map(|s| s.range())
 8610            .collect();
 8611        self.restore_hunks_in_ranges(selections, window, cx);
 8612    }
 8613
 8614    pub fn restore_hunks_in_ranges(
 8615        &mut self,
 8616        ranges: Vec<Range<Point>>,
 8617        window: &mut Window,
 8618        cx: &mut Context<Editor>,
 8619    ) {
 8620        let mut revert_changes = HashMap::default();
 8621        let chunk_by = self
 8622            .snapshot(window, cx)
 8623            .hunks_for_ranges(ranges)
 8624            .into_iter()
 8625            .chunk_by(|hunk| hunk.buffer_id);
 8626        for (buffer_id, hunks) in &chunk_by {
 8627            let hunks = hunks.collect::<Vec<_>>();
 8628            for hunk in &hunks {
 8629                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 8630            }
 8631            self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
 8632        }
 8633        drop(chunk_by);
 8634        if !revert_changes.is_empty() {
 8635            self.transact(window, cx, |editor, window, cx| {
 8636                editor.restore(revert_changes, window, cx);
 8637            });
 8638        }
 8639    }
 8640
 8641    pub fn open_active_item_in_terminal(
 8642        &mut self,
 8643        _: &OpenInTerminal,
 8644        window: &mut Window,
 8645        cx: &mut Context<Self>,
 8646    ) {
 8647        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 8648            let project_path = buffer.read(cx).project_path(cx)?;
 8649            let project = self.project.as_ref()?.read(cx);
 8650            let entry = project.entry_for_path(&project_path, cx)?;
 8651            let parent = match &entry.canonical_path {
 8652                Some(canonical_path) => canonical_path.to_path_buf(),
 8653                None => project.absolute_path(&project_path, cx)?,
 8654            }
 8655            .parent()?
 8656            .to_path_buf();
 8657            Some(parent)
 8658        }) {
 8659            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 8660        }
 8661    }
 8662
 8663    fn set_breakpoint_context_menu(
 8664        &mut self,
 8665        display_row: DisplayRow,
 8666        position: Option<Anchor>,
 8667        clicked_point: gpui::Point<Pixels>,
 8668        window: &mut Window,
 8669        cx: &mut Context<Self>,
 8670    ) {
 8671        if !cx.has_flag::<Debugger>() {
 8672            return;
 8673        }
 8674        let source = self
 8675            .buffer
 8676            .read(cx)
 8677            .snapshot(cx)
 8678            .anchor_before(Point::new(display_row.0, 0u32));
 8679
 8680        let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
 8681
 8682        self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
 8683            self,
 8684            source,
 8685            clicked_point,
 8686            context_menu,
 8687            window,
 8688            cx,
 8689        );
 8690    }
 8691
 8692    fn add_edit_breakpoint_block(
 8693        &mut self,
 8694        anchor: Anchor,
 8695        breakpoint: &Breakpoint,
 8696        edit_action: BreakpointPromptEditAction,
 8697        window: &mut Window,
 8698        cx: &mut Context<Self>,
 8699    ) {
 8700        let weak_editor = cx.weak_entity();
 8701        let bp_prompt = cx.new(|cx| {
 8702            BreakpointPromptEditor::new(
 8703                weak_editor,
 8704                anchor,
 8705                breakpoint.clone(),
 8706                edit_action,
 8707                window,
 8708                cx,
 8709            )
 8710        });
 8711
 8712        let height = bp_prompt.update(cx, |this, cx| {
 8713            this.prompt
 8714                .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
 8715        });
 8716        let cloned_prompt = bp_prompt.clone();
 8717        let blocks = vec![BlockProperties {
 8718            style: BlockStyle::Sticky,
 8719            placement: BlockPlacement::Above(anchor),
 8720            height: Some(height),
 8721            render: Arc::new(move |cx| {
 8722                *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
 8723                cloned_prompt.clone().into_any_element()
 8724            }),
 8725            priority: 0,
 8726        }];
 8727
 8728        let focus_handle = bp_prompt.focus_handle(cx);
 8729        window.focus(&focus_handle);
 8730
 8731        let block_ids = self.insert_blocks(blocks, None, cx);
 8732        bp_prompt.update(cx, |prompt, _| {
 8733            prompt.add_block_ids(block_ids);
 8734        });
 8735    }
 8736
 8737    fn breakpoint_at_cursor_head(
 8738        &self,
 8739        window: &mut Window,
 8740        cx: &mut Context<Self>,
 8741    ) -> Option<(Anchor, Breakpoint)> {
 8742        let cursor_position: Point = self.selections.newest(cx).head();
 8743        self.breakpoint_at_row(cursor_position.row, window, cx)
 8744    }
 8745
 8746    pub(crate) fn breakpoint_at_row(
 8747        &self,
 8748        row: u32,
 8749        window: &mut Window,
 8750        cx: &mut Context<Self>,
 8751    ) -> Option<(Anchor, Breakpoint)> {
 8752        let snapshot = self.snapshot(window, cx);
 8753        let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
 8754
 8755        let project = self.project.clone()?;
 8756
 8757        let buffer_id = breakpoint_position.buffer_id.or_else(|| {
 8758            snapshot
 8759                .buffer_snapshot
 8760                .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
 8761        })?;
 8762
 8763        let enclosing_excerpt = breakpoint_position.excerpt_id;
 8764        let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
 8765        let buffer_snapshot = buffer.read(cx).snapshot();
 8766
 8767        let row = buffer_snapshot
 8768            .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
 8769            .row;
 8770
 8771        let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
 8772        let anchor_end = snapshot
 8773            .buffer_snapshot
 8774            .anchor_after(Point::new(row, line_len));
 8775
 8776        let bp = self
 8777            .breakpoint_store
 8778            .as_ref()?
 8779            .read_with(cx, |breakpoint_store, cx| {
 8780                breakpoint_store
 8781                    .breakpoints(
 8782                        &buffer,
 8783                        Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
 8784                        &buffer_snapshot,
 8785                        cx,
 8786                    )
 8787                    .next()
 8788                    .and_then(|(anchor, bp)| {
 8789                        let breakpoint_row = buffer_snapshot
 8790                            .summary_for_anchor::<text::PointUtf16>(anchor)
 8791                            .row;
 8792
 8793                        if breakpoint_row == row {
 8794                            snapshot
 8795                                .buffer_snapshot
 8796                                .anchor_in_excerpt(enclosing_excerpt, *anchor)
 8797                                .map(|anchor| (anchor, bp.clone()))
 8798                        } else {
 8799                            None
 8800                        }
 8801                    })
 8802            });
 8803        bp
 8804    }
 8805
 8806    pub fn edit_log_breakpoint(
 8807        &mut self,
 8808        _: &EditLogBreakpoint,
 8809        window: &mut Window,
 8810        cx: &mut Context<Self>,
 8811    ) {
 8812        let (anchor, bp) = self
 8813            .breakpoint_at_cursor_head(window, cx)
 8814            .unwrap_or_else(|| {
 8815                let cursor_position: Point = self.selections.newest(cx).head();
 8816
 8817                let breakpoint_position = self
 8818                    .snapshot(window, cx)
 8819                    .display_snapshot
 8820                    .buffer_snapshot
 8821                    .anchor_after(Point::new(cursor_position.row, 0));
 8822
 8823                (
 8824                    breakpoint_position,
 8825                    Breakpoint {
 8826                        message: None,
 8827                        state: BreakpointState::Enabled,
 8828                        condition: None,
 8829                        hit_condition: None,
 8830                    },
 8831                )
 8832            });
 8833
 8834        self.add_edit_breakpoint_block(anchor, &bp, BreakpointPromptEditAction::Log, window, cx);
 8835    }
 8836
 8837    pub fn enable_breakpoint(
 8838        &mut self,
 8839        _: &crate::actions::EnableBreakpoint,
 8840        window: &mut Window,
 8841        cx: &mut Context<Self>,
 8842    ) {
 8843        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8844            if breakpoint.is_disabled() {
 8845                self.edit_breakpoint_at_anchor(
 8846                    anchor,
 8847                    breakpoint,
 8848                    BreakpointEditAction::InvertState,
 8849                    cx,
 8850                );
 8851            }
 8852        }
 8853    }
 8854
 8855    pub fn disable_breakpoint(
 8856        &mut self,
 8857        _: &crate::actions::DisableBreakpoint,
 8858        window: &mut Window,
 8859        cx: &mut Context<Self>,
 8860    ) {
 8861        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8862            if breakpoint.is_enabled() {
 8863                self.edit_breakpoint_at_anchor(
 8864                    anchor,
 8865                    breakpoint,
 8866                    BreakpointEditAction::InvertState,
 8867                    cx,
 8868                );
 8869            }
 8870        }
 8871    }
 8872
 8873    pub fn toggle_breakpoint(
 8874        &mut self,
 8875        _: &crate::actions::ToggleBreakpoint,
 8876        window: &mut Window,
 8877        cx: &mut Context<Self>,
 8878    ) {
 8879        let edit_action = BreakpointEditAction::Toggle;
 8880
 8881        if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
 8882            self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
 8883        } else {
 8884            let cursor_position: Point = self.selections.newest(cx).head();
 8885
 8886            let breakpoint_position = self
 8887                .snapshot(window, cx)
 8888                .display_snapshot
 8889                .buffer_snapshot
 8890                .anchor_after(Point::new(cursor_position.row, 0));
 8891
 8892            self.edit_breakpoint_at_anchor(
 8893                breakpoint_position,
 8894                Breakpoint::new_standard(),
 8895                edit_action,
 8896                cx,
 8897            );
 8898        }
 8899    }
 8900
 8901    pub fn edit_breakpoint_at_anchor(
 8902        &mut self,
 8903        breakpoint_position: Anchor,
 8904        breakpoint: Breakpoint,
 8905        edit_action: BreakpointEditAction,
 8906        cx: &mut Context<Self>,
 8907    ) {
 8908        let Some(breakpoint_store) = &self.breakpoint_store else {
 8909            return;
 8910        };
 8911
 8912        let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
 8913            if breakpoint_position == Anchor::min() {
 8914                self.buffer()
 8915                    .read(cx)
 8916                    .excerpt_buffer_ids()
 8917                    .into_iter()
 8918                    .next()
 8919            } else {
 8920                None
 8921            }
 8922        }) else {
 8923            return;
 8924        };
 8925
 8926        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
 8927            return;
 8928        };
 8929
 8930        breakpoint_store.update(cx, |breakpoint_store, cx| {
 8931            breakpoint_store.toggle_breakpoint(
 8932                buffer,
 8933                (breakpoint_position.text_anchor, breakpoint),
 8934                edit_action,
 8935                cx,
 8936            );
 8937        });
 8938
 8939        cx.notify();
 8940    }
 8941
 8942    #[cfg(any(test, feature = "test-support"))]
 8943    pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
 8944        self.breakpoint_store.clone()
 8945    }
 8946
 8947    pub fn prepare_restore_change(
 8948        &self,
 8949        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 8950        hunk: &MultiBufferDiffHunk,
 8951        cx: &mut App,
 8952    ) -> Option<()> {
 8953        if hunk.is_created_file() {
 8954            return None;
 8955        }
 8956        let buffer = self.buffer.read(cx);
 8957        let diff = buffer.diff_for(hunk.buffer_id)?;
 8958        let buffer = buffer.buffer(hunk.buffer_id)?;
 8959        let buffer = buffer.read(cx);
 8960        let original_text = diff
 8961            .read(cx)
 8962            .base_text()
 8963            .as_rope()
 8964            .slice(hunk.diff_base_byte_range.clone());
 8965        let buffer_snapshot = buffer.snapshot();
 8966        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 8967        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 8968            probe
 8969                .0
 8970                .start
 8971                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 8972                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 8973        }) {
 8974            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 8975            Some(())
 8976        } else {
 8977            None
 8978        }
 8979    }
 8980
 8981    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 8982        self.manipulate_lines(window, cx, |lines| lines.reverse())
 8983    }
 8984
 8985    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 8986        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 8987    }
 8988
 8989    fn manipulate_lines<Fn>(
 8990        &mut self,
 8991        window: &mut Window,
 8992        cx: &mut Context<Self>,
 8993        mut callback: Fn,
 8994    ) where
 8995        Fn: FnMut(&mut Vec<&str>),
 8996    {
 8997        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 8998
 8999        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9000        let buffer = self.buffer.read(cx).snapshot(cx);
 9001
 9002        let mut edits = Vec::new();
 9003
 9004        let selections = self.selections.all::<Point>(cx);
 9005        let mut selections = selections.iter().peekable();
 9006        let mut contiguous_row_selections = Vec::new();
 9007        let mut new_selections = Vec::new();
 9008        let mut added_lines = 0;
 9009        let mut removed_lines = 0;
 9010
 9011        while let Some(selection) = selections.next() {
 9012            let (start_row, end_row) = consume_contiguous_rows(
 9013                &mut contiguous_row_selections,
 9014                selection,
 9015                &display_map,
 9016                &mut selections,
 9017            );
 9018
 9019            let start_point = Point::new(start_row.0, 0);
 9020            let end_point = Point::new(
 9021                end_row.previous_row().0,
 9022                buffer.line_len(end_row.previous_row()),
 9023            );
 9024            let text = buffer
 9025                .text_for_range(start_point..end_point)
 9026                .collect::<String>();
 9027
 9028            let mut lines = text.split('\n').collect_vec();
 9029
 9030            let lines_before = lines.len();
 9031            callback(&mut lines);
 9032            let lines_after = lines.len();
 9033
 9034            edits.push((start_point..end_point, lines.join("\n")));
 9035
 9036            // Selections must change based on added and removed line count
 9037            let start_row =
 9038                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 9039            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 9040            new_selections.push(Selection {
 9041                id: selection.id,
 9042                start: start_row,
 9043                end: end_row,
 9044                goal: SelectionGoal::None,
 9045                reversed: selection.reversed,
 9046            });
 9047
 9048            if lines_after > lines_before {
 9049                added_lines += lines_after - lines_before;
 9050            } else if lines_before > lines_after {
 9051                removed_lines += lines_before - lines_after;
 9052            }
 9053        }
 9054
 9055        self.transact(window, cx, |this, window, cx| {
 9056            let buffer = this.buffer.update(cx, |buffer, cx| {
 9057                buffer.edit(edits, None, cx);
 9058                buffer.snapshot(cx)
 9059            });
 9060
 9061            // Recalculate offsets on newly edited buffer
 9062            let new_selections = new_selections
 9063                .iter()
 9064                .map(|s| {
 9065                    let start_point = Point::new(s.start.0, 0);
 9066                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 9067                    Selection {
 9068                        id: s.id,
 9069                        start: buffer.point_to_offset(start_point),
 9070                        end: buffer.point_to_offset(end_point),
 9071                        goal: s.goal,
 9072                        reversed: s.reversed,
 9073                    }
 9074                })
 9075                .collect();
 9076
 9077            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9078                s.select(new_selections);
 9079            });
 9080
 9081            this.request_autoscroll(Autoscroll::fit(), cx);
 9082        });
 9083    }
 9084
 9085    pub fn convert_to_upper_case(
 9086        &mut self,
 9087        _: &ConvertToUpperCase,
 9088        window: &mut Window,
 9089        cx: &mut Context<Self>,
 9090    ) {
 9091        self.manipulate_text(window, cx, |text| text.to_uppercase())
 9092    }
 9093
 9094    pub fn convert_to_lower_case(
 9095        &mut self,
 9096        _: &ConvertToLowerCase,
 9097        window: &mut Window,
 9098        cx: &mut Context<Self>,
 9099    ) {
 9100        self.manipulate_text(window, cx, |text| text.to_lowercase())
 9101    }
 9102
 9103    pub fn convert_to_title_case(
 9104        &mut self,
 9105        _: &ConvertToTitleCase,
 9106        window: &mut Window,
 9107        cx: &mut Context<Self>,
 9108    ) {
 9109        self.manipulate_text(window, cx, |text| {
 9110            text.split('\n')
 9111                .map(|line| line.to_case(Case::Title))
 9112                .join("\n")
 9113        })
 9114    }
 9115
 9116    pub fn convert_to_snake_case(
 9117        &mut self,
 9118        _: &ConvertToSnakeCase,
 9119        window: &mut Window,
 9120        cx: &mut Context<Self>,
 9121    ) {
 9122        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 9123    }
 9124
 9125    pub fn convert_to_kebab_case(
 9126        &mut self,
 9127        _: &ConvertToKebabCase,
 9128        window: &mut Window,
 9129        cx: &mut Context<Self>,
 9130    ) {
 9131        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 9132    }
 9133
 9134    pub fn convert_to_upper_camel_case(
 9135        &mut self,
 9136        _: &ConvertToUpperCamelCase,
 9137        window: &mut Window,
 9138        cx: &mut Context<Self>,
 9139    ) {
 9140        self.manipulate_text(window, cx, |text| {
 9141            text.split('\n')
 9142                .map(|line| line.to_case(Case::UpperCamel))
 9143                .join("\n")
 9144        })
 9145    }
 9146
 9147    pub fn convert_to_lower_camel_case(
 9148        &mut self,
 9149        _: &ConvertToLowerCamelCase,
 9150        window: &mut Window,
 9151        cx: &mut Context<Self>,
 9152    ) {
 9153        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 9154    }
 9155
 9156    pub fn convert_to_opposite_case(
 9157        &mut self,
 9158        _: &ConvertToOppositeCase,
 9159        window: &mut Window,
 9160        cx: &mut Context<Self>,
 9161    ) {
 9162        self.manipulate_text(window, cx, |text| {
 9163            text.chars()
 9164                .fold(String::with_capacity(text.len()), |mut t, c| {
 9165                    if c.is_uppercase() {
 9166                        t.extend(c.to_lowercase());
 9167                    } else {
 9168                        t.extend(c.to_uppercase());
 9169                    }
 9170                    t
 9171                })
 9172        })
 9173    }
 9174
 9175    pub fn convert_to_rot13(
 9176        &mut self,
 9177        _: &ConvertToRot13,
 9178        window: &mut Window,
 9179        cx: &mut Context<Self>,
 9180    ) {
 9181        self.manipulate_text(window, cx, |text| {
 9182            text.chars()
 9183                .map(|c| match c {
 9184                    'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
 9185                    'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
 9186                    _ => c,
 9187                })
 9188                .collect()
 9189        })
 9190    }
 9191
 9192    pub fn convert_to_rot47(
 9193        &mut self,
 9194        _: &ConvertToRot47,
 9195        window: &mut Window,
 9196        cx: &mut Context<Self>,
 9197    ) {
 9198        self.manipulate_text(window, cx, |text| {
 9199            text.chars()
 9200                .map(|c| {
 9201                    let code_point = c as u32;
 9202                    if code_point >= 33 && code_point <= 126 {
 9203                        return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
 9204                    }
 9205                    c
 9206                })
 9207                .collect()
 9208        })
 9209    }
 9210
 9211    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 9212    where
 9213        Fn: FnMut(&str) -> String,
 9214    {
 9215        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9216        let buffer = self.buffer.read(cx).snapshot(cx);
 9217
 9218        let mut new_selections = Vec::new();
 9219        let mut edits = Vec::new();
 9220        let mut selection_adjustment = 0i32;
 9221
 9222        for selection in self.selections.all::<usize>(cx) {
 9223            let selection_is_empty = selection.is_empty();
 9224
 9225            let (start, end) = if selection_is_empty {
 9226                let word_range = movement::surrounding_word(
 9227                    &display_map,
 9228                    selection.start.to_display_point(&display_map),
 9229                );
 9230                let start = word_range.start.to_offset(&display_map, Bias::Left);
 9231                let end = word_range.end.to_offset(&display_map, Bias::Left);
 9232                (start, end)
 9233            } else {
 9234                (selection.start, selection.end)
 9235            };
 9236
 9237            let text = buffer.text_for_range(start..end).collect::<String>();
 9238            let old_length = text.len() as i32;
 9239            let text = callback(&text);
 9240
 9241            new_selections.push(Selection {
 9242                start: (start as i32 - selection_adjustment) as usize,
 9243                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 9244                goal: SelectionGoal::None,
 9245                ..selection
 9246            });
 9247
 9248            selection_adjustment += old_length - text.len() as i32;
 9249
 9250            edits.push((start..end, text));
 9251        }
 9252
 9253        self.transact(window, cx, |this, window, cx| {
 9254            this.buffer.update(cx, |buffer, cx| {
 9255                buffer.edit(edits, None, cx);
 9256            });
 9257
 9258            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9259                s.select(new_selections);
 9260            });
 9261
 9262            this.request_autoscroll(Autoscroll::fit(), cx);
 9263        });
 9264    }
 9265
 9266    pub fn duplicate(
 9267        &mut self,
 9268        upwards: bool,
 9269        whole_lines: bool,
 9270        window: &mut Window,
 9271        cx: &mut Context<Self>,
 9272    ) {
 9273        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9274
 9275        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9276        let buffer = &display_map.buffer_snapshot;
 9277        let selections = self.selections.all::<Point>(cx);
 9278
 9279        let mut edits = Vec::new();
 9280        let mut selections_iter = selections.iter().peekable();
 9281        while let Some(selection) = selections_iter.next() {
 9282            let mut rows = selection.spanned_rows(false, &display_map);
 9283            // duplicate line-wise
 9284            if whole_lines || selection.start == selection.end {
 9285                // Avoid duplicating the same lines twice.
 9286                while let Some(next_selection) = selections_iter.peek() {
 9287                    let next_rows = next_selection.spanned_rows(false, &display_map);
 9288                    if next_rows.start < rows.end {
 9289                        rows.end = next_rows.end;
 9290                        selections_iter.next().unwrap();
 9291                    } else {
 9292                        break;
 9293                    }
 9294                }
 9295
 9296                // Copy the text from the selected row region and splice it either at the start
 9297                // or end of the region.
 9298                let start = Point::new(rows.start.0, 0);
 9299                let end = Point::new(
 9300                    rows.end.previous_row().0,
 9301                    buffer.line_len(rows.end.previous_row()),
 9302                );
 9303                let text = buffer
 9304                    .text_for_range(start..end)
 9305                    .chain(Some("\n"))
 9306                    .collect::<String>();
 9307                let insert_location = if upwards {
 9308                    Point::new(rows.end.0, 0)
 9309                } else {
 9310                    start
 9311                };
 9312                edits.push((insert_location..insert_location, text));
 9313            } else {
 9314                // duplicate character-wise
 9315                let start = selection.start;
 9316                let end = selection.end;
 9317                let text = buffer.text_for_range(start..end).collect::<String>();
 9318                edits.push((selection.end..selection.end, text));
 9319            }
 9320        }
 9321
 9322        self.transact(window, cx, |this, _, cx| {
 9323            this.buffer.update(cx, |buffer, cx| {
 9324                buffer.edit(edits, None, cx);
 9325            });
 9326
 9327            this.request_autoscroll(Autoscroll::fit(), cx);
 9328        });
 9329    }
 9330
 9331    pub fn duplicate_line_up(
 9332        &mut self,
 9333        _: &DuplicateLineUp,
 9334        window: &mut Window,
 9335        cx: &mut Context<Self>,
 9336    ) {
 9337        self.duplicate(true, true, window, cx);
 9338    }
 9339
 9340    pub fn duplicate_line_down(
 9341        &mut self,
 9342        _: &DuplicateLineDown,
 9343        window: &mut Window,
 9344        cx: &mut Context<Self>,
 9345    ) {
 9346        self.duplicate(false, true, window, cx);
 9347    }
 9348
 9349    pub fn duplicate_selection(
 9350        &mut self,
 9351        _: &DuplicateSelection,
 9352        window: &mut Window,
 9353        cx: &mut Context<Self>,
 9354    ) {
 9355        self.duplicate(false, false, window, cx);
 9356    }
 9357
 9358    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 9359        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9360
 9361        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9362        let buffer = self.buffer.read(cx).snapshot(cx);
 9363
 9364        let mut edits = Vec::new();
 9365        let mut unfold_ranges = Vec::new();
 9366        let mut refold_creases = Vec::new();
 9367
 9368        let selections = self.selections.all::<Point>(cx);
 9369        let mut selections = selections.iter().peekable();
 9370        let mut contiguous_row_selections = Vec::new();
 9371        let mut new_selections = Vec::new();
 9372
 9373        while let Some(selection) = selections.next() {
 9374            // Find all the selections that span a contiguous row range
 9375            let (start_row, end_row) = consume_contiguous_rows(
 9376                &mut contiguous_row_selections,
 9377                selection,
 9378                &display_map,
 9379                &mut selections,
 9380            );
 9381
 9382            // Move the text spanned by the row range to be before the line preceding the row range
 9383            if start_row.0 > 0 {
 9384                let range_to_move = Point::new(
 9385                    start_row.previous_row().0,
 9386                    buffer.line_len(start_row.previous_row()),
 9387                )
 9388                    ..Point::new(
 9389                        end_row.previous_row().0,
 9390                        buffer.line_len(end_row.previous_row()),
 9391                    );
 9392                let insertion_point = display_map
 9393                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 9394                    .0;
 9395
 9396                // Don't move lines across excerpts
 9397                if buffer
 9398                    .excerpt_containing(insertion_point..range_to_move.end)
 9399                    .is_some()
 9400                {
 9401                    let text = buffer
 9402                        .text_for_range(range_to_move.clone())
 9403                        .flat_map(|s| s.chars())
 9404                        .skip(1)
 9405                        .chain(['\n'])
 9406                        .collect::<String>();
 9407
 9408                    edits.push((
 9409                        buffer.anchor_after(range_to_move.start)
 9410                            ..buffer.anchor_before(range_to_move.end),
 9411                        String::new(),
 9412                    ));
 9413                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9414                    edits.push((insertion_anchor..insertion_anchor, text));
 9415
 9416                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 9417
 9418                    // Move selections up
 9419                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9420                        |mut selection| {
 9421                            selection.start.row -= row_delta;
 9422                            selection.end.row -= row_delta;
 9423                            selection
 9424                        },
 9425                    ));
 9426
 9427                    // Move folds up
 9428                    unfold_ranges.push(range_to_move.clone());
 9429                    for fold in display_map.folds_in_range(
 9430                        buffer.anchor_before(range_to_move.start)
 9431                            ..buffer.anchor_after(range_to_move.end),
 9432                    ) {
 9433                        let mut start = fold.range.start.to_point(&buffer);
 9434                        let mut end = fold.range.end.to_point(&buffer);
 9435                        start.row -= row_delta;
 9436                        end.row -= row_delta;
 9437                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9438                    }
 9439                }
 9440            }
 9441
 9442            // If we didn't move line(s), preserve the existing selections
 9443            new_selections.append(&mut contiguous_row_selections);
 9444        }
 9445
 9446        self.transact(window, cx, |this, window, cx| {
 9447            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9448            this.buffer.update(cx, |buffer, cx| {
 9449                for (range, text) in edits {
 9450                    buffer.edit([(range, text)], None, cx);
 9451                }
 9452            });
 9453            this.fold_creases(refold_creases, true, window, cx);
 9454            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9455                s.select(new_selections);
 9456            })
 9457        });
 9458    }
 9459
 9460    pub fn move_line_down(
 9461        &mut self,
 9462        _: &MoveLineDown,
 9463        window: &mut Window,
 9464        cx: &mut Context<Self>,
 9465    ) {
 9466        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9467
 9468        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9469        let buffer = self.buffer.read(cx).snapshot(cx);
 9470
 9471        let mut edits = Vec::new();
 9472        let mut unfold_ranges = Vec::new();
 9473        let mut refold_creases = Vec::new();
 9474
 9475        let selections = self.selections.all::<Point>(cx);
 9476        let mut selections = selections.iter().peekable();
 9477        let mut contiguous_row_selections = Vec::new();
 9478        let mut new_selections = Vec::new();
 9479
 9480        while let Some(selection) = selections.next() {
 9481            // Find all the selections that span a contiguous row range
 9482            let (start_row, end_row) = consume_contiguous_rows(
 9483                &mut contiguous_row_selections,
 9484                selection,
 9485                &display_map,
 9486                &mut selections,
 9487            );
 9488
 9489            // Move the text spanned by the row range to be after the last line of the row range
 9490            if end_row.0 <= buffer.max_point().row {
 9491                let range_to_move =
 9492                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 9493                let insertion_point = display_map
 9494                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 9495                    .0;
 9496
 9497                // Don't move lines across excerpt boundaries
 9498                if buffer
 9499                    .excerpt_containing(range_to_move.start..insertion_point)
 9500                    .is_some()
 9501                {
 9502                    let mut text = String::from("\n");
 9503                    text.extend(buffer.text_for_range(range_to_move.clone()));
 9504                    text.pop(); // Drop trailing newline
 9505                    edits.push((
 9506                        buffer.anchor_after(range_to_move.start)
 9507                            ..buffer.anchor_before(range_to_move.end),
 9508                        String::new(),
 9509                    ));
 9510                    let insertion_anchor = buffer.anchor_after(insertion_point);
 9511                    edits.push((insertion_anchor..insertion_anchor, text));
 9512
 9513                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 9514
 9515                    // Move selections down
 9516                    new_selections.extend(contiguous_row_selections.drain(..).map(
 9517                        |mut selection| {
 9518                            selection.start.row += row_delta;
 9519                            selection.end.row += row_delta;
 9520                            selection
 9521                        },
 9522                    ));
 9523
 9524                    // Move folds down
 9525                    unfold_ranges.push(range_to_move.clone());
 9526                    for fold in display_map.folds_in_range(
 9527                        buffer.anchor_before(range_to_move.start)
 9528                            ..buffer.anchor_after(range_to_move.end),
 9529                    ) {
 9530                        let mut start = fold.range.start.to_point(&buffer);
 9531                        let mut end = fold.range.end.to_point(&buffer);
 9532                        start.row += row_delta;
 9533                        end.row += row_delta;
 9534                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 9535                    }
 9536                }
 9537            }
 9538
 9539            // If we didn't move line(s), preserve the existing selections
 9540            new_selections.append(&mut contiguous_row_selections);
 9541        }
 9542
 9543        self.transact(window, cx, |this, window, cx| {
 9544            this.unfold_ranges(&unfold_ranges, true, true, cx);
 9545            this.buffer.update(cx, |buffer, cx| {
 9546                for (range, text) in edits {
 9547                    buffer.edit([(range, text)], None, cx);
 9548                }
 9549            });
 9550            this.fold_creases(refold_creases, true, window, cx);
 9551            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9552                s.select(new_selections)
 9553            });
 9554        });
 9555    }
 9556
 9557    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 9558        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9559        let text_layout_details = &self.text_layout_details(window);
 9560        self.transact(window, cx, |this, window, cx| {
 9561            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9562                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 9563                s.move_with(|display_map, selection| {
 9564                    if !selection.is_empty() {
 9565                        return;
 9566                    }
 9567
 9568                    let mut head = selection.head();
 9569                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 9570                    if head.column() == display_map.line_len(head.row()) {
 9571                        transpose_offset = display_map
 9572                            .buffer_snapshot
 9573                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9574                    }
 9575
 9576                    if transpose_offset == 0 {
 9577                        return;
 9578                    }
 9579
 9580                    *head.column_mut() += 1;
 9581                    head = display_map.clip_point(head, Bias::Right);
 9582                    let goal = SelectionGoal::HorizontalPosition(
 9583                        display_map
 9584                            .x_for_display_point(head, text_layout_details)
 9585                            .into(),
 9586                    );
 9587                    selection.collapse_to(head, goal);
 9588
 9589                    let transpose_start = display_map
 9590                        .buffer_snapshot
 9591                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 9592                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 9593                        let transpose_end = display_map
 9594                            .buffer_snapshot
 9595                            .clip_offset(transpose_offset + 1, Bias::Right);
 9596                        if let Some(ch) =
 9597                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 9598                        {
 9599                            edits.push((transpose_start..transpose_offset, String::new()));
 9600                            edits.push((transpose_end..transpose_end, ch.to_string()));
 9601                        }
 9602                    }
 9603                });
 9604                edits
 9605            });
 9606            this.buffer
 9607                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9608            let selections = this.selections.all::<usize>(cx);
 9609            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9610                s.select(selections);
 9611            });
 9612        });
 9613    }
 9614
 9615    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 9616        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9617        self.rewrap_impl(RewrapOptions::default(), cx)
 9618    }
 9619
 9620    pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
 9621        let buffer = self.buffer.read(cx).snapshot(cx);
 9622        let selections = self.selections.all::<Point>(cx);
 9623        let mut selections = selections.iter().peekable();
 9624
 9625        let mut edits = Vec::new();
 9626        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 9627
 9628        while let Some(selection) = selections.next() {
 9629            let mut start_row = selection.start.row;
 9630            let mut end_row = selection.end.row;
 9631
 9632            // Skip selections that overlap with a range that has already been rewrapped.
 9633            let selection_range = start_row..end_row;
 9634            if rewrapped_row_ranges
 9635                .iter()
 9636                .any(|range| range.overlaps(&selection_range))
 9637            {
 9638                continue;
 9639            }
 9640
 9641            let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
 9642
 9643            // Since not all lines in the selection may be at the same indent
 9644            // level, choose the indent size that is the most common between all
 9645            // of the lines.
 9646            //
 9647            // If there is a tie, we use the deepest indent.
 9648            let (indent_size, indent_end) = {
 9649                let mut indent_size_occurrences = HashMap::default();
 9650                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 9651
 9652                for row in start_row..=end_row {
 9653                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 9654                    rows_by_indent_size.entry(indent).or_default().push(row);
 9655                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 9656                }
 9657
 9658                let indent_size = indent_size_occurrences
 9659                    .into_iter()
 9660                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 9661                    .map(|(indent, _)| indent)
 9662                    .unwrap_or_default();
 9663                let row = rows_by_indent_size[&indent_size][0];
 9664                let indent_end = Point::new(row, indent_size.len);
 9665
 9666                (indent_size, indent_end)
 9667            };
 9668
 9669            let mut line_prefix = indent_size.chars().collect::<String>();
 9670
 9671            let mut inside_comment = false;
 9672            if let Some(comment_prefix) =
 9673                buffer
 9674                    .language_scope_at(selection.head())
 9675                    .and_then(|language| {
 9676                        language
 9677                            .line_comment_prefixes()
 9678                            .iter()
 9679                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 9680                            .cloned()
 9681                    })
 9682            {
 9683                line_prefix.push_str(&comment_prefix);
 9684                inside_comment = true;
 9685            }
 9686
 9687            let language_settings = buffer.language_settings_at(selection.head(), cx);
 9688            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 9689                RewrapBehavior::InComments => inside_comment,
 9690                RewrapBehavior::InSelections => !selection.is_empty(),
 9691                RewrapBehavior::Anywhere => true,
 9692            };
 9693
 9694            let should_rewrap = options.override_language_settings
 9695                || allow_rewrap_based_on_language
 9696                || self.hard_wrap.is_some();
 9697            if !should_rewrap {
 9698                continue;
 9699            }
 9700
 9701            if selection.is_empty() {
 9702                'expand_upwards: while start_row > 0 {
 9703                    let prev_row = start_row - 1;
 9704                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 9705                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 9706                    {
 9707                        start_row = prev_row;
 9708                    } else {
 9709                        break 'expand_upwards;
 9710                    }
 9711                }
 9712
 9713                'expand_downwards: while end_row < buffer.max_point().row {
 9714                    let next_row = end_row + 1;
 9715                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 9716                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 9717                    {
 9718                        end_row = next_row;
 9719                    } else {
 9720                        break 'expand_downwards;
 9721                    }
 9722                }
 9723            }
 9724
 9725            let start = Point::new(start_row, 0);
 9726            let start_offset = start.to_offset(&buffer);
 9727            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 9728            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 9729            let Some(lines_without_prefixes) = selection_text
 9730                .lines()
 9731                .map(|line| {
 9732                    line.strip_prefix(&line_prefix)
 9733                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 9734                        .ok_or_else(|| {
 9735                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 9736                        })
 9737                })
 9738                .collect::<Result<Vec<_>, _>>()
 9739                .log_err()
 9740            else {
 9741                continue;
 9742            };
 9743
 9744            let wrap_column = self.hard_wrap.unwrap_or_else(|| {
 9745                buffer
 9746                    .language_settings_at(Point::new(start_row, 0), cx)
 9747                    .preferred_line_length as usize
 9748            });
 9749            let wrapped_text = wrap_with_prefix(
 9750                line_prefix,
 9751                lines_without_prefixes.join("\n"),
 9752                wrap_column,
 9753                tab_size,
 9754                options.preserve_existing_whitespace,
 9755            );
 9756
 9757            // TODO: should always use char-based diff while still supporting cursor behavior that
 9758            // matches vim.
 9759            let mut diff_options = DiffOptions::default();
 9760            if options.override_language_settings {
 9761                diff_options.max_word_diff_len = 0;
 9762                diff_options.max_word_diff_line_count = 0;
 9763            } else {
 9764                diff_options.max_word_diff_len = usize::MAX;
 9765                diff_options.max_word_diff_line_count = usize::MAX;
 9766            }
 9767
 9768            for (old_range, new_text) in
 9769                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 9770            {
 9771                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 9772                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 9773                edits.push((edit_start..edit_end, new_text));
 9774            }
 9775
 9776            rewrapped_row_ranges.push(start_row..=end_row);
 9777        }
 9778
 9779        self.buffer
 9780            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 9781    }
 9782
 9783    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 9784        let mut text = String::new();
 9785        let buffer = self.buffer.read(cx).snapshot(cx);
 9786        let mut selections = self.selections.all::<Point>(cx);
 9787        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9788        {
 9789            let max_point = buffer.max_point();
 9790            let mut is_first = true;
 9791            for selection in &mut selections {
 9792                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9793                if is_entire_line {
 9794                    selection.start = Point::new(selection.start.row, 0);
 9795                    if !selection.is_empty() && selection.end.column == 0 {
 9796                        selection.end = cmp::min(max_point, selection.end);
 9797                    } else {
 9798                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 9799                    }
 9800                    selection.goal = SelectionGoal::None;
 9801                }
 9802                if is_first {
 9803                    is_first = false;
 9804                } else {
 9805                    text += "\n";
 9806                }
 9807                let mut len = 0;
 9808                for chunk in buffer.text_for_range(selection.start..selection.end) {
 9809                    text.push_str(chunk);
 9810                    len += chunk.len();
 9811                }
 9812                clipboard_selections.push(ClipboardSelection {
 9813                    len,
 9814                    is_entire_line,
 9815                    first_line_indent: buffer
 9816                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 9817                        .len,
 9818                });
 9819            }
 9820        }
 9821
 9822        self.transact(window, cx, |this, window, cx| {
 9823            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9824                s.select(selections);
 9825            });
 9826            this.insert("", window, cx);
 9827        });
 9828        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 9829    }
 9830
 9831    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 9832        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9833        let item = self.cut_common(window, cx);
 9834        cx.write_to_clipboard(item);
 9835    }
 9836
 9837    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 9838        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9839        self.change_selections(None, window, cx, |s| {
 9840            s.move_with(|snapshot, sel| {
 9841                if sel.is_empty() {
 9842                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 9843                }
 9844            });
 9845        });
 9846        let item = self.cut_common(window, cx);
 9847        cx.set_global(KillRing(item))
 9848    }
 9849
 9850    pub fn kill_ring_yank(
 9851        &mut self,
 9852        _: &KillRingYank,
 9853        window: &mut Window,
 9854        cx: &mut Context<Self>,
 9855    ) {
 9856        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
 9857        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 9858            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 9859                (kill_ring.text().to_string(), kill_ring.metadata_json())
 9860            } else {
 9861                return;
 9862            }
 9863        } else {
 9864            return;
 9865        };
 9866        self.do_paste(&text, metadata, false, window, cx);
 9867    }
 9868
 9869    pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
 9870        self.do_copy(true, cx);
 9871    }
 9872
 9873    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 9874        self.do_copy(false, cx);
 9875    }
 9876
 9877    fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
 9878        let selections = self.selections.all::<Point>(cx);
 9879        let buffer = self.buffer.read(cx).read(cx);
 9880        let mut text = String::new();
 9881
 9882        let mut clipboard_selections = Vec::with_capacity(selections.len());
 9883        {
 9884            let max_point = buffer.max_point();
 9885            let mut is_first = true;
 9886            for selection in &selections {
 9887                let mut start = selection.start;
 9888                let mut end = selection.end;
 9889                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 9890                if is_entire_line {
 9891                    start = Point::new(start.row, 0);
 9892                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 9893                }
 9894
 9895                let mut trimmed_selections = Vec::new();
 9896                if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
 9897                    let row = MultiBufferRow(start.row);
 9898                    let first_indent = buffer.indent_size_for_line(row);
 9899                    if first_indent.len == 0 || start.column > first_indent.len {
 9900                        trimmed_selections.push(start..end);
 9901                    } else {
 9902                        trimmed_selections.push(
 9903                            Point::new(row.0, first_indent.len)
 9904                                ..Point::new(row.0, buffer.line_len(row)),
 9905                        );
 9906                        for row in start.row + 1..=end.row {
 9907                            let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
 9908                            if row_indent_size.len >= first_indent.len {
 9909                                trimmed_selections.push(
 9910                                    Point::new(row, first_indent.len)
 9911                                        ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
 9912                                );
 9913                            } else {
 9914                                trimmed_selections.clear();
 9915                                trimmed_selections.push(start..end);
 9916                                break;
 9917                            }
 9918                        }
 9919                    }
 9920                } else {
 9921                    trimmed_selections.push(start..end);
 9922                }
 9923
 9924                for trimmed_range in trimmed_selections {
 9925                    if is_first {
 9926                        is_first = false;
 9927                    } else {
 9928                        text += "\n";
 9929                    }
 9930                    let mut len = 0;
 9931                    for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
 9932                        text.push_str(chunk);
 9933                        len += chunk.len();
 9934                    }
 9935                    clipboard_selections.push(ClipboardSelection {
 9936                        len,
 9937                        is_entire_line,
 9938                        first_line_indent: buffer
 9939                            .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
 9940                            .len,
 9941                    });
 9942                }
 9943            }
 9944        }
 9945
 9946        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 9947            text,
 9948            clipboard_selections,
 9949        ));
 9950    }
 9951
 9952    pub fn do_paste(
 9953        &mut self,
 9954        text: &String,
 9955        clipboard_selections: Option<Vec<ClipboardSelection>>,
 9956        handle_entire_lines: bool,
 9957        window: &mut Window,
 9958        cx: &mut Context<Self>,
 9959    ) {
 9960        if self.read_only(cx) {
 9961            return;
 9962        }
 9963
 9964        let clipboard_text = Cow::Borrowed(text);
 9965
 9966        self.transact(window, cx, |this, window, cx| {
 9967            if let Some(mut clipboard_selections) = clipboard_selections {
 9968                let old_selections = this.selections.all::<usize>(cx);
 9969                let all_selections_were_entire_line =
 9970                    clipboard_selections.iter().all(|s| s.is_entire_line);
 9971                let first_selection_indent_column =
 9972                    clipboard_selections.first().map(|s| s.first_line_indent);
 9973                if clipboard_selections.len() != old_selections.len() {
 9974                    clipboard_selections.drain(..);
 9975                }
 9976                let cursor_offset = this.selections.last::<usize>(cx).head();
 9977                let mut auto_indent_on_paste = true;
 9978
 9979                this.buffer.update(cx, |buffer, cx| {
 9980                    let snapshot = buffer.read(cx);
 9981                    auto_indent_on_paste = snapshot
 9982                        .language_settings_at(cursor_offset, cx)
 9983                        .auto_indent_on_paste;
 9984
 9985                    let mut start_offset = 0;
 9986                    let mut edits = Vec::new();
 9987                    let mut original_indent_columns = Vec::new();
 9988                    for (ix, selection) in old_selections.iter().enumerate() {
 9989                        let to_insert;
 9990                        let entire_line;
 9991                        let original_indent_column;
 9992                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 9993                            let end_offset = start_offset + clipboard_selection.len;
 9994                            to_insert = &clipboard_text[start_offset..end_offset];
 9995                            entire_line = clipboard_selection.is_entire_line;
 9996                            start_offset = end_offset + 1;
 9997                            original_indent_column = Some(clipboard_selection.first_line_indent);
 9998                        } else {
 9999                            to_insert = clipboard_text.as_str();
10000                            entire_line = all_selections_were_entire_line;
10001                            original_indent_column = first_selection_indent_column
10002                        }
10003
10004                        // If the corresponding selection was empty when this slice of the
10005                        // clipboard text was written, then the entire line containing the
10006                        // selection was copied. If this selection is also currently empty,
10007                        // then paste the line before the current line of the buffer.
10008                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
10009                            let column = selection.start.to_point(&snapshot).column as usize;
10010                            let line_start = selection.start - column;
10011                            line_start..line_start
10012                        } else {
10013                            selection.range()
10014                        };
10015
10016                        edits.push((range, to_insert));
10017                        original_indent_columns.push(original_indent_column);
10018                    }
10019                    drop(snapshot);
10020
10021                    buffer.edit(
10022                        edits,
10023                        if auto_indent_on_paste {
10024                            Some(AutoindentMode::Block {
10025                                original_indent_columns,
10026                            })
10027                        } else {
10028                            None
10029                        },
10030                        cx,
10031                    );
10032                });
10033
10034                let selections = this.selections.all::<usize>(cx);
10035                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10036                    s.select(selections)
10037                });
10038            } else {
10039                this.insert(&clipboard_text, window, cx);
10040            }
10041        });
10042    }
10043
10044    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10045        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10046        if let Some(item) = cx.read_from_clipboard() {
10047            let entries = item.entries();
10048
10049            match entries.first() {
10050                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10051                // of all the pasted entries.
10052                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10053                    .do_paste(
10054                        clipboard_string.text(),
10055                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10056                        true,
10057                        window,
10058                        cx,
10059                    ),
10060                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10061            }
10062        }
10063    }
10064
10065    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10066        if self.read_only(cx) {
10067            return;
10068        }
10069
10070        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10071
10072        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10073            if let Some((selections, _)) =
10074                self.selection_history.transaction(transaction_id).cloned()
10075            {
10076                self.change_selections(None, window, cx, |s| {
10077                    s.select_anchors(selections.to_vec());
10078                });
10079            } else {
10080                log::error!(
10081                    "No entry in selection_history found for undo. \
10082                     This may correspond to a bug where undo does not update the selection. \
10083                     If this is occurring, please add details to \
10084                     https://github.com/zed-industries/zed/issues/22692"
10085                );
10086            }
10087            self.request_autoscroll(Autoscroll::fit(), cx);
10088            self.unmark_text(window, cx);
10089            self.refresh_inline_completion(true, false, window, cx);
10090            cx.emit(EditorEvent::Edited { transaction_id });
10091            cx.emit(EditorEvent::TransactionUndone { transaction_id });
10092        }
10093    }
10094
10095    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10096        if self.read_only(cx) {
10097            return;
10098        }
10099
10100        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10101
10102        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10103            if let Some((_, Some(selections))) =
10104                self.selection_history.transaction(transaction_id).cloned()
10105            {
10106                self.change_selections(None, window, cx, |s| {
10107                    s.select_anchors(selections.to_vec());
10108                });
10109            } else {
10110                log::error!(
10111                    "No entry in selection_history found for redo. \
10112                     This may correspond to a bug where undo does not update the selection. \
10113                     If this is occurring, please add details to \
10114                     https://github.com/zed-industries/zed/issues/22692"
10115                );
10116            }
10117            self.request_autoscroll(Autoscroll::fit(), cx);
10118            self.unmark_text(window, cx);
10119            self.refresh_inline_completion(true, false, window, cx);
10120            cx.emit(EditorEvent::Edited { transaction_id });
10121        }
10122    }
10123
10124    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10125        self.buffer
10126            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10127    }
10128
10129    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10130        self.buffer
10131            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10132    }
10133
10134    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10135        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10136        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10137            s.move_with(|map, selection| {
10138                let cursor = if selection.is_empty() {
10139                    movement::left(map, selection.start)
10140                } else {
10141                    selection.start
10142                };
10143                selection.collapse_to(cursor, SelectionGoal::None);
10144            });
10145        })
10146    }
10147
10148    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10149        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10150        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10151            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10152        })
10153    }
10154
10155    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10156        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10157        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10158            s.move_with(|map, selection| {
10159                let cursor = if selection.is_empty() {
10160                    movement::right(map, selection.end)
10161                } else {
10162                    selection.end
10163                };
10164                selection.collapse_to(cursor, SelectionGoal::None)
10165            });
10166        })
10167    }
10168
10169    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10170        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10171        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10172            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10173        })
10174    }
10175
10176    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10177        if self.take_rename(true, window, cx).is_some() {
10178            return;
10179        }
10180
10181        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10182            cx.propagate();
10183            return;
10184        }
10185
10186        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10187
10188        let text_layout_details = &self.text_layout_details(window);
10189        let selection_count = self.selections.count();
10190        let first_selection = self.selections.first_anchor();
10191
10192        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10193            s.move_with(|map, selection| {
10194                if !selection.is_empty() {
10195                    selection.goal = SelectionGoal::None;
10196                }
10197                let (cursor, goal) = movement::up(
10198                    map,
10199                    selection.start,
10200                    selection.goal,
10201                    false,
10202                    text_layout_details,
10203                );
10204                selection.collapse_to(cursor, goal);
10205            });
10206        });
10207
10208        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10209        {
10210            cx.propagate();
10211        }
10212    }
10213
10214    pub fn move_up_by_lines(
10215        &mut self,
10216        action: &MoveUpByLines,
10217        window: &mut Window,
10218        cx: &mut Context<Self>,
10219    ) {
10220        if self.take_rename(true, window, cx).is_some() {
10221            return;
10222        }
10223
10224        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10225            cx.propagate();
10226            return;
10227        }
10228
10229        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10230
10231        let text_layout_details = &self.text_layout_details(window);
10232
10233        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10234            s.move_with(|map, selection| {
10235                if !selection.is_empty() {
10236                    selection.goal = SelectionGoal::None;
10237                }
10238                let (cursor, goal) = movement::up_by_rows(
10239                    map,
10240                    selection.start,
10241                    action.lines,
10242                    selection.goal,
10243                    false,
10244                    text_layout_details,
10245                );
10246                selection.collapse_to(cursor, goal);
10247            });
10248        })
10249    }
10250
10251    pub fn move_down_by_lines(
10252        &mut self,
10253        action: &MoveDownByLines,
10254        window: &mut Window,
10255        cx: &mut Context<Self>,
10256    ) {
10257        if self.take_rename(true, window, cx).is_some() {
10258            return;
10259        }
10260
10261        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10262            cx.propagate();
10263            return;
10264        }
10265
10266        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10267
10268        let text_layout_details = &self.text_layout_details(window);
10269
10270        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10271            s.move_with(|map, selection| {
10272                if !selection.is_empty() {
10273                    selection.goal = SelectionGoal::None;
10274                }
10275                let (cursor, goal) = movement::down_by_rows(
10276                    map,
10277                    selection.start,
10278                    action.lines,
10279                    selection.goal,
10280                    false,
10281                    text_layout_details,
10282                );
10283                selection.collapse_to(cursor, goal);
10284            });
10285        })
10286    }
10287
10288    pub fn select_down_by_lines(
10289        &mut self,
10290        action: &SelectDownByLines,
10291        window: &mut Window,
10292        cx: &mut Context<Self>,
10293    ) {
10294        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10295        let text_layout_details = &self.text_layout_details(window);
10296        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10297            s.move_heads_with(|map, head, goal| {
10298                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10299            })
10300        })
10301    }
10302
10303    pub fn select_up_by_lines(
10304        &mut self,
10305        action: &SelectUpByLines,
10306        window: &mut Window,
10307        cx: &mut Context<Self>,
10308    ) {
10309        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10310        let text_layout_details = &self.text_layout_details(window);
10311        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10312            s.move_heads_with(|map, head, goal| {
10313                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10314            })
10315        })
10316    }
10317
10318    pub fn select_page_up(
10319        &mut self,
10320        _: &SelectPageUp,
10321        window: &mut Window,
10322        cx: &mut Context<Self>,
10323    ) {
10324        let Some(row_count) = self.visible_row_count() else {
10325            return;
10326        };
10327
10328        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10329
10330        let text_layout_details = &self.text_layout_details(window);
10331
10332        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10333            s.move_heads_with(|map, head, goal| {
10334                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10335            })
10336        })
10337    }
10338
10339    pub fn move_page_up(
10340        &mut self,
10341        action: &MovePageUp,
10342        window: &mut Window,
10343        cx: &mut Context<Self>,
10344    ) {
10345        if self.take_rename(true, window, cx).is_some() {
10346            return;
10347        }
10348
10349        if self
10350            .context_menu
10351            .borrow_mut()
10352            .as_mut()
10353            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10354            .unwrap_or(false)
10355        {
10356            return;
10357        }
10358
10359        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10360            cx.propagate();
10361            return;
10362        }
10363
10364        let Some(row_count) = self.visible_row_count() else {
10365            return;
10366        };
10367
10368        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10369
10370        let autoscroll = if action.center_cursor {
10371            Autoscroll::center()
10372        } else {
10373            Autoscroll::fit()
10374        };
10375
10376        let text_layout_details = &self.text_layout_details(window);
10377
10378        self.change_selections(Some(autoscroll), 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::up_by_rows(
10384                    map,
10385                    selection.end,
10386                    row_count,
10387                    selection.goal,
10388                    false,
10389                    text_layout_details,
10390                );
10391                selection.collapse_to(cursor, goal);
10392            });
10393        });
10394    }
10395
10396    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10397        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10398        let text_layout_details = &self.text_layout_details(window);
10399        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10400            s.move_heads_with(|map, head, goal| {
10401                movement::up(map, head, goal, false, text_layout_details)
10402            })
10403        })
10404    }
10405
10406    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10407        self.take_rename(true, window, cx);
10408
10409        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10410            cx.propagate();
10411            return;
10412        }
10413
10414        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10415
10416        let text_layout_details = &self.text_layout_details(window);
10417        let selection_count = self.selections.count();
10418        let first_selection = self.selections.first_anchor();
10419
10420        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10421            s.move_with(|map, selection| {
10422                if !selection.is_empty() {
10423                    selection.goal = SelectionGoal::None;
10424                }
10425                let (cursor, goal) = movement::down(
10426                    map,
10427                    selection.end,
10428                    selection.goal,
10429                    false,
10430                    text_layout_details,
10431                );
10432                selection.collapse_to(cursor, goal);
10433            });
10434        });
10435
10436        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10437        {
10438            cx.propagate();
10439        }
10440    }
10441
10442    pub fn select_page_down(
10443        &mut self,
10444        _: &SelectPageDown,
10445        window: &mut Window,
10446        cx: &mut Context<Self>,
10447    ) {
10448        let Some(row_count) = self.visible_row_count() else {
10449            return;
10450        };
10451
10452        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10453
10454        let text_layout_details = &self.text_layout_details(window);
10455
10456        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10457            s.move_heads_with(|map, head, goal| {
10458                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10459            })
10460        })
10461    }
10462
10463    pub fn move_page_down(
10464        &mut self,
10465        action: &MovePageDown,
10466        window: &mut Window,
10467        cx: &mut Context<Self>,
10468    ) {
10469        if self.take_rename(true, window, cx).is_some() {
10470            return;
10471        }
10472
10473        if self
10474            .context_menu
10475            .borrow_mut()
10476            .as_mut()
10477            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10478            .unwrap_or(false)
10479        {
10480            return;
10481        }
10482
10483        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10484            cx.propagate();
10485            return;
10486        }
10487
10488        let Some(row_count) = self.visible_row_count() else {
10489            return;
10490        };
10491
10492        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10493
10494        let autoscroll = if action.center_cursor {
10495            Autoscroll::center()
10496        } else {
10497            Autoscroll::fit()
10498        };
10499
10500        let text_layout_details = &self.text_layout_details(window);
10501        self.change_selections(Some(autoscroll), window, cx, |s| {
10502            s.move_with(|map, selection| {
10503                if !selection.is_empty() {
10504                    selection.goal = SelectionGoal::None;
10505                }
10506                let (cursor, goal) = movement::down_by_rows(
10507                    map,
10508                    selection.end,
10509                    row_count,
10510                    selection.goal,
10511                    false,
10512                    text_layout_details,
10513                );
10514                selection.collapse_to(cursor, goal);
10515            });
10516        });
10517    }
10518
10519    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10520        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10521        let text_layout_details = &self.text_layout_details(window);
10522        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10523            s.move_heads_with(|map, head, goal| {
10524                movement::down(map, head, goal, false, text_layout_details)
10525            })
10526        });
10527    }
10528
10529    pub fn context_menu_first(
10530        &mut self,
10531        _: &ContextMenuFirst,
10532        _window: &mut Window,
10533        cx: &mut Context<Self>,
10534    ) {
10535        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10536            context_menu.select_first(self.completion_provider.as_deref(), cx);
10537        }
10538    }
10539
10540    pub fn context_menu_prev(
10541        &mut self,
10542        _: &ContextMenuPrevious,
10543        _window: &mut Window,
10544        cx: &mut Context<Self>,
10545    ) {
10546        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10547            context_menu.select_prev(self.completion_provider.as_deref(), cx);
10548        }
10549    }
10550
10551    pub fn context_menu_next(
10552        &mut self,
10553        _: &ContextMenuNext,
10554        _window: &mut Window,
10555        cx: &mut Context<Self>,
10556    ) {
10557        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10558            context_menu.select_next(self.completion_provider.as_deref(), cx);
10559        }
10560    }
10561
10562    pub fn context_menu_last(
10563        &mut self,
10564        _: &ContextMenuLast,
10565        _window: &mut Window,
10566        cx: &mut Context<Self>,
10567    ) {
10568        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10569            context_menu.select_last(self.completion_provider.as_deref(), cx);
10570        }
10571    }
10572
10573    pub fn move_to_previous_word_start(
10574        &mut self,
10575        _: &MoveToPreviousWordStart,
10576        window: &mut Window,
10577        cx: &mut Context<Self>,
10578    ) {
10579        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10580        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10581            s.move_cursors_with(|map, head, _| {
10582                (
10583                    movement::previous_word_start(map, head),
10584                    SelectionGoal::None,
10585                )
10586            });
10587        })
10588    }
10589
10590    pub fn move_to_previous_subword_start(
10591        &mut self,
10592        _: &MoveToPreviousSubwordStart,
10593        window: &mut Window,
10594        cx: &mut Context<Self>,
10595    ) {
10596        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10597        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10598            s.move_cursors_with(|map, head, _| {
10599                (
10600                    movement::previous_subword_start(map, head),
10601                    SelectionGoal::None,
10602                )
10603            });
10604        })
10605    }
10606
10607    pub fn select_to_previous_word_start(
10608        &mut self,
10609        _: &SelectToPreviousWordStart,
10610        window: &mut Window,
10611        cx: &mut Context<Self>,
10612    ) {
10613        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10614        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10615            s.move_heads_with(|map, head, _| {
10616                (
10617                    movement::previous_word_start(map, head),
10618                    SelectionGoal::None,
10619                )
10620            });
10621        })
10622    }
10623
10624    pub fn select_to_previous_subword_start(
10625        &mut self,
10626        _: &SelectToPreviousSubwordStart,
10627        window: &mut Window,
10628        cx: &mut Context<Self>,
10629    ) {
10630        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10631        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10632            s.move_heads_with(|map, head, _| {
10633                (
10634                    movement::previous_subword_start(map, head),
10635                    SelectionGoal::None,
10636                )
10637            });
10638        })
10639    }
10640
10641    pub fn delete_to_previous_word_start(
10642        &mut self,
10643        action: &DeleteToPreviousWordStart,
10644        window: &mut Window,
10645        cx: &mut Context<Self>,
10646    ) {
10647        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10648        self.transact(window, cx, |this, window, cx| {
10649            this.select_autoclose_pair(window, cx);
10650            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10651                s.move_with(|map, selection| {
10652                    if selection.is_empty() {
10653                        let cursor = if action.ignore_newlines {
10654                            movement::previous_word_start(map, selection.head())
10655                        } else {
10656                            movement::previous_word_start_or_newline(map, selection.head())
10657                        };
10658                        selection.set_head(cursor, SelectionGoal::None);
10659                    }
10660                });
10661            });
10662            this.insert("", window, cx);
10663        });
10664    }
10665
10666    pub fn delete_to_previous_subword_start(
10667        &mut self,
10668        _: &DeleteToPreviousSubwordStart,
10669        window: &mut Window,
10670        cx: &mut Context<Self>,
10671    ) {
10672        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10673        self.transact(window, cx, |this, window, cx| {
10674            this.select_autoclose_pair(window, cx);
10675            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10676                s.move_with(|map, selection| {
10677                    if selection.is_empty() {
10678                        let cursor = movement::previous_subword_start(map, selection.head());
10679                        selection.set_head(cursor, SelectionGoal::None);
10680                    }
10681                });
10682            });
10683            this.insert("", window, cx);
10684        });
10685    }
10686
10687    pub fn move_to_next_word_end(
10688        &mut self,
10689        _: &MoveToNextWordEnd,
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_cursors_with(|map, head, _| {
10696                (movement::next_word_end(map, head), SelectionGoal::None)
10697            });
10698        })
10699    }
10700
10701    pub fn move_to_next_subword_end(
10702        &mut self,
10703        _: &MoveToNextSubwordEnd,
10704        window: &mut Window,
10705        cx: &mut Context<Self>,
10706    ) {
10707        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10708        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10709            s.move_cursors_with(|map, head, _| {
10710                (movement::next_subword_end(map, head), SelectionGoal::None)
10711            });
10712        })
10713    }
10714
10715    pub fn select_to_next_word_end(
10716        &mut self,
10717        _: &SelectToNextWordEnd,
10718        window: &mut Window,
10719        cx: &mut Context<Self>,
10720    ) {
10721        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10722        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10723            s.move_heads_with(|map, head, _| {
10724                (movement::next_word_end(map, head), SelectionGoal::None)
10725            });
10726        })
10727    }
10728
10729    pub fn select_to_next_subword_end(
10730        &mut self,
10731        _: &SelectToNextSubwordEnd,
10732        window: &mut Window,
10733        cx: &mut Context<Self>,
10734    ) {
10735        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10736        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10737            s.move_heads_with(|map, head, _| {
10738                (movement::next_subword_end(map, head), SelectionGoal::None)
10739            });
10740        })
10741    }
10742
10743    pub fn delete_to_next_word_end(
10744        &mut self,
10745        action: &DeleteToNextWordEnd,
10746        window: &mut Window,
10747        cx: &mut Context<Self>,
10748    ) {
10749        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10750        self.transact(window, cx, |this, window, cx| {
10751            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10752                s.move_with(|map, selection| {
10753                    if selection.is_empty() {
10754                        let cursor = if action.ignore_newlines {
10755                            movement::next_word_end(map, selection.head())
10756                        } else {
10757                            movement::next_word_end_or_newline(map, selection.head())
10758                        };
10759                        selection.set_head(cursor, SelectionGoal::None);
10760                    }
10761                });
10762            });
10763            this.insert("", window, cx);
10764        });
10765    }
10766
10767    pub fn delete_to_next_subword_end(
10768        &mut self,
10769        _: &DeleteToNextSubwordEnd,
10770        window: &mut Window,
10771        cx: &mut Context<Self>,
10772    ) {
10773        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10774        self.transact(window, cx, |this, window, cx| {
10775            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10776                s.move_with(|map, selection| {
10777                    if selection.is_empty() {
10778                        let cursor = movement::next_subword_end(map, selection.head());
10779                        selection.set_head(cursor, SelectionGoal::None);
10780                    }
10781                });
10782            });
10783            this.insert("", window, cx);
10784        });
10785    }
10786
10787    pub fn move_to_beginning_of_line(
10788        &mut self,
10789        action: &MoveToBeginningOfLine,
10790        window: &mut Window,
10791        cx: &mut Context<Self>,
10792    ) {
10793        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10794        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10795            s.move_cursors_with(|map, head, _| {
10796                (
10797                    movement::indented_line_beginning(
10798                        map,
10799                        head,
10800                        action.stop_at_soft_wraps,
10801                        action.stop_at_indent,
10802                    ),
10803                    SelectionGoal::None,
10804                )
10805            });
10806        })
10807    }
10808
10809    pub fn select_to_beginning_of_line(
10810        &mut self,
10811        action: &SelectToBeginningOfLine,
10812        window: &mut Window,
10813        cx: &mut Context<Self>,
10814    ) {
10815        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10816        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10817            s.move_heads_with(|map, head, _| {
10818                (
10819                    movement::indented_line_beginning(
10820                        map,
10821                        head,
10822                        action.stop_at_soft_wraps,
10823                        action.stop_at_indent,
10824                    ),
10825                    SelectionGoal::None,
10826                )
10827            });
10828        });
10829    }
10830
10831    pub fn delete_to_beginning_of_line(
10832        &mut self,
10833        action: &DeleteToBeginningOfLine,
10834        window: &mut Window,
10835        cx: &mut Context<Self>,
10836    ) {
10837        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10838        self.transact(window, cx, |this, window, cx| {
10839            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10840                s.move_with(|_, selection| {
10841                    selection.reversed = true;
10842                });
10843            });
10844
10845            this.select_to_beginning_of_line(
10846                &SelectToBeginningOfLine {
10847                    stop_at_soft_wraps: false,
10848                    stop_at_indent: action.stop_at_indent,
10849                },
10850                window,
10851                cx,
10852            );
10853            this.backspace(&Backspace, window, cx);
10854        });
10855    }
10856
10857    pub fn move_to_end_of_line(
10858        &mut self,
10859        action: &MoveToEndOfLine,
10860        window: &mut Window,
10861        cx: &mut Context<Self>,
10862    ) {
10863        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10864        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10865            s.move_cursors_with(|map, head, _| {
10866                (
10867                    movement::line_end(map, head, action.stop_at_soft_wraps),
10868                    SelectionGoal::None,
10869                )
10870            });
10871        })
10872    }
10873
10874    pub fn select_to_end_of_line(
10875        &mut self,
10876        action: &SelectToEndOfLine,
10877        window: &mut Window,
10878        cx: &mut Context<Self>,
10879    ) {
10880        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10881        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10882            s.move_heads_with(|map, head, _| {
10883                (
10884                    movement::line_end(map, head, action.stop_at_soft_wraps),
10885                    SelectionGoal::None,
10886                )
10887            });
10888        })
10889    }
10890
10891    pub fn delete_to_end_of_line(
10892        &mut self,
10893        _: &DeleteToEndOfLine,
10894        window: &mut Window,
10895        cx: &mut Context<Self>,
10896    ) {
10897        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10898        self.transact(window, cx, |this, window, cx| {
10899            this.select_to_end_of_line(
10900                &SelectToEndOfLine {
10901                    stop_at_soft_wraps: false,
10902                },
10903                window,
10904                cx,
10905            );
10906            this.delete(&Delete, window, cx);
10907        });
10908    }
10909
10910    pub fn cut_to_end_of_line(
10911        &mut self,
10912        _: &CutToEndOfLine,
10913        window: &mut Window,
10914        cx: &mut Context<Self>,
10915    ) {
10916        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10917        self.transact(window, cx, |this, window, cx| {
10918            this.select_to_end_of_line(
10919                &SelectToEndOfLine {
10920                    stop_at_soft_wraps: false,
10921                },
10922                window,
10923                cx,
10924            );
10925            this.cut(&Cut, window, cx);
10926        });
10927    }
10928
10929    pub fn move_to_start_of_paragraph(
10930        &mut self,
10931        _: &MoveToStartOfParagraph,
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_with(|map, selection| {
10942                selection.collapse_to(
10943                    movement::start_of_paragraph(map, selection.head(), 1),
10944                    SelectionGoal::None,
10945                )
10946            });
10947        })
10948    }
10949
10950    pub fn move_to_end_of_paragraph(
10951        &mut self,
10952        _: &MoveToEndOfParagraph,
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_with(|map, selection| {
10963                selection.collapse_to(
10964                    movement::end_of_paragraph(map, selection.head(), 1),
10965                    SelectionGoal::None,
10966                )
10967            });
10968        })
10969    }
10970
10971    pub fn select_to_start_of_paragraph(
10972        &mut self,
10973        _: &SelectToStartOfParagraph,
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_heads_with(|map, head, _| {
10984                (
10985                    movement::start_of_paragraph(map, head, 1),
10986                    SelectionGoal::None,
10987                )
10988            });
10989        })
10990    }
10991
10992    pub fn select_to_end_of_paragraph(
10993        &mut self,
10994        _: &SelectToEndOfParagraph,
10995        window: &mut Window,
10996        cx: &mut Context<Self>,
10997    ) {
10998        if matches!(self.mode, EditorMode::SingleLine { .. }) {
10999            cx.propagate();
11000            return;
11001        }
11002        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11003        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11004            s.move_heads_with(|map, head, _| {
11005                (
11006                    movement::end_of_paragraph(map, head, 1),
11007                    SelectionGoal::None,
11008                )
11009            });
11010        })
11011    }
11012
11013    pub fn move_to_start_of_excerpt(
11014        &mut self,
11015        _: &MoveToStartOfExcerpt,
11016        window: &mut Window,
11017        cx: &mut Context<Self>,
11018    ) {
11019        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11020            cx.propagate();
11021            return;
11022        }
11023        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11024        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11025            s.move_with(|map, selection| {
11026                selection.collapse_to(
11027                    movement::start_of_excerpt(
11028                        map,
11029                        selection.head(),
11030                        workspace::searchable::Direction::Prev,
11031                    ),
11032                    SelectionGoal::None,
11033                )
11034            });
11035        })
11036    }
11037
11038    pub fn move_to_start_of_next_excerpt(
11039        &mut self,
11040        _: &MoveToStartOfNextExcerpt,
11041        window: &mut Window,
11042        cx: &mut Context<Self>,
11043    ) {
11044        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11045            cx.propagate();
11046            return;
11047        }
11048
11049        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11050            s.move_with(|map, selection| {
11051                selection.collapse_to(
11052                    movement::start_of_excerpt(
11053                        map,
11054                        selection.head(),
11055                        workspace::searchable::Direction::Next,
11056                    ),
11057                    SelectionGoal::None,
11058                )
11059            });
11060        })
11061    }
11062
11063    pub fn move_to_end_of_excerpt(
11064        &mut self,
11065        _: &MoveToEndOfExcerpt,
11066        window: &mut Window,
11067        cx: &mut Context<Self>,
11068    ) {
11069        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11070            cx.propagate();
11071            return;
11072        }
11073        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11074        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11075            s.move_with(|map, selection| {
11076                selection.collapse_to(
11077                    movement::end_of_excerpt(
11078                        map,
11079                        selection.head(),
11080                        workspace::searchable::Direction::Next,
11081                    ),
11082                    SelectionGoal::None,
11083                )
11084            });
11085        })
11086    }
11087
11088    pub fn move_to_end_of_previous_excerpt(
11089        &mut self,
11090        _: &MoveToEndOfPreviousExcerpt,
11091        window: &mut Window,
11092        cx: &mut Context<Self>,
11093    ) {
11094        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11095            cx.propagate();
11096            return;
11097        }
11098        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11099        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11100            s.move_with(|map, selection| {
11101                selection.collapse_to(
11102                    movement::end_of_excerpt(
11103                        map,
11104                        selection.head(),
11105                        workspace::searchable::Direction::Prev,
11106                    ),
11107                    SelectionGoal::None,
11108                )
11109            });
11110        })
11111    }
11112
11113    pub fn select_to_start_of_excerpt(
11114        &mut self,
11115        _: &SelectToStartOfExcerpt,
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::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11128                    SelectionGoal::None,
11129                )
11130            });
11131        })
11132    }
11133
11134    pub fn select_to_start_of_next_excerpt(
11135        &mut self,
11136        _: &SelectToStartOfNextExcerpt,
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::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11149                    SelectionGoal::None,
11150                )
11151            });
11152        })
11153    }
11154
11155    pub fn select_to_end_of_excerpt(
11156        &mut self,
11157        _: &SelectToEndOfExcerpt,
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.move_heads_with(|map, head, _| {
11168                (
11169                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11170                    SelectionGoal::None,
11171                )
11172            });
11173        })
11174    }
11175
11176    pub fn select_to_end_of_previous_excerpt(
11177        &mut self,
11178        _: &SelectToEndOfPreviousExcerpt,
11179        window: &mut Window,
11180        cx: &mut Context<Self>,
11181    ) {
11182        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11183            cx.propagate();
11184            return;
11185        }
11186        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11187        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11188            s.move_heads_with(|map, head, _| {
11189                (
11190                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11191                    SelectionGoal::None,
11192                )
11193            });
11194        })
11195    }
11196
11197    pub fn move_to_beginning(
11198        &mut self,
11199        _: &MoveToBeginning,
11200        window: &mut Window,
11201        cx: &mut Context<Self>,
11202    ) {
11203        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11204            cx.propagate();
11205            return;
11206        }
11207        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11208        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11209            s.select_ranges(vec![0..0]);
11210        });
11211    }
11212
11213    pub fn select_to_beginning(
11214        &mut self,
11215        _: &SelectToBeginning,
11216        window: &mut Window,
11217        cx: &mut Context<Self>,
11218    ) {
11219        let mut selection = self.selections.last::<Point>(cx);
11220        selection.set_head(Point::zero(), SelectionGoal::None);
11221        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11222        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11223            s.select(vec![selection]);
11224        });
11225    }
11226
11227    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11228        if matches!(self.mode, EditorMode::SingleLine { .. }) {
11229            cx.propagate();
11230            return;
11231        }
11232        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11233        let cursor = self.buffer.read(cx).read(cx).len();
11234        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11235            s.select_ranges(vec![cursor..cursor])
11236        });
11237    }
11238
11239    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11240        self.nav_history = nav_history;
11241    }
11242
11243    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11244        self.nav_history.as_ref()
11245    }
11246
11247    pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11248        self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11249    }
11250
11251    fn push_to_nav_history(
11252        &mut self,
11253        cursor_anchor: Anchor,
11254        new_position: Option<Point>,
11255        is_deactivate: bool,
11256        cx: &mut Context<Self>,
11257    ) {
11258        if let Some(nav_history) = self.nav_history.as_mut() {
11259            let buffer = self.buffer.read(cx).read(cx);
11260            let cursor_position = cursor_anchor.to_point(&buffer);
11261            let scroll_state = self.scroll_manager.anchor();
11262            let scroll_top_row = scroll_state.top_row(&buffer);
11263            drop(buffer);
11264
11265            if let Some(new_position) = new_position {
11266                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11267                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11268                    return;
11269                }
11270            }
11271
11272            nav_history.push(
11273                Some(NavigationData {
11274                    cursor_anchor,
11275                    cursor_position,
11276                    scroll_anchor: scroll_state,
11277                    scroll_top_row,
11278                }),
11279                cx,
11280            );
11281            cx.emit(EditorEvent::PushedToNavHistory {
11282                anchor: cursor_anchor,
11283                is_deactivate,
11284            })
11285        }
11286    }
11287
11288    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11289        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11290        let buffer = self.buffer.read(cx).snapshot(cx);
11291        let mut selection = self.selections.first::<usize>(cx);
11292        selection.set_head(buffer.len(), SelectionGoal::None);
11293        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11294            s.select(vec![selection]);
11295        });
11296    }
11297
11298    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11299        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11300        let end = self.buffer.read(cx).read(cx).len();
11301        self.change_selections(None, window, cx, |s| {
11302            s.select_ranges(vec![0..end]);
11303        });
11304    }
11305
11306    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11307        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11308        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11309        let mut selections = self.selections.all::<Point>(cx);
11310        let max_point = display_map.buffer_snapshot.max_point();
11311        for selection in &mut selections {
11312            let rows = selection.spanned_rows(true, &display_map);
11313            selection.start = Point::new(rows.start.0, 0);
11314            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11315            selection.reversed = false;
11316        }
11317        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11318            s.select(selections);
11319        });
11320    }
11321
11322    pub fn split_selection_into_lines(
11323        &mut self,
11324        _: &SplitSelectionIntoLines,
11325        window: &mut Window,
11326        cx: &mut Context<Self>,
11327    ) {
11328        let selections = self
11329            .selections
11330            .all::<Point>(cx)
11331            .into_iter()
11332            .map(|selection| selection.start..selection.end)
11333            .collect::<Vec<_>>();
11334        self.unfold_ranges(&selections, true, true, cx);
11335
11336        let mut new_selection_ranges = Vec::new();
11337        {
11338            let buffer = self.buffer.read(cx).read(cx);
11339            for selection in selections {
11340                for row in selection.start.row..selection.end.row {
11341                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11342                    new_selection_ranges.push(cursor..cursor);
11343                }
11344
11345                let is_multiline_selection = selection.start.row != selection.end.row;
11346                // Don't insert last one if it's a multi-line selection ending at the start of a line,
11347                // so this action feels more ergonomic when paired with other selection operations
11348                let should_skip_last = is_multiline_selection && selection.end.column == 0;
11349                if !should_skip_last {
11350                    new_selection_ranges.push(selection.end..selection.end);
11351                }
11352            }
11353        }
11354        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11355            s.select_ranges(new_selection_ranges);
11356        });
11357    }
11358
11359    pub fn add_selection_above(
11360        &mut self,
11361        _: &AddSelectionAbove,
11362        window: &mut Window,
11363        cx: &mut Context<Self>,
11364    ) {
11365        self.add_selection(true, window, cx);
11366    }
11367
11368    pub fn add_selection_below(
11369        &mut self,
11370        _: &AddSelectionBelow,
11371        window: &mut Window,
11372        cx: &mut Context<Self>,
11373    ) {
11374        self.add_selection(false, window, cx);
11375    }
11376
11377    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11378        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11379
11380        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11381        let mut selections = self.selections.all::<Point>(cx);
11382        let text_layout_details = self.text_layout_details(window);
11383        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11384            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11385            let range = oldest_selection.display_range(&display_map).sorted();
11386
11387            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11388            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11389            let positions = start_x.min(end_x)..start_x.max(end_x);
11390
11391            selections.clear();
11392            let mut stack = Vec::new();
11393            for row in range.start.row().0..=range.end.row().0 {
11394                if let Some(selection) = self.selections.build_columnar_selection(
11395                    &display_map,
11396                    DisplayRow(row),
11397                    &positions,
11398                    oldest_selection.reversed,
11399                    &text_layout_details,
11400                ) {
11401                    stack.push(selection.id);
11402                    selections.push(selection);
11403                }
11404            }
11405
11406            if above {
11407                stack.reverse();
11408            }
11409
11410            AddSelectionsState { above, stack }
11411        });
11412
11413        let last_added_selection = *state.stack.last().unwrap();
11414        let mut new_selections = Vec::new();
11415        if above == state.above {
11416            let end_row = if above {
11417                DisplayRow(0)
11418            } else {
11419                display_map.max_point().row()
11420            };
11421
11422            'outer: for selection in selections {
11423                if selection.id == last_added_selection {
11424                    let range = selection.display_range(&display_map).sorted();
11425                    debug_assert_eq!(range.start.row(), range.end.row());
11426                    let mut row = range.start.row();
11427                    let positions =
11428                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11429                            px(start)..px(end)
11430                        } else {
11431                            let start_x =
11432                                display_map.x_for_display_point(range.start, &text_layout_details);
11433                            let end_x =
11434                                display_map.x_for_display_point(range.end, &text_layout_details);
11435                            start_x.min(end_x)..start_x.max(end_x)
11436                        };
11437
11438                    while row != end_row {
11439                        if above {
11440                            row.0 -= 1;
11441                        } else {
11442                            row.0 += 1;
11443                        }
11444
11445                        if let Some(new_selection) = self.selections.build_columnar_selection(
11446                            &display_map,
11447                            row,
11448                            &positions,
11449                            selection.reversed,
11450                            &text_layout_details,
11451                        ) {
11452                            state.stack.push(new_selection.id);
11453                            if above {
11454                                new_selections.push(new_selection);
11455                                new_selections.push(selection);
11456                            } else {
11457                                new_selections.push(selection);
11458                                new_selections.push(new_selection);
11459                            }
11460
11461                            continue 'outer;
11462                        }
11463                    }
11464                }
11465
11466                new_selections.push(selection);
11467            }
11468        } else {
11469            new_selections = selections;
11470            new_selections.retain(|s| s.id != last_added_selection);
11471            state.stack.pop();
11472        }
11473
11474        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11475            s.select(new_selections);
11476        });
11477        if state.stack.len() > 1 {
11478            self.add_selections_state = Some(state);
11479        }
11480    }
11481
11482    pub fn select_next_match_internal(
11483        &mut self,
11484        display_map: &DisplaySnapshot,
11485        replace_newest: bool,
11486        autoscroll: Option<Autoscroll>,
11487        window: &mut Window,
11488        cx: &mut Context<Self>,
11489    ) -> Result<()> {
11490        fn select_next_match_ranges(
11491            this: &mut Editor,
11492            range: Range<usize>,
11493            replace_newest: bool,
11494            auto_scroll: Option<Autoscroll>,
11495            window: &mut Window,
11496            cx: &mut Context<Editor>,
11497        ) {
11498            this.unfold_ranges(&[range.clone()], false, true, cx);
11499            this.change_selections(auto_scroll, window, cx, |s| {
11500                if replace_newest {
11501                    s.delete(s.newest_anchor().id);
11502                }
11503                s.insert_range(range.clone());
11504            });
11505        }
11506
11507        let buffer = &display_map.buffer_snapshot;
11508        let mut selections = self.selections.all::<usize>(cx);
11509        if let Some(mut select_next_state) = self.select_next_state.take() {
11510            let query = &select_next_state.query;
11511            if !select_next_state.done {
11512                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11513                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11514                let mut next_selected_range = None;
11515
11516                let bytes_after_last_selection =
11517                    buffer.bytes_in_range(last_selection.end..buffer.len());
11518                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11519                let query_matches = query
11520                    .stream_find_iter(bytes_after_last_selection)
11521                    .map(|result| (last_selection.end, result))
11522                    .chain(
11523                        query
11524                            .stream_find_iter(bytes_before_first_selection)
11525                            .map(|result| (0, result)),
11526                    );
11527
11528                for (start_offset, query_match) in query_matches {
11529                    let query_match = query_match.unwrap(); // can only fail due to I/O
11530                    let offset_range =
11531                        start_offset + query_match.start()..start_offset + query_match.end();
11532                    let display_range = offset_range.start.to_display_point(display_map)
11533                        ..offset_range.end.to_display_point(display_map);
11534
11535                    if !select_next_state.wordwise
11536                        || (!movement::is_inside_word(display_map, display_range.start)
11537                            && !movement::is_inside_word(display_map, display_range.end))
11538                    {
11539                        // TODO: This is n^2, because we might check all the selections
11540                        if !selections
11541                            .iter()
11542                            .any(|selection| selection.range().overlaps(&offset_range))
11543                        {
11544                            next_selected_range = Some(offset_range);
11545                            break;
11546                        }
11547                    }
11548                }
11549
11550                if let Some(next_selected_range) = next_selected_range {
11551                    select_next_match_ranges(
11552                        self,
11553                        next_selected_range,
11554                        replace_newest,
11555                        autoscroll,
11556                        window,
11557                        cx,
11558                    );
11559                } else {
11560                    select_next_state.done = true;
11561                }
11562            }
11563
11564            self.select_next_state = Some(select_next_state);
11565        } else {
11566            let mut only_carets = true;
11567            let mut same_text_selected = true;
11568            let mut selected_text = None;
11569
11570            let mut selections_iter = selections.iter().peekable();
11571            while let Some(selection) = selections_iter.next() {
11572                if selection.start != selection.end {
11573                    only_carets = false;
11574                }
11575
11576                if same_text_selected {
11577                    if selected_text.is_none() {
11578                        selected_text =
11579                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11580                    }
11581
11582                    if let Some(next_selection) = selections_iter.peek() {
11583                        if next_selection.range().len() == selection.range().len() {
11584                            let next_selected_text = buffer
11585                                .text_for_range(next_selection.range())
11586                                .collect::<String>();
11587                            if Some(next_selected_text) != selected_text {
11588                                same_text_selected = false;
11589                                selected_text = None;
11590                            }
11591                        } else {
11592                            same_text_selected = false;
11593                            selected_text = None;
11594                        }
11595                    }
11596                }
11597            }
11598
11599            if only_carets {
11600                for selection in &mut selections {
11601                    let word_range = movement::surrounding_word(
11602                        display_map,
11603                        selection.start.to_display_point(display_map),
11604                    );
11605                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
11606                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
11607                    selection.goal = SelectionGoal::None;
11608                    selection.reversed = false;
11609                    select_next_match_ranges(
11610                        self,
11611                        selection.start..selection.end,
11612                        replace_newest,
11613                        autoscroll,
11614                        window,
11615                        cx,
11616                    );
11617                }
11618
11619                if selections.len() == 1 {
11620                    let selection = selections
11621                        .last()
11622                        .expect("ensured that there's only one selection");
11623                    let query = buffer
11624                        .text_for_range(selection.start..selection.end)
11625                        .collect::<String>();
11626                    let is_empty = query.is_empty();
11627                    let select_state = SelectNextState {
11628                        query: AhoCorasick::new(&[query])?,
11629                        wordwise: true,
11630                        done: is_empty,
11631                    };
11632                    self.select_next_state = Some(select_state);
11633                } else {
11634                    self.select_next_state = None;
11635                }
11636            } else if let Some(selected_text) = selected_text {
11637                self.select_next_state = Some(SelectNextState {
11638                    query: AhoCorasick::new(&[selected_text])?,
11639                    wordwise: false,
11640                    done: false,
11641                });
11642                self.select_next_match_internal(
11643                    display_map,
11644                    replace_newest,
11645                    autoscroll,
11646                    window,
11647                    cx,
11648                )?;
11649            }
11650        }
11651        Ok(())
11652    }
11653
11654    pub fn select_all_matches(
11655        &mut self,
11656        _action: &SelectAllMatches,
11657        window: &mut Window,
11658        cx: &mut Context<Self>,
11659    ) -> Result<()> {
11660        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11661
11662        self.push_to_selection_history();
11663        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11664
11665        self.select_next_match_internal(&display_map, false, None, window, cx)?;
11666        let Some(select_next_state) = self.select_next_state.as_mut() else {
11667            return Ok(());
11668        };
11669        if select_next_state.done {
11670            return Ok(());
11671        }
11672
11673        let mut new_selections = self.selections.all::<usize>(cx);
11674
11675        let buffer = &display_map.buffer_snapshot;
11676        let query_matches = select_next_state
11677            .query
11678            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11679
11680        for query_match in query_matches {
11681            let query_match = query_match.unwrap(); // can only fail due to I/O
11682            let offset_range = query_match.start()..query_match.end();
11683            let display_range = offset_range.start.to_display_point(&display_map)
11684                ..offset_range.end.to_display_point(&display_map);
11685
11686            if !select_next_state.wordwise
11687                || (!movement::is_inside_word(&display_map, display_range.start)
11688                    && !movement::is_inside_word(&display_map, display_range.end))
11689            {
11690                self.selections.change_with(cx, |selections| {
11691                    new_selections.push(Selection {
11692                        id: selections.new_selection_id(),
11693                        start: offset_range.start,
11694                        end: offset_range.end,
11695                        reversed: false,
11696                        goal: SelectionGoal::None,
11697                    });
11698                });
11699            }
11700        }
11701
11702        new_selections.sort_by_key(|selection| selection.start);
11703        let mut ix = 0;
11704        while ix + 1 < new_selections.len() {
11705            let current_selection = &new_selections[ix];
11706            let next_selection = &new_selections[ix + 1];
11707            if current_selection.range().overlaps(&next_selection.range()) {
11708                if current_selection.id < next_selection.id {
11709                    new_selections.remove(ix + 1);
11710                } else {
11711                    new_selections.remove(ix);
11712                }
11713            } else {
11714                ix += 1;
11715            }
11716        }
11717
11718        let reversed = self.selections.oldest::<usize>(cx).reversed;
11719
11720        for selection in new_selections.iter_mut() {
11721            selection.reversed = reversed;
11722        }
11723
11724        select_next_state.done = true;
11725        self.unfold_ranges(
11726            &new_selections
11727                .iter()
11728                .map(|selection| selection.range())
11729                .collect::<Vec<_>>(),
11730            false,
11731            false,
11732            cx,
11733        );
11734        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11735            selections.select(new_selections)
11736        });
11737
11738        Ok(())
11739    }
11740
11741    pub fn select_next(
11742        &mut self,
11743        action: &SelectNext,
11744        window: &mut Window,
11745        cx: &mut Context<Self>,
11746    ) -> Result<()> {
11747        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11748        self.push_to_selection_history();
11749        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11750        self.select_next_match_internal(
11751            &display_map,
11752            action.replace_newest,
11753            Some(Autoscroll::newest()),
11754            window,
11755            cx,
11756        )?;
11757        Ok(())
11758    }
11759
11760    pub fn select_previous(
11761        &mut self,
11762        action: &SelectPrevious,
11763        window: &mut Window,
11764        cx: &mut Context<Self>,
11765    ) -> Result<()> {
11766        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11767        self.push_to_selection_history();
11768        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11769        let buffer = &display_map.buffer_snapshot;
11770        let mut selections = self.selections.all::<usize>(cx);
11771        if let Some(mut select_prev_state) = self.select_prev_state.take() {
11772            let query = &select_prev_state.query;
11773            if !select_prev_state.done {
11774                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11775                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11776                let mut next_selected_range = None;
11777                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11778                let bytes_before_last_selection =
11779                    buffer.reversed_bytes_in_range(0..last_selection.start);
11780                let bytes_after_first_selection =
11781                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11782                let query_matches = query
11783                    .stream_find_iter(bytes_before_last_selection)
11784                    .map(|result| (last_selection.start, result))
11785                    .chain(
11786                        query
11787                            .stream_find_iter(bytes_after_first_selection)
11788                            .map(|result| (buffer.len(), result)),
11789                    );
11790                for (end_offset, query_match) in query_matches {
11791                    let query_match = query_match.unwrap(); // can only fail due to I/O
11792                    let offset_range =
11793                        end_offset - query_match.end()..end_offset - query_match.start();
11794                    let display_range = offset_range.start.to_display_point(&display_map)
11795                        ..offset_range.end.to_display_point(&display_map);
11796
11797                    if !select_prev_state.wordwise
11798                        || (!movement::is_inside_word(&display_map, display_range.start)
11799                            && !movement::is_inside_word(&display_map, display_range.end))
11800                    {
11801                        next_selected_range = Some(offset_range);
11802                        break;
11803                    }
11804                }
11805
11806                if let Some(next_selected_range) = next_selected_range {
11807                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11808                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11809                        if action.replace_newest {
11810                            s.delete(s.newest_anchor().id);
11811                        }
11812                        s.insert_range(next_selected_range);
11813                    });
11814                } else {
11815                    select_prev_state.done = true;
11816                }
11817            }
11818
11819            self.select_prev_state = Some(select_prev_state);
11820        } else {
11821            let mut only_carets = true;
11822            let mut same_text_selected = true;
11823            let mut selected_text = None;
11824
11825            let mut selections_iter = selections.iter().peekable();
11826            while let Some(selection) = selections_iter.next() {
11827                if selection.start != selection.end {
11828                    only_carets = false;
11829                }
11830
11831                if same_text_selected {
11832                    if selected_text.is_none() {
11833                        selected_text =
11834                            Some(buffer.text_for_range(selection.range()).collect::<String>());
11835                    }
11836
11837                    if let Some(next_selection) = selections_iter.peek() {
11838                        if next_selection.range().len() == selection.range().len() {
11839                            let next_selected_text = buffer
11840                                .text_for_range(next_selection.range())
11841                                .collect::<String>();
11842                            if Some(next_selected_text) != selected_text {
11843                                same_text_selected = false;
11844                                selected_text = None;
11845                            }
11846                        } else {
11847                            same_text_selected = false;
11848                            selected_text = None;
11849                        }
11850                    }
11851                }
11852            }
11853
11854            if only_carets {
11855                for selection in &mut selections {
11856                    let word_range = movement::surrounding_word(
11857                        &display_map,
11858                        selection.start.to_display_point(&display_map),
11859                    );
11860                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11861                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11862                    selection.goal = SelectionGoal::None;
11863                    selection.reversed = false;
11864                }
11865                if selections.len() == 1 {
11866                    let selection = selections
11867                        .last()
11868                        .expect("ensured that there's only one selection");
11869                    let query = buffer
11870                        .text_for_range(selection.start..selection.end)
11871                        .collect::<String>();
11872                    let is_empty = query.is_empty();
11873                    let select_state = SelectNextState {
11874                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11875                        wordwise: true,
11876                        done: is_empty,
11877                    };
11878                    self.select_prev_state = Some(select_state);
11879                } else {
11880                    self.select_prev_state = None;
11881                }
11882
11883                self.unfold_ranges(
11884                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11885                    false,
11886                    true,
11887                    cx,
11888                );
11889                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11890                    s.select(selections);
11891                });
11892            } else if let Some(selected_text) = selected_text {
11893                self.select_prev_state = Some(SelectNextState {
11894                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11895                    wordwise: false,
11896                    done: false,
11897                });
11898                self.select_previous(action, window, cx)?;
11899            }
11900        }
11901        Ok(())
11902    }
11903
11904    pub fn toggle_comments(
11905        &mut self,
11906        action: &ToggleComments,
11907        window: &mut Window,
11908        cx: &mut Context<Self>,
11909    ) {
11910        if self.read_only(cx) {
11911            return;
11912        }
11913        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11914        let text_layout_details = &self.text_layout_details(window);
11915        self.transact(window, cx, |this, window, cx| {
11916            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11917            let mut edits = Vec::new();
11918            let mut selection_edit_ranges = Vec::new();
11919            let mut last_toggled_row = None;
11920            let snapshot = this.buffer.read(cx).read(cx);
11921            let empty_str: Arc<str> = Arc::default();
11922            let mut suffixes_inserted = Vec::new();
11923            let ignore_indent = action.ignore_indent;
11924
11925            fn comment_prefix_range(
11926                snapshot: &MultiBufferSnapshot,
11927                row: MultiBufferRow,
11928                comment_prefix: &str,
11929                comment_prefix_whitespace: &str,
11930                ignore_indent: bool,
11931            ) -> Range<Point> {
11932                let indent_size = if ignore_indent {
11933                    0
11934                } else {
11935                    snapshot.indent_size_for_line(row).len
11936                };
11937
11938                let start = Point::new(row.0, indent_size);
11939
11940                let mut line_bytes = snapshot
11941                    .bytes_in_range(start..snapshot.max_point())
11942                    .flatten()
11943                    .copied();
11944
11945                // If this line currently begins with the line comment prefix, then record
11946                // the range containing the prefix.
11947                if line_bytes
11948                    .by_ref()
11949                    .take(comment_prefix.len())
11950                    .eq(comment_prefix.bytes())
11951                {
11952                    // Include any whitespace that matches the comment prefix.
11953                    let matching_whitespace_len = line_bytes
11954                        .zip(comment_prefix_whitespace.bytes())
11955                        .take_while(|(a, b)| a == b)
11956                        .count() as u32;
11957                    let end = Point::new(
11958                        start.row,
11959                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11960                    );
11961                    start..end
11962                } else {
11963                    start..start
11964                }
11965            }
11966
11967            fn comment_suffix_range(
11968                snapshot: &MultiBufferSnapshot,
11969                row: MultiBufferRow,
11970                comment_suffix: &str,
11971                comment_suffix_has_leading_space: bool,
11972            ) -> Range<Point> {
11973                let end = Point::new(row.0, snapshot.line_len(row));
11974                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11975
11976                let mut line_end_bytes = snapshot
11977                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11978                    .flatten()
11979                    .copied();
11980
11981                let leading_space_len = if suffix_start_column > 0
11982                    && line_end_bytes.next() == Some(b' ')
11983                    && comment_suffix_has_leading_space
11984                {
11985                    1
11986                } else {
11987                    0
11988                };
11989
11990                // If this line currently begins with the line comment prefix, then record
11991                // the range containing the prefix.
11992                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
11993                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
11994                    start..end
11995                } else {
11996                    end..end
11997                }
11998            }
11999
12000            // TODO: Handle selections that cross excerpts
12001            for selection in &mut selections {
12002                let start_column = snapshot
12003                    .indent_size_for_line(MultiBufferRow(selection.start.row))
12004                    .len;
12005                let language = if let Some(language) =
12006                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12007                {
12008                    language
12009                } else {
12010                    continue;
12011                };
12012
12013                selection_edit_ranges.clear();
12014
12015                // If multiple selections contain a given row, avoid processing that
12016                // row more than once.
12017                let mut start_row = MultiBufferRow(selection.start.row);
12018                if last_toggled_row == Some(start_row) {
12019                    start_row = start_row.next_row();
12020                }
12021                let end_row =
12022                    if selection.end.row > selection.start.row && selection.end.column == 0 {
12023                        MultiBufferRow(selection.end.row - 1)
12024                    } else {
12025                        MultiBufferRow(selection.end.row)
12026                    };
12027                last_toggled_row = Some(end_row);
12028
12029                if start_row > end_row {
12030                    continue;
12031                }
12032
12033                // If the language has line comments, toggle those.
12034                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12035
12036                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12037                if ignore_indent {
12038                    full_comment_prefixes = full_comment_prefixes
12039                        .into_iter()
12040                        .map(|s| Arc::from(s.trim_end()))
12041                        .collect();
12042                }
12043
12044                if !full_comment_prefixes.is_empty() {
12045                    let first_prefix = full_comment_prefixes
12046                        .first()
12047                        .expect("prefixes is non-empty");
12048                    let prefix_trimmed_lengths = full_comment_prefixes
12049                        .iter()
12050                        .map(|p| p.trim_end_matches(' ').len())
12051                        .collect::<SmallVec<[usize; 4]>>();
12052
12053                    let mut all_selection_lines_are_comments = true;
12054
12055                    for row in start_row.0..=end_row.0 {
12056                        let row = MultiBufferRow(row);
12057                        if start_row < end_row && snapshot.is_line_blank(row) {
12058                            continue;
12059                        }
12060
12061                        let prefix_range = full_comment_prefixes
12062                            .iter()
12063                            .zip(prefix_trimmed_lengths.iter().copied())
12064                            .map(|(prefix, trimmed_prefix_len)| {
12065                                comment_prefix_range(
12066                                    snapshot.deref(),
12067                                    row,
12068                                    &prefix[..trimmed_prefix_len],
12069                                    &prefix[trimmed_prefix_len..],
12070                                    ignore_indent,
12071                                )
12072                            })
12073                            .max_by_key(|range| range.end.column - range.start.column)
12074                            .expect("prefixes is non-empty");
12075
12076                        if prefix_range.is_empty() {
12077                            all_selection_lines_are_comments = false;
12078                        }
12079
12080                        selection_edit_ranges.push(prefix_range);
12081                    }
12082
12083                    if all_selection_lines_are_comments {
12084                        edits.extend(
12085                            selection_edit_ranges
12086                                .iter()
12087                                .cloned()
12088                                .map(|range| (range, empty_str.clone())),
12089                        );
12090                    } else {
12091                        let min_column = selection_edit_ranges
12092                            .iter()
12093                            .map(|range| range.start.column)
12094                            .min()
12095                            .unwrap_or(0);
12096                        edits.extend(selection_edit_ranges.iter().map(|range| {
12097                            let position = Point::new(range.start.row, min_column);
12098                            (position..position, first_prefix.clone())
12099                        }));
12100                    }
12101                } else if let Some((full_comment_prefix, comment_suffix)) =
12102                    language.block_comment_delimiters()
12103                {
12104                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12105                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12106                    let prefix_range = comment_prefix_range(
12107                        snapshot.deref(),
12108                        start_row,
12109                        comment_prefix,
12110                        comment_prefix_whitespace,
12111                        ignore_indent,
12112                    );
12113                    let suffix_range = comment_suffix_range(
12114                        snapshot.deref(),
12115                        end_row,
12116                        comment_suffix.trim_start_matches(' '),
12117                        comment_suffix.starts_with(' '),
12118                    );
12119
12120                    if prefix_range.is_empty() || suffix_range.is_empty() {
12121                        edits.push((
12122                            prefix_range.start..prefix_range.start,
12123                            full_comment_prefix.clone(),
12124                        ));
12125                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12126                        suffixes_inserted.push((end_row, comment_suffix.len()));
12127                    } else {
12128                        edits.push((prefix_range, empty_str.clone()));
12129                        edits.push((suffix_range, empty_str.clone()));
12130                    }
12131                } else {
12132                    continue;
12133                }
12134            }
12135
12136            drop(snapshot);
12137            this.buffer.update(cx, |buffer, cx| {
12138                buffer.edit(edits, None, cx);
12139            });
12140
12141            // Adjust selections so that they end before any comment suffixes that
12142            // were inserted.
12143            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12144            let mut selections = this.selections.all::<Point>(cx);
12145            let snapshot = this.buffer.read(cx).read(cx);
12146            for selection in &mut selections {
12147                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12148                    match row.cmp(&MultiBufferRow(selection.end.row)) {
12149                        Ordering::Less => {
12150                            suffixes_inserted.next();
12151                            continue;
12152                        }
12153                        Ordering::Greater => break,
12154                        Ordering::Equal => {
12155                            if selection.end.column == snapshot.line_len(row) {
12156                                if selection.is_empty() {
12157                                    selection.start.column -= suffix_len as u32;
12158                                }
12159                                selection.end.column -= suffix_len as u32;
12160                            }
12161                            break;
12162                        }
12163                    }
12164                }
12165            }
12166
12167            drop(snapshot);
12168            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12169                s.select(selections)
12170            });
12171
12172            let selections = this.selections.all::<Point>(cx);
12173            let selections_on_single_row = selections.windows(2).all(|selections| {
12174                selections[0].start.row == selections[1].start.row
12175                    && selections[0].end.row == selections[1].end.row
12176                    && selections[0].start.row == selections[0].end.row
12177            });
12178            let selections_selecting = selections
12179                .iter()
12180                .any(|selection| selection.start != selection.end);
12181            let advance_downwards = action.advance_downwards
12182                && selections_on_single_row
12183                && !selections_selecting
12184                && !matches!(this.mode, EditorMode::SingleLine { .. });
12185
12186            if advance_downwards {
12187                let snapshot = this.buffer.read(cx).snapshot(cx);
12188
12189                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12190                    s.move_cursors_with(|display_snapshot, display_point, _| {
12191                        let mut point = display_point.to_point(display_snapshot);
12192                        point.row += 1;
12193                        point = snapshot.clip_point(point, Bias::Left);
12194                        let display_point = point.to_display_point(display_snapshot);
12195                        let goal = SelectionGoal::HorizontalPosition(
12196                            display_snapshot
12197                                .x_for_display_point(display_point, text_layout_details)
12198                                .into(),
12199                        );
12200                        (display_point, goal)
12201                    })
12202                });
12203            }
12204        });
12205    }
12206
12207    pub fn select_enclosing_symbol(
12208        &mut self,
12209        _: &SelectEnclosingSymbol,
12210        window: &mut Window,
12211        cx: &mut Context<Self>,
12212    ) {
12213        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12214
12215        let buffer = self.buffer.read(cx).snapshot(cx);
12216        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12217
12218        fn update_selection(
12219            selection: &Selection<usize>,
12220            buffer_snap: &MultiBufferSnapshot,
12221        ) -> Option<Selection<usize>> {
12222            let cursor = selection.head();
12223            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12224            for symbol in symbols.iter().rev() {
12225                let start = symbol.range.start.to_offset(buffer_snap);
12226                let end = symbol.range.end.to_offset(buffer_snap);
12227                let new_range = start..end;
12228                if start < selection.start || end > selection.end {
12229                    return Some(Selection {
12230                        id: selection.id,
12231                        start: new_range.start,
12232                        end: new_range.end,
12233                        goal: SelectionGoal::None,
12234                        reversed: selection.reversed,
12235                    });
12236                }
12237            }
12238            None
12239        }
12240
12241        let mut selected_larger_symbol = false;
12242        let new_selections = old_selections
12243            .iter()
12244            .map(|selection| match update_selection(selection, &buffer) {
12245                Some(new_selection) => {
12246                    if new_selection.range() != selection.range() {
12247                        selected_larger_symbol = true;
12248                    }
12249                    new_selection
12250                }
12251                None => selection.clone(),
12252            })
12253            .collect::<Vec<_>>();
12254
12255        if selected_larger_symbol {
12256            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12257                s.select(new_selections);
12258            });
12259        }
12260    }
12261
12262    pub fn select_larger_syntax_node(
12263        &mut self,
12264        _: &SelectLargerSyntaxNode,
12265        window: &mut Window,
12266        cx: &mut Context<Self>,
12267    ) {
12268        let Some(visible_row_count) = self.visible_row_count() else {
12269            return;
12270        };
12271        let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12272        if old_selections.is_empty() {
12273            return;
12274        }
12275
12276        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12277
12278        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12279        let buffer = self.buffer.read(cx).snapshot(cx);
12280
12281        let mut selected_larger_node = false;
12282        let mut new_selections = old_selections
12283            .iter()
12284            .map(|selection| {
12285                let old_range = selection.start..selection.end;
12286                let mut new_range = old_range.clone();
12287                let mut new_node = None;
12288                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12289                {
12290                    new_node = Some(node);
12291                    new_range = match containing_range {
12292                        MultiOrSingleBufferOffsetRange::Single(_) => break,
12293                        MultiOrSingleBufferOffsetRange::Multi(range) => range,
12294                    };
12295                    if !display_map.intersects_fold(new_range.start)
12296                        && !display_map.intersects_fold(new_range.end)
12297                    {
12298                        break;
12299                    }
12300                }
12301
12302                if let Some(node) = new_node {
12303                    // Log the ancestor, to support using this action as a way to explore TreeSitter
12304                    // nodes. Parent and grandparent are also logged because this operation will not
12305                    // visit nodes that have the same range as their parent.
12306                    log::info!("Node: {node:?}");
12307                    let parent = node.parent();
12308                    log::info!("Parent: {parent:?}");
12309                    let grandparent = parent.and_then(|x| x.parent());
12310                    log::info!("Grandparent: {grandparent:?}");
12311                }
12312
12313                selected_larger_node |= new_range != old_range;
12314                Selection {
12315                    id: selection.id,
12316                    start: new_range.start,
12317                    end: new_range.end,
12318                    goal: SelectionGoal::None,
12319                    reversed: selection.reversed,
12320                }
12321            })
12322            .collect::<Vec<_>>();
12323
12324        if !selected_larger_node {
12325            return; // don't put this call in the history
12326        }
12327
12328        // scroll based on transformation done to the last selection created by the user
12329        let (last_old, last_new) = old_selections
12330            .last()
12331            .zip(new_selections.last().cloned())
12332            .expect("old_selections isn't empty");
12333
12334        // revert selection
12335        let is_selection_reversed = {
12336            let should_newest_selection_be_reversed = last_old.start != last_new.start;
12337            new_selections.last_mut().expect("checked above").reversed =
12338                should_newest_selection_be_reversed;
12339            should_newest_selection_be_reversed
12340        };
12341
12342        if selected_larger_node {
12343            self.select_syntax_node_history.disable_clearing = true;
12344            self.change_selections(None, window, cx, |s| {
12345                s.select(new_selections.clone());
12346            });
12347            self.select_syntax_node_history.disable_clearing = false;
12348        }
12349
12350        let start_row = last_new.start.to_display_point(&display_map).row().0;
12351        let end_row = last_new.end.to_display_point(&display_map).row().0;
12352        let selection_height = end_row - start_row + 1;
12353        let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12354
12355        let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12356        let scroll_behavior = if fits_on_the_screen {
12357            self.request_autoscroll(Autoscroll::fit(), cx);
12358            SelectSyntaxNodeScrollBehavior::FitSelection
12359        } else if is_selection_reversed {
12360            self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12361            SelectSyntaxNodeScrollBehavior::CursorTop
12362        } else {
12363            self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12364            SelectSyntaxNodeScrollBehavior::CursorBottom
12365        };
12366
12367        self.select_syntax_node_history.push((
12368            old_selections,
12369            scroll_behavior,
12370            is_selection_reversed,
12371        ));
12372    }
12373
12374    pub fn select_smaller_syntax_node(
12375        &mut self,
12376        _: &SelectSmallerSyntaxNode,
12377        window: &mut Window,
12378        cx: &mut Context<Self>,
12379    ) {
12380        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12381
12382        if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12383            self.select_syntax_node_history.pop()
12384        {
12385            if let Some(selection) = selections.last_mut() {
12386                selection.reversed = is_selection_reversed;
12387            }
12388
12389            self.select_syntax_node_history.disable_clearing = true;
12390            self.change_selections(None, window, cx, |s| {
12391                s.select(selections.to_vec());
12392            });
12393            self.select_syntax_node_history.disable_clearing = false;
12394
12395            match scroll_behavior {
12396                SelectSyntaxNodeScrollBehavior::CursorTop => {
12397                    self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12398                }
12399                SelectSyntaxNodeScrollBehavior::FitSelection => {
12400                    self.request_autoscroll(Autoscroll::fit(), cx);
12401                }
12402                SelectSyntaxNodeScrollBehavior::CursorBottom => {
12403                    self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12404                }
12405            }
12406        }
12407    }
12408
12409    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12410        if !EditorSettings::get_global(cx).gutter.runnables {
12411            self.clear_tasks();
12412            return Task::ready(());
12413        }
12414        let project = self.project.as_ref().map(Entity::downgrade);
12415        cx.spawn_in(window, async move |this, cx| {
12416            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12417            let Some(project) = project.and_then(|p| p.upgrade()) else {
12418                return;
12419            };
12420            let Ok(display_snapshot) = this.update(cx, |this, cx| {
12421                this.display_map.update(cx, |map, cx| map.snapshot(cx))
12422            }) else {
12423                return;
12424            };
12425
12426            let hide_runnables = project
12427                .update(cx, |project, cx| {
12428                    // Do not display any test indicators in non-dev server remote projects.
12429                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12430                })
12431                .unwrap_or(true);
12432            if hide_runnables {
12433                return;
12434            }
12435            let new_rows =
12436                cx.background_spawn({
12437                    let snapshot = display_snapshot.clone();
12438                    async move {
12439                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12440                    }
12441                })
12442                    .await;
12443
12444            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12445            this.update(cx, |this, _| {
12446                this.clear_tasks();
12447                for (key, value) in rows {
12448                    this.insert_tasks(key, value);
12449                }
12450            })
12451            .ok();
12452        })
12453    }
12454    fn fetch_runnable_ranges(
12455        snapshot: &DisplaySnapshot,
12456        range: Range<Anchor>,
12457    ) -> Vec<language::RunnableRange> {
12458        snapshot.buffer_snapshot.runnable_ranges(range).collect()
12459    }
12460
12461    fn runnable_rows(
12462        project: Entity<Project>,
12463        snapshot: DisplaySnapshot,
12464        runnable_ranges: Vec<RunnableRange>,
12465        mut cx: AsyncWindowContext,
12466    ) -> Vec<((BufferId, u32), RunnableTasks)> {
12467        runnable_ranges
12468            .into_iter()
12469            .filter_map(|mut runnable| {
12470                let tasks = cx
12471                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12472                    .ok()?;
12473                if tasks.is_empty() {
12474                    return None;
12475                }
12476
12477                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12478
12479                let row = snapshot
12480                    .buffer_snapshot
12481                    .buffer_line_for_row(MultiBufferRow(point.row))?
12482                    .1
12483                    .start
12484                    .row;
12485
12486                let context_range =
12487                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12488                Some((
12489                    (runnable.buffer_id, row),
12490                    RunnableTasks {
12491                        templates: tasks,
12492                        offset: snapshot
12493                            .buffer_snapshot
12494                            .anchor_before(runnable.run_range.start),
12495                        context_range,
12496                        column: point.column,
12497                        extra_variables: runnable.extra_captures,
12498                    },
12499                ))
12500            })
12501            .collect()
12502    }
12503
12504    fn templates_with_tags(
12505        project: &Entity<Project>,
12506        runnable: &mut Runnable,
12507        cx: &mut App,
12508    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12509        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12510            let (worktree_id, file) = project
12511                .buffer_for_id(runnable.buffer, cx)
12512                .and_then(|buffer| buffer.read(cx).file())
12513                .map(|file| (file.worktree_id(cx), file.clone()))
12514                .unzip();
12515
12516            (
12517                project.task_store().read(cx).task_inventory().cloned(),
12518                worktree_id,
12519                file,
12520            )
12521        });
12522
12523        let tags = mem::take(&mut runnable.tags);
12524        let mut tags: Vec<_> = tags
12525            .into_iter()
12526            .flat_map(|tag| {
12527                let tag = tag.0.clone();
12528                inventory
12529                    .as_ref()
12530                    .into_iter()
12531                    .flat_map(|inventory| {
12532                        inventory.read(cx).list_tasks(
12533                            file.clone(),
12534                            Some(runnable.language.clone()),
12535                            worktree_id,
12536                            cx,
12537                        )
12538                    })
12539                    .filter(move |(_, template)| {
12540                        template.tags.iter().any(|source_tag| source_tag == &tag)
12541                    })
12542            })
12543            .sorted_by_key(|(kind, _)| kind.to_owned())
12544            .collect();
12545        if let Some((leading_tag_source, _)) = tags.first() {
12546            // Strongest source wins; if we have worktree tag binding, prefer that to
12547            // global and language bindings;
12548            // if we have a global binding, prefer that to language binding.
12549            let first_mismatch = tags
12550                .iter()
12551                .position(|(tag_source, _)| tag_source != leading_tag_source);
12552            if let Some(index) = first_mismatch {
12553                tags.truncate(index);
12554            }
12555        }
12556
12557        tags
12558    }
12559
12560    pub fn move_to_enclosing_bracket(
12561        &mut self,
12562        _: &MoveToEnclosingBracket,
12563        window: &mut Window,
12564        cx: &mut Context<Self>,
12565    ) {
12566        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12567        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12568            s.move_offsets_with(|snapshot, selection| {
12569                let Some(enclosing_bracket_ranges) =
12570                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12571                else {
12572                    return;
12573                };
12574
12575                let mut best_length = usize::MAX;
12576                let mut best_inside = false;
12577                let mut best_in_bracket_range = false;
12578                let mut best_destination = None;
12579                for (open, close) in enclosing_bracket_ranges {
12580                    let close = close.to_inclusive();
12581                    let length = close.end() - open.start;
12582                    let inside = selection.start >= open.end && selection.end <= *close.start();
12583                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
12584                        || close.contains(&selection.head());
12585
12586                    // If best is next to a bracket and current isn't, skip
12587                    if !in_bracket_range && best_in_bracket_range {
12588                        continue;
12589                    }
12590
12591                    // Prefer smaller lengths unless best is inside and current isn't
12592                    if length > best_length && (best_inside || !inside) {
12593                        continue;
12594                    }
12595
12596                    best_length = length;
12597                    best_inside = inside;
12598                    best_in_bracket_range = in_bracket_range;
12599                    best_destination = Some(
12600                        if close.contains(&selection.start) && close.contains(&selection.end) {
12601                            if inside { open.end } else { open.start }
12602                        } else if inside {
12603                            *close.start()
12604                        } else {
12605                            *close.end()
12606                        },
12607                    );
12608                }
12609
12610                if let Some(destination) = best_destination {
12611                    selection.collapse_to(destination, SelectionGoal::None);
12612                }
12613            })
12614        });
12615    }
12616
12617    pub fn undo_selection(
12618        &mut self,
12619        _: &UndoSelection,
12620        window: &mut Window,
12621        cx: &mut Context<Self>,
12622    ) {
12623        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12624        self.end_selection(window, cx);
12625        self.selection_history.mode = SelectionHistoryMode::Undoing;
12626        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12627            self.change_selections(None, window, cx, |s| {
12628                s.select_anchors(entry.selections.to_vec())
12629            });
12630            self.select_next_state = entry.select_next_state;
12631            self.select_prev_state = entry.select_prev_state;
12632            self.add_selections_state = entry.add_selections_state;
12633            self.request_autoscroll(Autoscroll::newest(), cx);
12634        }
12635        self.selection_history.mode = SelectionHistoryMode::Normal;
12636    }
12637
12638    pub fn redo_selection(
12639        &mut self,
12640        _: &RedoSelection,
12641        window: &mut Window,
12642        cx: &mut Context<Self>,
12643    ) {
12644        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12645        self.end_selection(window, cx);
12646        self.selection_history.mode = SelectionHistoryMode::Redoing;
12647        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12648            self.change_selections(None, window, cx, |s| {
12649                s.select_anchors(entry.selections.to_vec())
12650            });
12651            self.select_next_state = entry.select_next_state;
12652            self.select_prev_state = entry.select_prev_state;
12653            self.add_selections_state = entry.add_selections_state;
12654            self.request_autoscroll(Autoscroll::newest(), cx);
12655        }
12656        self.selection_history.mode = SelectionHistoryMode::Normal;
12657    }
12658
12659    pub fn expand_excerpts(
12660        &mut self,
12661        action: &ExpandExcerpts,
12662        _: &mut Window,
12663        cx: &mut Context<Self>,
12664    ) {
12665        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12666    }
12667
12668    pub fn expand_excerpts_down(
12669        &mut self,
12670        action: &ExpandExcerptsDown,
12671        _: &mut Window,
12672        cx: &mut Context<Self>,
12673    ) {
12674        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12675    }
12676
12677    pub fn expand_excerpts_up(
12678        &mut self,
12679        action: &ExpandExcerptsUp,
12680        _: &mut Window,
12681        cx: &mut Context<Self>,
12682    ) {
12683        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12684    }
12685
12686    pub fn expand_excerpts_for_direction(
12687        &mut self,
12688        lines: u32,
12689        direction: ExpandExcerptDirection,
12690
12691        cx: &mut Context<Self>,
12692    ) {
12693        let selections = self.selections.disjoint_anchors();
12694
12695        let lines = if lines == 0 {
12696            EditorSettings::get_global(cx).expand_excerpt_lines
12697        } else {
12698            lines
12699        };
12700
12701        self.buffer.update(cx, |buffer, cx| {
12702            let snapshot = buffer.snapshot(cx);
12703            let mut excerpt_ids = selections
12704                .iter()
12705                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12706                .collect::<Vec<_>>();
12707            excerpt_ids.sort();
12708            excerpt_ids.dedup();
12709            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12710        })
12711    }
12712
12713    pub fn expand_excerpt(
12714        &mut self,
12715        excerpt: ExcerptId,
12716        direction: ExpandExcerptDirection,
12717        window: &mut Window,
12718        cx: &mut Context<Self>,
12719    ) {
12720        let current_scroll_position = self.scroll_position(cx);
12721        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12722        self.buffer.update(cx, |buffer, cx| {
12723            buffer.expand_excerpts([excerpt], lines, direction, cx)
12724        });
12725        if direction == ExpandExcerptDirection::Down {
12726            let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12727            self.set_scroll_position(new_scroll_position, window, cx);
12728        }
12729    }
12730
12731    pub fn go_to_singleton_buffer_point(
12732        &mut self,
12733        point: Point,
12734        window: &mut Window,
12735        cx: &mut Context<Self>,
12736    ) {
12737        self.go_to_singleton_buffer_range(point..point, window, cx);
12738    }
12739
12740    pub fn go_to_singleton_buffer_range(
12741        &mut self,
12742        range: Range<Point>,
12743        window: &mut Window,
12744        cx: &mut Context<Self>,
12745    ) {
12746        let multibuffer = self.buffer().read(cx);
12747        let Some(buffer) = multibuffer.as_singleton() else {
12748            return;
12749        };
12750        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12751            return;
12752        };
12753        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12754            return;
12755        };
12756        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12757            s.select_anchor_ranges([start..end])
12758        });
12759    }
12760
12761    fn go_to_diagnostic(
12762        &mut self,
12763        _: &GoToDiagnostic,
12764        window: &mut Window,
12765        cx: &mut Context<Self>,
12766    ) {
12767        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12768        self.go_to_diagnostic_impl(Direction::Next, window, cx)
12769    }
12770
12771    fn go_to_prev_diagnostic(
12772        &mut self,
12773        _: &GoToPreviousDiagnostic,
12774        window: &mut Window,
12775        cx: &mut Context<Self>,
12776    ) {
12777        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12778        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12779    }
12780
12781    pub fn go_to_diagnostic_impl(
12782        &mut self,
12783        direction: Direction,
12784        window: &mut Window,
12785        cx: &mut Context<Self>,
12786    ) {
12787        let buffer = self.buffer.read(cx).snapshot(cx);
12788        let selection = self.selections.newest::<usize>(cx);
12789        // If there is an active Diagnostic Popover jump to its diagnostic instead.
12790        if direction == Direction::Next {
12791            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12792                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12793                    return;
12794                };
12795                self.activate_diagnostics(
12796                    buffer_id,
12797                    popover.local_diagnostic.diagnostic.group_id,
12798                    window,
12799                    cx,
12800                );
12801                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12802                    let primary_range_start = active_diagnostics.primary_range.start;
12803                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12804                        let mut new_selection = s.newest_anchor().clone();
12805                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12806                        s.select_anchors(vec![new_selection.clone()]);
12807                    });
12808                    self.refresh_inline_completion(false, true, window, cx);
12809                }
12810                return;
12811            }
12812        }
12813
12814        let active_group_id = self
12815            .active_diagnostics
12816            .as_ref()
12817            .map(|active_group| active_group.group_id);
12818        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12819            active_diagnostics
12820                .primary_range
12821                .to_offset(&buffer)
12822                .to_inclusive()
12823        });
12824        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12825            if active_primary_range.contains(&selection.head()) {
12826                *active_primary_range.start()
12827            } else {
12828                selection.head()
12829            }
12830        } else {
12831            selection.head()
12832        };
12833
12834        let snapshot = self.snapshot(window, cx);
12835        let primary_diagnostics_before = buffer
12836            .diagnostics_in_range::<usize>(0..search_start)
12837            .filter(|entry| entry.diagnostic.is_primary)
12838            .filter(|entry| entry.range.start != entry.range.end)
12839            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12840            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12841            .collect::<Vec<_>>();
12842        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12843            primary_diagnostics_before
12844                .iter()
12845                .position(|entry| entry.diagnostic.group_id == active_group_id)
12846        });
12847
12848        let primary_diagnostics_after = buffer
12849            .diagnostics_in_range::<usize>(search_start..buffer.len())
12850            .filter(|entry| entry.diagnostic.is_primary)
12851            .filter(|entry| entry.range.start != entry.range.end)
12852            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12853            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12854            .collect::<Vec<_>>();
12855        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12856            primary_diagnostics_after
12857                .iter()
12858                .enumerate()
12859                .rev()
12860                .find_map(|(i, entry)| {
12861                    if entry.diagnostic.group_id == active_group_id {
12862                        Some(i)
12863                    } else {
12864                        None
12865                    }
12866                })
12867        });
12868
12869        let next_primary_diagnostic = match direction {
12870            Direction::Prev => primary_diagnostics_before
12871                .iter()
12872                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12873                .rev()
12874                .next(),
12875            Direction::Next => primary_diagnostics_after
12876                .iter()
12877                .skip(
12878                    last_same_group_diagnostic_after
12879                        .map(|index| index + 1)
12880                        .unwrap_or(0),
12881                )
12882                .next(),
12883        };
12884
12885        // Cycle around to the start of the buffer, potentially moving back to the start of
12886        // the currently active diagnostic.
12887        let cycle_around = || match direction {
12888            Direction::Prev => primary_diagnostics_after
12889                .iter()
12890                .rev()
12891                .chain(primary_diagnostics_before.iter().rev())
12892                .next(),
12893            Direction::Next => primary_diagnostics_before
12894                .iter()
12895                .chain(primary_diagnostics_after.iter())
12896                .next(),
12897        };
12898
12899        if let Some((primary_range, group_id)) = next_primary_diagnostic
12900            .or_else(cycle_around)
12901            .map(|entry| (&entry.range, entry.diagnostic.group_id))
12902        {
12903            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12904                return;
12905            };
12906            self.activate_diagnostics(buffer_id, group_id, window, cx);
12907            if self.active_diagnostics.is_some() {
12908                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12909                    s.select(vec![Selection {
12910                        id: selection.id,
12911                        start: primary_range.start,
12912                        end: primary_range.start,
12913                        reversed: false,
12914                        goal: SelectionGoal::None,
12915                    }]);
12916                });
12917                self.refresh_inline_completion(false, true, window, cx);
12918            }
12919        }
12920    }
12921
12922    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12923        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12924        let snapshot = self.snapshot(window, cx);
12925        let selection = self.selections.newest::<Point>(cx);
12926        self.go_to_hunk_before_or_after_position(
12927            &snapshot,
12928            selection.head(),
12929            Direction::Next,
12930            window,
12931            cx,
12932        );
12933    }
12934
12935    pub fn go_to_hunk_before_or_after_position(
12936        &mut self,
12937        snapshot: &EditorSnapshot,
12938        position: Point,
12939        direction: Direction,
12940        window: &mut Window,
12941        cx: &mut Context<Editor>,
12942    ) {
12943        let row = if direction == Direction::Next {
12944            self.hunk_after_position(snapshot, position)
12945                .map(|hunk| hunk.row_range.start)
12946        } else {
12947            self.hunk_before_position(snapshot, position)
12948        };
12949
12950        if let Some(row) = row {
12951            let destination = Point::new(row.0, 0);
12952            let autoscroll = Autoscroll::center();
12953
12954            self.unfold_ranges(&[destination..destination], false, false, cx);
12955            self.change_selections(Some(autoscroll), window, cx, |s| {
12956                s.select_ranges([destination..destination]);
12957            });
12958        }
12959    }
12960
12961    fn hunk_after_position(
12962        &mut self,
12963        snapshot: &EditorSnapshot,
12964        position: Point,
12965    ) -> Option<MultiBufferDiffHunk> {
12966        snapshot
12967            .buffer_snapshot
12968            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12969            .find(|hunk| hunk.row_range.start.0 > position.row)
12970            .or_else(|| {
12971                snapshot
12972                    .buffer_snapshot
12973                    .diff_hunks_in_range(Point::zero()..position)
12974                    .find(|hunk| hunk.row_range.end.0 < position.row)
12975            })
12976    }
12977
12978    fn go_to_prev_hunk(
12979        &mut self,
12980        _: &GoToPreviousHunk,
12981        window: &mut Window,
12982        cx: &mut Context<Self>,
12983    ) {
12984        self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12985        let snapshot = self.snapshot(window, cx);
12986        let selection = self.selections.newest::<Point>(cx);
12987        self.go_to_hunk_before_or_after_position(
12988            &snapshot,
12989            selection.head(),
12990            Direction::Prev,
12991            window,
12992            cx,
12993        );
12994    }
12995
12996    fn hunk_before_position(
12997        &mut self,
12998        snapshot: &EditorSnapshot,
12999        position: Point,
13000    ) -> Option<MultiBufferRow> {
13001        snapshot
13002            .buffer_snapshot
13003            .diff_hunk_before(position)
13004            .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13005    }
13006
13007    fn go_to_line<T: 'static>(
13008        &mut self,
13009        position: Anchor,
13010        highlight_color: Option<Hsla>,
13011        window: &mut Window,
13012        cx: &mut Context<Self>,
13013    ) {
13014        let snapshot = self.snapshot(window, cx).display_snapshot;
13015        let position = position.to_point(&snapshot.buffer_snapshot);
13016        let start = snapshot
13017            .buffer_snapshot
13018            .clip_point(Point::new(position.row, 0), Bias::Left);
13019        let end = start + Point::new(1, 0);
13020        let start = snapshot.buffer_snapshot.anchor_before(start);
13021        let end = snapshot.buffer_snapshot.anchor_before(end);
13022
13023        self.highlight_rows::<T>(
13024            start..end,
13025            highlight_color
13026                .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13027            false,
13028            cx,
13029        );
13030        self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13031    }
13032
13033    pub fn go_to_definition(
13034        &mut self,
13035        _: &GoToDefinition,
13036        window: &mut Window,
13037        cx: &mut Context<Self>,
13038    ) -> Task<Result<Navigated>> {
13039        let definition =
13040            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13041        let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13042        cx.spawn_in(window, async move |editor, cx| {
13043            if definition.await? == Navigated::Yes {
13044                return Ok(Navigated::Yes);
13045            }
13046            match fallback_strategy {
13047                GoToDefinitionFallback::None => Ok(Navigated::No),
13048                GoToDefinitionFallback::FindAllReferences => {
13049                    match editor.update_in(cx, |editor, window, cx| {
13050                        editor.find_all_references(&FindAllReferences, window, cx)
13051                    })? {
13052                        Some(references) => references.await,
13053                        None => Ok(Navigated::No),
13054                    }
13055                }
13056            }
13057        })
13058    }
13059
13060    pub fn go_to_declaration(
13061        &mut self,
13062        _: &GoToDeclaration,
13063        window: &mut Window,
13064        cx: &mut Context<Self>,
13065    ) -> Task<Result<Navigated>> {
13066        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13067    }
13068
13069    pub fn go_to_declaration_split(
13070        &mut self,
13071        _: &GoToDeclaration,
13072        window: &mut Window,
13073        cx: &mut Context<Self>,
13074    ) -> Task<Result<Navigated>> {
13075        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13076    }
13077
13078    pub fn go_to_implementation(
13079        &mut self,
13080        _: &GoToImplementation,
13081        window: &mut Window,
13082        cx: &mut Context<Self>,
13083    ) -> Task<Result<Navigated>> {
13084        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13085    }
13086
13087    pub fn go_to_implementation_split(
13088        &mut self,
13089        _: &GoToImplementationSplit,
13090        window: &mut Window,
13091        cx: &mut Context<Self>,
13092    ) -> Task<Result<Navigated>> {
13093        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13094    }
13095
13096    pub fn go_to_type_definition(
13097        &mut self,
13098        _: &GoToTypeDefinition,
13099        window: &mut Window,
13100        cx: &mut Context<Self>,
13101    ) -> Task<Result<Navigated>> {
13102        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13103    }
13104
13105    pub fn go_to_definition_split(
13106        &mut self,
13107        _: &GoToDefinitionSplit,
13108        window: &mut Window,
13109        cx: &mut Context<Self>,
13110    ) -> Task<Result<Navigated>> {
13111        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13112    }
13113
13114    pub fn go_to_type_definition_split(
13115        &mut self,
13116        _: &GoToTypeDefinitionSplit,
13117        window: &mut Window,
13118        cx: &mut Context<Self>,
13119    ) -> Task<Result<Navigated>> {
13120        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13121    }
13122
13123    fn go_to_definition_of_kind(
13124        &mut self,
13125        kind: GotoDefinitionKind,
13126        split: bool,
13127        window: &mut Window,
13128        cx: &mut Context<Self>,
13129    ) -> Task<Result<Navigated>> {
13130        let Some(provider) = self.semantics_provider.clone() else {
13131            return Task::ready(Ok(Navigated::No));
13132        };
13133        let head = self.selections.newest::<usize>(cx).head();
13134        let buffer = self.buffer.read(cx);
13135        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13136            text_anchor
13137        } else {
13138            return Task::ready(Ok(Navigated::No));
13139        };
13140
13141        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13142            return Task::ready(Ok(Navigated::No));
13143        };
13144
13145        cx.spawn_in(window, async move |editor, cx| {
13146            let definitions = definitions.await?;
13147            let navigated = editor
13148                .update_in(cx, |editor, window, cx| {
13149                    editor.navigate_to_hover_links(
13150                        Some(kind),
13151                        definitions
13152                            .into_iter()
13153                            .filter(|location| {
13154                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13155                            })
13156                            .map(HoverLink::Text)
13157                            .collect::<Vec<_>>(),
13158                        split,
13159                        window,
13160                        cx,
13161                    )
13162                })?
13163                .await?;
13164            anyhow::Ok(navigated)
13165        })
13166    }
13167
13168    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13169        let selection = self.selections.newest_anchor();
13170        let head = selection.head();
13171        let tail = selection.tail();
13172
13173        let Some((buffer, start_position)) =
13174            self.buffer.read(cx).text_anchor_for_position(head, cx)
13175        else {
13176            return;
13177        };
13178
13179        let end_position = if head != tail {
13180            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13181                return;
13182            };
13183            Some(pos)
13184        } else {
13185            None
13186        };
13187
13188        let url_finder = cx.spawn_in(window, async move |editor, cx| {
13189            let url = if let Some(end_pos) = end_position {
13190                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13191            } else {
13192                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13193            };
13194
13195            if let Some(url) = url {
13196                editor.update(cx, |_, cx| {
13197                    cx.open_url(&url);
13198                })
13199            } else {
13200                Ok(())
13201            }
13202        });
13203
13204        url_finder.detach();
13205    }
13206
13207    pub fn open_selected_filename(
13208        &mut self,
13209        _: &OpenSelectedFilename,
13210        window: &mut Window,
13211        cx: &mut Context<Self>,
13212    ) {
13213        let Some(workspace) = self.workspace() else {
13214            return;
13215        };
13216
13217        let position = self.selections.newest_anchor().head();
13218
13219        let Some((buffer, buffer_position)) =
13220            self.buffer.read(cx).text_anchor_for_position(position, cx)
13221        else {
13222            return;
13223        };
13224
13225        let project = self.project.clone();
13226
13227        cx.spawn_in(window, async move |_, cx| {
13228            let result = find_file(&buffer, project, buffer_position, cx).await;
13229
13230            if let Some((_, path)) = result {
13231                workspace
13232                    .update_in(cx, |workspace, window, cx| {
13233                        workspace.open_resolved_path(path, window, cx)
13234                    })?
13235                    .await?;
13236            }
13237            anyhow::Ok(())
13238        })
13239        .detach();
13240    }
13241
13242    pub(crate) fn navigate_to_hover_links(
13243        &mut self,
13244        kind: Option<GotoDefinitionKind>,
13245        mut definitions: Vec<HoverLink>,
13246        split: bool,
13247        window: &mut Window,
13248        cx: &mut Context<Editor>,
13249    ) -> Task<Result<Navigated>> {
13250        // If there is one definition, just open it directly
13251        if definitions.len() == 1 {
13252            let definition = definitions.pop().unwrap();
13253
13254            enum TargetTaskResult {
13255                Location(Option<Location>),
13256                AlreadyNavigated,
13257            }
13258
13259            let target_task = match definition {
13260                HoverLink::Text(link) => {
13261                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13262                }
13263                HoverLink::InlayHint(lsp_location, server_id) => {
13264                    let computation =
13265                        self.compute_target_location(lsp_location, server_id, window, cx);
13266                    cx.background_spawn(async move {
13267                        let location = computation.await?;
13268                        Ok(TargetTaskResult::Location(location))
13269                    })
13270                }
13271                HoverLink::Url(url) => {
13272                    cx.open_url(&url);
13273                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13274                }
13275                HoverLink::File(path) => {
13276                    if let Some(workspace) = self.workspace() {
13277                        cx.spawn_in(window, async move |_, cx| {
13278                            workspace
13279                                .update_in(cx, |workspace, window, cx| {
13280                                    workspace.open_resolved_path(path, window, cx)
13281                                })?
13282                                .await
13283                                .map(|_| TargetTaskResult::AlreadyNavigated)
13284                        })
13285                    } else {
13286                        Task::ready(Ok(TargetTaskResult::Location(None)))
13287                    }
13288                }
13289            };
13290            cx.spawn_in(window, async move |editor, cx| {
13291                let target = match target_task.await.context("target resolution task")? {
13292                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13293                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
13294                    TargetTaskResult::Location(Some(target)) => target,
13295                };
13296
13297                editor.update_in(cx, |editor, window, cx| {
13298                    let Some(workspace) = editor.workspace() else {
13299                        return Navigated::No;
13300                    };
13301                    let pane = workspace.read(cx).active_pane().clone();
13302
13303                    let range = target.range.to_point(target.buffer.read(cx));
13304                    let range = editor.range_for_match(&range);
13305                    let range = collapse_multiline_range(range);
13306
13307                    if !split
13308                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13309                    {
13310                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13311                    } else {
13312                        window.defer(cx, move |window, cx| {
13313                            let target_editor: Entity<Self> =
13314                                workspace.update(cx, |workspace, cx| {
13315                                    let pane = if split {
13316                                        workspace.adjacent_pane(window, cx)
13317                                    } else {
13318                                        workspace.active_pane().clone()
13319                                    };
13320
13321                                    workspace.open_project_item(
13322                                        pane,
13323                                        target.buffer.clone(),
13324                                        true,
13325                                        true,
13326                                        window,
13327                                        cx,
13328                                    )
13329                                });
13330                            target_editor.update(cx, |target_editor, cx| {
13331                                // When selecting a definition in a different buffer, disable the nav history
13332                                // to avoid creating a history entry at the previous cursor location.
13333                                pane.update(cx, |pane, _| pane.disable_history());
13334                                target_editor.go_to_singleton_buffer_range(range, window, cx);
13335                                pane.update(cx, |pane, _| pane.enable_history());
13336                            });
13337                        });
13338                    }
13339                    Navigated::Yes
13340                })
13341            })
13342        } else if !definitions.is_empty() {
13343            cx.spawn_in(window, async move |editor, cx| {
13344                let (title, location_tasks, workspace) = editor
13345                    .update_in(cx, |editor, window, cx| {
13346                        let tab_kind = match kind {
13347                            Some(GotoDefinitionKind::Implementation) => "Implementations",
13348                            _ => "Definitions",
13349                        };
13350                        let title = definitions
13351                            .iter()
13352                            .find_map(|definition| match definition {
13353                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13354                                    let buffer = origin.buffer.read(cx);
13355                                    format!(
13356                                        "{} for {}",
13357                                        tab_kind,
13358                                        buffer
13359                                            .text_for_range(origin.range.clone())
13360                                            .collect::<String>()
13361                                    )
13362                                }),
13363                                HoverLink::InlayHint(_, _) => None,
13364                                HoverLink::Url(_) => None,
13365                                HoverLink::File(_) => None,
13366                            })
13367                            .unwrap_or(tab_kind.to_string());
13368                        let location_tasks = definitions
13369                            .into_iter()
13370                            .map(|definition| match definition {
13371                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13372                                HoverLink::InlayHint(lsp_location, server_id) => editor
13373                                    .compute_target_location(lsp_location, server_id, window, cx),
13374                                HoverLink::Url(_) => Task::ready(Ok(None)),
13375                                HoverLink::File(_) => Task::ready(Ok(None)),
13376                            })
13377                            .collect::<Vec<_>>();
13378                        (title, location_tasks, editor.workspace().clone())
13379                    })
13380                    .context("location tasks preparation")?;
13381
13382                let locations = future::join_all(location_tasks)
13383                    .await
13384                    .into_iter()
13385                    .filter_map(|location| location.transpose())
13386                    .collect::<Result<_>>()
13387                    .context("location tasks")?;
13388
13389                let Some(workspace) = workspace else {
13390                    return Ok(Navigated::No);
13391                };
13392                let opened = workspace
13393                    .update_in(cx, |workspace, window, cx| {
13394                        Self::open_locations_in_multibuffer(
13395                            workspace,
13396                            locations,
13397                            title,
13398                            split,
13399                            MultibufferSelectionMode::First,
13400                            window,
13401                            cx,
13402                        )
13403                    })
13404                    .ok();
13405
13406                anyhow::Ok(Navigated::from_bool(opened.is_some()))
13407            })
13408        } else {
13409            Task::ready(Ok(Navigated::No))
13410        }
13411    }
13412
13413    fn compute_target_location(
13414        &self,
13415        lsp_location: lsp::Location,
13416        server_id: LanguageServerId,
13417        window: &mut Window,
13418        cx: &mut Context<Self>,
13419    ) -> Task<anyhow::Result<Option<Location>>> {
13420        let Some(project) = self.project.clone() else {
13421            return Task::ready(Ok(None));
13422        };
13423
13424        cx.spawn_in(window, async move |editor, cx| {
13425            let location_task = editor.update(cx, |_, cx| {
13426                project.update(cx, |project, cx| {
13427                    let language_server_name = project
13428                        .language_server_statuses(cx)
13429                        .find(|(id, _)| server_id == *id)
13430                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13431                    language_server_name.map(|language_server_name| {
13432                        project.open_local_buffer_via_lsp(
13433                            lsp_location.uri.clone(),
13434                            server_id,
13435                            language_server_name,
13436                            cx,
13437                        )
13438                    })
13439                })
13440            })?;
13441            let location = match location_task {
13442                Some(task) => Some({
13443                    let target_buffer_handle = task.await.context("open local buffer")?;
13444                    let range = target_buffer_handle.update(cx, |target_buffer, _| {
13445                        let target_start = target_buffer
13446                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13447                        let target_end = target_buffer
13448                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13449                        target_buffer.anchor_after(target_start)
13450                            ..target_buffer.anchor_before(target_end)
13451                    })?;
13452                    Location {
13453                        buffer: target_buffer_handle,
13454                        range,
13455                    }
13456                }),
13457                None => None,
13458            };
13459            Ok(location)
13460        })
13461    }
13462
13463    pub fn find_all_references(
13464        &mut self,
13465        _: &FindAllReferences,
13466        window: &mut Window,
13467        cx: &mut Context<Self>,
13468    ) -> Option<Task<Result<Navigated>>> {
13469        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13470
13471        let selection = self.selections.newest::<usize>(cx);
13472        let multi_buffer = self.buffer.read(cx);
13473        let head = selection.head();
13474
13475        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13476        let head_anchor = multi_buffer_snapshot.anchor_at(
13477            head,
13478            if head < selection.tail() {
13479                Bias::Right
13480            } else {
13481                Bias::Left
13482            },
13483        );
13484
13485        match self
13486            .find_all_references_task_sources
13487            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13488        {
13489            Ok(_) => {
13490                log::info!(
13491                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
13492                );
13493                return None;
13494            }
13495            Err(i) => {
13496                self.find_all_references_task_sources.insert(i, head_anchor);
13497            }
13498        }
13499
13500        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13501        let workspace = self.workspace()?;
13502        let project = workspace.read(cx).project().clone();
13503        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13504        Some(cx.spawn_in(window, async move |editor, cx| {
13505            let _cleanup = cx.on_drop(&editor, move |editor, _| {
13506                if let Ok(i) = editor
13507                    .find_all_references_task_sources
13508                    .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13509                {
13510                    editor.find_all_references_task_sources.remove(i);
13511                }
13512            });
13513
13514            let locations = references.await?;
13515            if locations.is_empty() {
13516                return anyhow::Ok(Navigated::No);
13517            }
13518
13519            workspace.update_in(cx, |workspace, window, cx| {
13520                let title = locations
13521                    .first()
13522                    .as_ref()
13523                    .map(|location| {
13524                        let buffer = location.buffer.read(cx);
13525                        format!(
13526                            "References to `{}`",
13527                            buffer
13528                                .text_for_range(location.range.clone())
13529                                .collect::<String>()
13530                        )
13531                    })
13532                    .unwrap();
13533                Self::open_locations_in_multibuffer(
13534                    workspace,
13535                    locations,
13536                    title,
13537                    false,
13538                    MultibufferSelectionMode::First,
13539                    window,
13540                    cx,
13541                );
13542                Navigated::Yes
13543            })
13544        }))
13545    }
13546
13547    /// Opens a multibuffer with the given project locations in it
13548    pub fn open_locations_in_multibuffer(
13549        workspace: &mut Workspace,
13550        mut locations: Vec<Location>,
13551        title: String,
13552        split: bool,
13553        multibuffer_selection_mode: MultibufferSelectionMode,
13554        window: &mut Window,
13555        cx: &mut Context<Workspace>,
13556    ) {
13557        // If there are multiple definitions, open them in a multibuffer
13558        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13559        let mut locations = locations.into_iter().peekable();
13560        let mut ranges: Vec<Range<Anchor>> = Vec::new();
13561        let capability = workspace.project().read(cx).capability();
13562
13563        let excerpt_buffer = cx.new(|cx| {
13564            let mut multibuffer = MultiBuffer::new(capability);
13565            while let Some(location) = locations.next() {
13566                let buffer = location.buffer.read(cx);
13567                let mut ranges_for_buffer = Vec::new();
13568                let range = location.range.to_point(buffer);
13569                ranges_for_buffer.push(range.clone());
13570
13571                while let Some(next_location) = locations.peek() {
13572                    if next_location.buffer == location.buffer {
13573                        ranges_for_buffer.push(next_location.range.to_point(buffer));
13574                        locations.next();
13575                    } else {
13576                        break;
13577                    }
13578                }
13579
13580                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13581                let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13582                    PathKey::for_buffer(&location.buffer, cx),
13583                    location.buffer.clone(),
13584                    ranges_for_buffer,
13585                    DEFAULT_MULTIBUFFER_CONTEXT,
13586                    cx,
13587                );
13588                ranges.extend(new_ranges)
13589            }
13590
13591            multibuffer.with_title(title)
13592        });
13593
13594        let editor = cx.new(|cx| {
13595            Editor::for_multibuffer(
13596                excerpt_buffer,
13597                Some(workspace.project().clone()),
13598                window,
13599                cx,
13600            )
13601        });
13602        editor.update(cx, |editor, cx| {
13603            match multibuffer_selection_mode {
13604                MultibufferSelectionMode::First => {
13605                    if let Some(first_range) = ranges.first() {
13606                        editor.change_selections(None, window, cx, |selections| {
13607                            selections.clear_disjoint();
13608                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13609                        });
13610                    }
13611                    editor.highlight_background::<Self>(
13612                        &ranges,
13613                        |theme| theme.editor_highlighted_line_background,
13614                        cx,
13615                    );
13616                }
13617                MultibufferSelectionMode::All => {
13618                    editor.change_selections(None, window, cx, |selections| {
13619                        selections.clear_disjoint();
13620                        selections.select_anchor_ranges(ranges);
13621                    });
13622                }
13623            }
13624            editor.register_buffers_with_language_servers(cx);
13625        });
13626
13627        let item = Box::new(editor);
13628        let item_id = item.item_id();
13629
13630        if split {
13631            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13632        } else {
13633            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13634                let (preview_item_id, preview_item_idx) =
13635                    workspace.active_pane().update(cx, |pane, _| {
13636                        (pane.preview_item_id(), pane.preview_item_idx())
13637                    });
13638
13639                workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13640
13641                if let Some(preview_item_id) = preview_item_id {
13642                    workspace.active_pane().update(cx, |pane, cx| {
13643                        pane.remove_item(preview_item_id, false, false, window, cx);
13644                    });
13645                }
13646            } else {
13647                workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13648            }
13649        }
13650        workspace.active_pane().update(cx, |pane, cx| {
13651            pane.set_preview_item_id(Some(item_id), cx);
13652        });
13653    }
13654
13655    pub fn rename(
13656        &mut self,
13657        _: &Rename,
13658        window: &mut Window,
13659        cx: &mut Context<Self>,
13660    ) -> Option<Task<Result<()>>> {
13661        use language::ToOffset as _;
13662
13663        let provider = self.semantics_provider.clone()?;
13664        let selection = self.selections.newest_anchor().clone();
13665        let (cursor_buffer, cursor_buffer_position) = self
13666            .buffer
13667            .read(cx)
13668            .text_anchor_for_position(selection.head(), cx)?;
13669        let (tail_buffer, cursor_buffer_position_end) = self
13670            .buffer
13671            .read(cx)
13672            .text_anchor_for_position(selection.tail(), cx)?;
13673        if tail_buffer != cursor_buffer {
13674            return None;
13675        }
13676
13677        let snapshot = cursor_buffer.read(cx).snapshot();
13678        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13679        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13680        let prepare_rename = provider
13681            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13682            .unwrap_or_else(|| Task::ready(Ok(None)));
13683        drop(snapshot);
13684
13685        Some(cx.spawn_in(window, async move |this, cx| {
13686            let rename_range = if let Some(range) = prepare_rename.await? {
13687                Some(range)
13688            } else {
13689                this.update(cx, |this, cx| {
13690                    let buffer = this.buffer.read(cx).snapshot(cx);
13691                    let mut buffer_highlights = this
13692                        .document_highlights_for_position(selection.head(), &buffer)
13693                        .filter(|highlight| {
13694                            highlight.start.excerpt_id == selection.head().excerpt_id
13695                                && highlight.end.excerpt_id == selection.head().excerpt_id
13696                        });
13697                    buffer_highlights
13698                        .next()
13699                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13700                })?
13701            };
13702            if let Some(rename_range) = rename_range {
13703                this.update_in(cx, |this, window, cx| {
13704                    let snapshot = cursor_buffer.read(cx).snapshot();
13705                    let rename_buffer_range = rename_range.to_offset(&snapshot);
13706                    let cursor_offset_in_rename_range =
13707                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13708                    let cursor_offset_in_rename_range_end =
13709                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13710
13711                    this.take_rename(false, window, cx);
13712                    let buffer = this.buffer.read(cx).read(cx);
13713                    let cursor_offset = selection.head().to_offset(&buffer);
13714                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13715                    let rename_end = rename_start + rename_buffer_range.len();
13716                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13717                    let mut old_highlight_id = None;
13718                    let old_name: Arc<str> = buffer
13719                        .chunks(rename_start..rename_end, true)
13720                        .map(|chunk| {
13721                            if old_highlight_id.is_none() {
13722                                old_highlight_id = chunk.syntax_highlight_id;
13723                            }
13724                            chunk.text
13725                        })
13726                        .collect::<String>()
13727                        .into();
13728
13729                    drop(buffer);
13730
13731                    // Position the selection in the rename editor so that it matches the current selection.
13732                    this.show_local_selections = false;
13733                    let rename_editor = cx.new(|cx| {
13734                        let mut editor = Editor::single_line(window, cx);
13735                        editor.buffer.update(cx, |buffer, cx| {
13736                            buffer.edit([(0..0, old_name.clone())], None, cx)
13737                        });
13738                        let rename_selection_range = match cursor_offset_in_rename_range
13739                            .cmp(&cursor_offset_in_rename_range_end)
13740                        {
13741                            Ordering::Equal => {
13742                                editor.select_all(&SelectAll, window, cx);
13743                                return editor;
13744                            }
13745                            Ordering::Less => {
13746                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13747                            }
13748                            Ordering::Greater => {
13749                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13750                            }
13751                        };
13752                        if rename_selection_range.end > old_name.len() {
13753                            editor.select_all(&SelectAll, window, cx);
13754                        } else {
13755                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13756                                s.select_ranges([rename_selection_range]);
13757                            });
13758                        }
13759                        editor
13760                    });
13761                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13762                        if e == &EditorEvent::Focused {
13763                            cx.emit(EditorEvent::FocusedIn)
13764                        }
13765                    })
13766                    .detach();
13767
13768                    let write_highlights =
13769                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13770                    let read_highlights =
13771                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
13772                    let ranges = write_highlights
13773                        .iter()
13774                        .flat_map(|(_, ranges)| ranges.iter())
13775                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13776                        .cloned()
13777                        .collect();
13778
13779                    this.highlight_text::<Rename>(
13780                        ranges,
13781                        HighlightStyle {
13782                            fade_out: Some(0.6),
13783                            ..Default::default()
13784                        },
13785                        cx,
13786                    );
13787                    let rename_focus_handle = rename_editor.focus_handle(cx);
13788                    window.focus(&rename_focus_handle);
13789                    let block_id = this.insert_blocks(
13790                        [BlockProperties {
13791                            style: BlockStyle::Flex,
13792                            placement: BlockPlacement::Below(range.start),
13793                            height: Some(1),
13794                            render: Arc::new({
13795                                let rename_editor = rename_editor.clone();
13796                                move |cx: &mut BlockContext| {
13797                                    let mut text_style = cx.editor_style.text.clone();
13798                                    if let Some(highlight_style) = old_highlight_id
13799                                        .and_then(|h| h.style(&cx.editor_style.syntax))
13800                                    {
13801                                        text_style = text_style.highlight(highlight_style);
13802                                    }
13803                                    div()
13804                                        .block_mouse_down()
13805                                        .pl(cx.anchor_x)
13806                                        .child(EditorElement::new(
13807                                            &rename_editor,
13808                                            EditorStyle {
13809                                                background: cx.theme().system().transparent,
13810                                                local_player: cx.editor_style.local_player,
13811                                                text: text_style,
13812                                                scrollbar_width: cx.editor_style.scrollbar_width,
13813                                                syntax: cx.editor_style.syntax.clone(),
13814                                                status: cx.editor_style.status.clone(),
13815                                                inlay_hints_style: HighlightStyle {
13816                                                    font_weight: Some(FontWeight::BOLD),
13817                                                    ..make_inlay_hints_style(cx.app)
13818                                                },
13819                                                inline_completion_styles: make_suggestion_styles(
13820                                                    cx.app,
13821                                                ),
13822                                                ..EditorStyle::default()
13823                                            },
13824                                        ))
13825                                        .into_any_element()
13826                                }
13827                            }),
13828                            priority: 0,
13829                        }],
13830                        Some(Autoscroll::fit()),
13831                        cx,
13832                    )[0];
13833                    this.pending_rename = Some(RenameState {
13834                        range,
13835                        old_name,
13836                        editor: rename_editor,
13837                        block_id,
13838                    });
13839                })?;
13840            }
13841
13842            Ok(())
13843        }))
13844    }
13845
13846    pub fn confirm_rename(
13847        &mut self,
13848        _: &ConfirmRename,
13849        window: &mut Window,
13850        cx: &mut Context<Self>,
13851    ) -> Option<Task<Result<()>>> {
13852        let rename = self.take_rename(false, window, cx)?;
13853        let workspace = self.workspace()?.downgrade();
13854        let (buffer, start) = self
13855            .buffer
13856            .read(cx)
13857            .text_anchor_for_position(rename.range.start, cx)?;
13858        let (end_buffer, _) = self
13859            .buffer
13860            .read(cx)
13861            .text_anchor_for_position(rename.range.end, cx)?;
13862        if buffer != end_buffer {
13863            return None;
13864        }
13865
13866        let old_name = rename.old_name;
13867        let new_name = rename.editor.read(cx).text(cx);
13868
13869        let rename = self.semantics_provider.as_ref()?.perform_rename(
13870            &buffer,
13871            start,
13872            new_name.clone(),
13873            cx,
13874        )?;
13875
13876        Some(cx.spawn_in(window, async move |editor, cx| {
13877            let project_transaction = rename.await?;
13878            Self::open_project_transaction(
13879                &editor,
13880                workspace,
13881                project_transaction,
13882                format!("Rename: {}{}", old_name, new_name),
13883                cx,
13884            )
13885            .await?;
13886
13887            editor.update(cx, |editor, cx| {
13888                editor.refresh_document_highlights(cx);
13889            })?;
13890            Ok(())
13891        }))
13892    }
13893
13894    fn take_rename(
13895        &mut self,
13896        moving_cursor: bool,
13897        window: &mut Window,
13898        cx: &mut Context<Self>,
13899    ) -> Option<RenameState> {
13900        let rename = self.pending_rename.take()?;
13901        if rename.editor.focus_handle(cx).is_focused(window) {
13902            window.focus(&self.focus_handle);
13903        }
13904
13905        self.remove_blocks(
13906            [rename.block_id].into_iter().collect(),
13907            Some(Autoscroll::fit()),
13908            cx,
13909        );
13910        self.clear_highlights::<Rename>(cx);
13911        self.show_local_selections = true;
13912
13913        if moving_cursor {
13914            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13915                editor.selections.newest::<usize>(cx).head()
13916            });
13917
13918            // Update the selection to match the position of the selection inside
13919            // the rename editor.
13920            let snapshot = self.buffer.read(cx).read(cx);
13921            let rename_range = rename.range.to_offset(&snapshot);
13922            let cursor_in_editor = snapshot
13923                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13924                .min(rename_range.end);
13925            drop(snapshot);
13926
13927            self.change_selections(None, window, cx, |s| {
13928                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13929            });
13930        } else {
13931            self.refresh_document_highlights(cx);
13932        }
13933
13934        Some(rename)
13935    }
13936
13937    pub fn pending_rename(&self) -> Option<&RenameState> {
13938        self.pending_rename.as_ref()
13939    }
13940
13941    fn format(
13942        &mut self,
13943        _: &Format,
13944        window: &mut Window,
13945        cx: &mut Context<Self>,
13946    ) -> Option<Task<Result<()>>> {
13947        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13948
13949        let project = match &self.project {
13950            Some(project) => project.clone(),
13951            None => return None,
13952        };
13953
13954        Some(self.perform_format(
13955            project,
13956            FormatTrigger::Manual,
13957            FormatTarget::Buffers,
13958            window,
13959            cx,
13960        ))
13961    }
13962
13963    fn format_selections(
13964        &mut self,
13965        _: &FormatSelections,
13966        window: &mut Window,
13967        cx: &mut Context<Self>,
13968    ) -> Option<Task<Result<()>>> {
13969        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13970
13971        let project = match &self.project {
13972            Some(project) => project.clone(),
13973            None => return None,
13974        };
13975
13976        let ranges = self
13977            .selections
13978            .all_adjusted(cx)
13979            .into_iter()
13980            .map(|selection| selection.range())
13981            .collect_vec();
13982
13983        Some(self.perform_format(
13984            project,
13985            FormatTrigger::Manual,
13986            FormatTarget::Ranges(ranges),
13987            window,
13988            cx,
13989        ))
13990    }
13991
13992    fn perform_format(
13993        &mut self,
13994        project: Entity<Project>,
13995        trigger: FormatTrigger,
13996        target: FormatTarget,
13997        window: &mut Window,
13998        cx: &mut Context<Self>,
13999    ) -> Task<Result<()>> {
14000        let buffer = self.buffer.clone();
14001        let (buffers, target) = match target {
14002            FormatTarget::Buffers => {
14003                let mut buffers = buffer.read(cx).all_buffers();
14004                if trigger == FormatTrigger::Save {
14005                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
14006                }
14007                (buffers, LspFormatTarget::Buffers)
14008            }
14009            FormatTarget::Ranges(selection_ranges) => {
14010                let multi_buffer = buffer.read(cx);
14011                let snapshot = multi_buffer.read(cx);
14012                let mut buffers = HashSet::default();
14013                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14014                    BTreeMap::new();
14015                for selection_range in selection_ranges {
14016                    for (buffer, buffer_range, _) in
14017                        snapshot.range_to_buffer_ranges(selection_range)
14018                    {
14019                        let buffer_id = buffer.remote_id();
14020                        let start = buffer.anchor_before(buffer_range.start);
14021                        let end = buffer.anchor_after(buffer_range.end);
14022                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14023                        buffer_id_to_ranges
14024                            .entry(buffer_id)
14025                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14026                            .or_insert_with(|| vec![start..end]);
14027                    }
14028                }
14029                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14030            }
14031        };
14032
14033        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14034        let format = project.update(cx, |project, cx| {
14035            project.format(buffers, target, true, trigger, cx)
14036        });
14037
14038        cx.spawn_in(window, async move |_, cx| {
14039            let transaction = futures::select_biased! {
14040                transaction = format.log_err().fuse() => transaction,
14041                () = timeout => {
14042                    log::warn!("timed out waiting for formatting");
14043                    None
14044                }
14045            };
14046
14047            buffer
14048                .update(cx, |buffer, cx| {
14049                    if let Some(transaction) = transaction {
14050                        if !buffer.is_singleton() {
14051                            buffer.push_transaction(&transaction.0, cx);
14052                        }
14053                    }
14054                    cx.notify();
14055                })
14056                .ok();
14057
14058            Ok(())
14059        })
14060    }
14061
14062    fn organize_imports(
14063        &mut self,
14064        _: &OrganizeImports,
14065        window: &mut Window,
14066        cx: &mut Context<Self>,
14067    ) -> Option<Task<Result<()>>> {
14068        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14069        let project = match &self.project {
14070            Some(project) => project.clone(),
14071            None => return None,
14072        };
14073        Some(self.perform_code_action_kind(
14074            project,
14075            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14076            window,
14077            cx,
14078        ))
14079    }
14080
14081    fn perform_code_action_kind(
14082        &mut self,
14083        project: Entity<Project>,
14084        kind: CodeActionKind,
14085        window: &mut Window,
14086        cx: &mut Context<Self>,
14087    ) -> Task<Result<()>> {
14088        let buffer = self.buffer.clone();
14089        let buffers = buffer.read(cx).all_buffers();
14090        let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14091        let apply_action = project.update(cx, |project, cx| {
14092            project.apply_code_action_kind(buffers, kind, true, cx)
14093        });
14094        cx.spawn_in(window, async move |_, cx| {
14095            let transaction = futures::select_biased! {
14096                () = timeout => {
14097                    log::warn!("timed out waiting for executing code action");
14098                    None
14099                }
14100                transaction = apply_action.log_err().fuse() => transaction,
14101            };
14102            buffer
14103                .update(cx, |buffer, cx| {
14104                    // check if we need this
14105                    if let Some(transaction) = transaction {
14106                        if !buffer.is_singleton() {
14107                            buffer.push_transaction(&transaction.0, cx);
14108                        }
14109                    }
14110                    cx.notify();
14111                })
14112                .ok();
14113            Ok(())
14114        })
14115    }
14116
14117    fn restart_language_server(
14118        &mut self,
14119        _: &RestartLanguageServer,
14120        _: &mut Window,
14121        cx: &mut Context<Self>,
14122    ) {
14123        if let Some(project) = self.project.clone() {
14124            self.buffer.update(cx, |multi_buffer, cx| {
14125                project.update(cx, |project, cx| {
14126                    project.restart_language_servers_for_buffers(
14127                        multi_buffer.all_buffers().into_iter().collect(),
14128                        cx,
14129                    );
14130                });
14131            })
14132        }
14133    }
14134
14135    fn stop_language_server(
14136        &mut self,
14137        _: &StopLanguageServer,
14138        _: &mut Window,
14139        cx: &mut Context<Self>,
14140    ) {
14141        if let Some(project) = self.project.clone() {
14142            self.buffer.update(cx, |multi_buffer, cx| {
14143                project.update(cx, |project, cx| {
14144                    project.stop_language_servers_for_buffers(
14145                        multi_buffer.all_buffers().into_iter().collect(),
14146                        cx,
14147                    );
14148                    cx.emit(project::Event::RefreshInlayHints);
14149                });
14150            });
14151        }
14152    }
14153
14154    fn cancel_language_server_work(
14155        workspace: &mut Workspace,
14156        _: &actions::CancelLanguageServerWork,
14157        _: &mut Window,
14158        cx: &mut Context<Workspace>,
14159    ) {
14160        let project = workspace.project();
14161        let buffers = workspace
14162            .active_item(cx)
14163            .and_then(|item| item.act_as::<Editor>(cx))
14164            .map_or(HashSet::default(), |editor| {
14165                editor.read(cx).buffer.read(cx).all_buffers()
14166            });
14167        project.update(cx, |project, cx| {
14168            project.cancel_language_server_work_for_buffers(buffers, cx);
14169        });
14170    }
14171
14172    fn show_character_palette(
14173        &mut self,
14174        _: &ShowCharacterPalette,
14175        window: &mut Window,
14176        _: &mut Context<Self>,
14177    ) {
14178        window.show_character_palette();
14179    }
14180
14181    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14182        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14183            let buffer = self.buffer.read(cx).snapshot(cx);
14184            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14185            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14186            let is_valid = buffer
14187                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14188                .any(|entry| {
14189                    entry.diagnostic.is_primary
14190                        && !entry.range.is_empty()
14191                        && entry.range.start == primary_range_start
14192                        && entry.diagnostic.message == active_diagnostics.primary_message
14193                });
14194
14195            if is_valid != active_diagnostics.is_valid {
14196                active_diagnostics.is_valid = is_valid;
14197                if is_valid {
14198                    let mut new_styles = HashMap::default();
14199                    for (block_id, diagnostic) in &active_diagnostics.blocks {
14200                        new_styles.insert(
14201                            *block_id,
14202                            diagnostic_block_renderer(diagnostic.clone(), None, true),
14203                        );
14204                    }
14205                    self.display_map.update(cx, |display_map, _cx| {
14206                        display_map.replace_blocks(new_styles);
14207                    });
14208                } else {
14209                    self.dismiss_diagnostics(cx);
14210                }
14211            }
14212        }
14213    }
14214
14215    fn activate_diagnostics(
14216        &mut self,
14217        buffer_id: BufferId,
14218        group_id: usize,
14219        window: &mut Window,
14220        cx: &mut Context<Self>,
14221    ) {
14222        self.dismiss_diagnostics(cx);
14223        let snapshot = self.snapshot(window, cx);
14224        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14225            let buffer = self.buffer.read(cx).snapshot(cx);
14226
14227            let mut primary_range = None;
14228            let mut primary_message = None;
14229            let diagnostic_group = buffer
14230                .diagnostic_group(buffer_id, group_id)
14231                .filter_map(|entry| {
14232                    let start = entry.range.start;
14233                    let end = entry.range.end;
14234                    if snapshot.is_line_folded(MultiBufferRow(start.row))
14235                        && (start.row == end.row
14236                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
14237                    {
14238                        return None;
14239                    }
14240                    if entry.diagnostic.is_primary {
14241                        primary_range = Some(entry.range.clone());
14242                        primary_message = Some(entry.diagnostic.message.clone());
14243                    }
14244                    Some(entry)
14245                })
14246                .collect::<Vec<_>>();
14247            let primary_range = primary_range?;
14248            let primary_message = primary_message?;
14249
14250            let blocks = display_map
14251                .insert_blocks(
14252                    diagnostic_group.iter().map(|entry| {
14253                        let diagnostic = entry.diagnostic.clone();
14254                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14255                        BlockProperties {
14256                            style: BlockStyle::Fixed,
14257                            placement: BlockPlacement::Below(
14258                                buffer.anchor_after(entry.range.start),
14259                            ),
14260                            height: Some(message_height),
14261                            render: diagnostic_block_renderer(diagnostic, None, true),
14262                            priority: 0,
14263                        }
14264                    }),
14265                    cx,
14266                )
14267                .into_iter()
14268                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14269                .collect();
14270
14271            Some(ActiveDiagnosticGroup {
14272                primary_range: buffer.anchor_before(primary_range.start)
14273                    ..buffer.anchor_after(primary_range.end),
14274                primary_message,
14275                group_id,
14276                blocks,
14277                is_valid: true,
14278            })
14279        });
14280    }
14281
14282    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14283        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14284            self.display_map.update(cx, |display_map, cx| {
14285                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14286            });
14287            cx.notify();
14288        }
14289    }
14290
14291    /// Disable inline diagnostics rendering for this editor.
14292    pub fn disable_inline_diagnostics(&mut self) {
14293        self.inline_diagnostics_enabled = false;
14294        self.inline_diagnostics_update = Task::ready(());
14295        self.inline_diagnostics.clear();
14296    }
14297
14298    pub fn inline_diagnostics_enabled(&self) -> bool {
14299        self.inline_diagnostics_enabled
14300    }
14301
14302    pub fn show_inline_diagnostics(&self) -> bool {
14303        self.show_inline_diagnostics
14304    }
14305
14306    pub fn toggle_inline_diagnostics(
14307        &mut self,
14308        _: &ToggleInlineDiagnostics,
14309        window: &mut Window,
14310        cx: &mut Context<Editor>,
14311    ) {
14312        self.show_inline_diagnostics = !self.show_inline_diagnostics;
14313        self.refresh_inline_diagnostics(false, window, cx);
14314    }
14315
14316    fn refresh_inline_diagnostics(
14317        &mut self,
14318        debounce: bool,
14319        window: &mut Window,
14320        cx: &mut Context<Self>,
14321    ) {
14322        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14323            self.inline_diagnostics_update = Task::ready(());
14324            self.inline_diagnostics.clear();
14325            return;
14326        }
14327
14328        let debounce_ms = ProjectSettings::get_global(cx)
14329            .diagnostics
14330            .inline
14331            .update_debounce_ms;
14332        let debounce = if debounce && debounce_ms > 0 {
14333            Some(Duration::from_millis(debounce_ms))
14334        } else {
14335            None
14336        };
14337        self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14338            if let Some(debounce) = debounce {
14339                cx.background_executor().timer(debounce).await;
14340            }
14341            let Some(snapshot) = editor
14342                .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14343                .ok()
14344            else {
14345                return;
14346            };
14347
14348            let new_inline_diagnostics = cx
14349                .background_spawn(async move {
14350                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14351                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14352                        let message = diagnostic_entry
14353                            .diagnostic
14354                            .message
14355                            .split_once('\n')
14356                            .map(|(line, _)| line)
14357                            .map(SharedString::new)
14358                            .unwrap_or_else(|| {
14359                                SharedString::from(diagnostic_entry.diagnostic.message)
14360                            });
14361                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14362                        let (Ok(i) | Err(i)) = inline_diagnostics
14363                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14364                        inline_diagnostics.insert(
14365                            i,
14366                            (
14367                                start_anchor,
14368                                InlineDiagnostic {
14369                                    message,
14370                                    group_id: diagnostic_entry.diagnostic.group_id,
14371                                    start: diagnostic_entry.range.start.to_point(&snapshot),
14372                                    is_primary: diagnostic_entry.diagnostic.is_primary,
14373                                    severity: diagnostic_entry.diagnostic.severity,
14374                                },
14375                            ),
14376                        );
14377                    }
14378                    inline_diagnostics
14379                })
14380                .await;
14381
14382            editor
14383                .update(cx, |editor, cx| {
14384                    editor.inline_diagnostics = new_inline_diagnostics;
14385                    cx.notify();
14386                })
14387                .ok();
14388        });
14389    }
14390
14391    pub fn set_selections_from_remote(
14392        &mut self,
14393        selections: Vec<Selection<Anchor>>,
14394        pending_selection: Option<Selection<Anchor>>,
14395        window: &mut Window,
14396        cx: &mut Context<Self>,
14397    ) {
14398        let old_cursor_position = self.selections.newest_anchor().head();
14399        self.selections.change_with(cx, |s| {
14400            s.select_anchors(selections);
14401            if let Some(pending_selection) = pending_selection {
14402                s.set_pending(pending_selection, SelectMode::Character);
14403            } else {
14404                s.clear_pending();
14405            }
14406        });
14407        self.selections_did_change(false, &old_cursor_position, true, window, cx);
14408    }
14409
14410    fn push_to_selection_history(&mut self) {
14411        self.selection_history.push(SelectionHistoryEntry {
14412            selections: self.selections.disjoint_anchors(),
14413            select_next_state: self.select_next_state.clone(),
14414            select_prev_state: self.select_prev_state.clone(),
14415            add_selections_state: self.add_selections_state.clone(),
14416        });
14417    }
14418
14419    pub fn transact(
14420        &mut self,
14421        window: &mut Window,
14422        cx: &mut Context<Self>,
14423        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14424    ) -> Option<TransactionId> {
14425        self.start_transaction_at(Instant::now(), window, cx);
14426        update(self, window, cx);
14427        self.end_transaction_at(Instant::now(), cx)
14428    }
14429
14430    pub fn start_transaction_at(
14431        &mut self,
14432        now: Instant,
14433        window: &mut Window,
14434        cx: &mut Context<Self>,
14435    ) {
14436        self.end_selection(window, cx);
14437        if let Some(tx_id) = self
14438            .buffer
14439            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14440        {
14441            self.selection_history
14442                .insert_transaction(tx_id, self.selections.disjoint_anchors());
14443            cx.emit(EditorEvent::TransactionBegun {
14444                transaction_id: tx_id,
14445            })
14446        }
14447    }
14448
14449    pub fn end_transaction_at(
14450        &mut self,
14451        now: Instant,
14452        cx: &mut Context<Self>,
14453    ) -> Option<TransactionId> {
14454        if let Some(transaction_id) = self
14455            .buffer
14456            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14457        {
14458            if let Some((_, end_selections)) =
14459                self.selection_history.transaction_mut(transaction_id)
14460            {
14461                *end_selections = Some(self.selections.disjoint_anchors());
14462            } else {
14463                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14464            }
14465
14466            cx.emit(EditorEvent::Edited { transaction_id });
14467            Some(transaction_id)
14468        } else {
14469            None
14470        }
14471    }
14472
14473    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14474        if self.selection_mark_mode {
14475            self.change_selections(None, window, cx, |s| {
14476                s.move_with(|_, sel| {
14477                    sel.collapse_to(sel.head(), SelectionGoal::None);
14478                });
14479            })
14480        }
14481        self.selection_mark_mode = true;
14482        cx.notify();
14483    }
14484
14485    pub fn swap_selection_ends(
14486        &mut self,
14487        _: &actions::SwapSelectionEnds,
14488        window: &mut Window,
14489        cx: &mut Context<Self>,
14490    ) {
14491        self.change_selections(None, window, cx, |s| {
14492            s.move_with(|_, sel| {
14493                if sel.start != sel.end {
14494                    sel.reversed = !sel.reversed
14495                }
14496            });
14497        });
14498        self.request_autoscroll(Autoscroll::newest(), cx);
14499        cx.notify();
14500    }
14501
14502    pub fn toggle_fold(
14503        &mut self,
14504        _: &actions::ToggleFold,
14505        window: &mut Window,
14506        cx: &mut Context<Self>,
14507    ) {
14508        if self.is_singleton(cx) {
14509            let selection = self.selections.newest::<Point>(cx);
14510
14511            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14512            let range = if selection.is_empty() {
14513                let point = selection.head().to_display_point(&display_map);
14514                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14515                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14516                    .to_point(&display_map);
14517                start..end
14518            } else {
14519                selection.range()
14520            };
14521            if display_map.folds_in_range(range).next().is_some() {
14522                self.unfold_lines(&Default::default(), window, cx)
14523            } else {
14524                self.fold(&Default::default(), window, cx)
14525            }
14526        } else {
14527            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14528            let buffer_ids: HashSet<_> = self
14529                .selections
14530                .disjoint_anchor_ranges()
14531                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14532                .collect();
14533
14534            let should_unfold = buffer_ids
14535                .iter()
14536                .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14537
14538            for buffer_id in buffer_ids {
14539                if should_unfold {
14540                    self.unfold_buffer(buffer_id, cx);
14541                } else {
14542                    self.fold_buffer(buffer_id, cx);
14543                }
14544            }
14545        }
14546    }
14547
14548    pub fn toggle_fold_recursive(
14549        &mut self,
14550        _: &actions::ToggleFoldRecursive,
14551        window: &mut Window,
14552        cx: &mut Context<Self>,
14553    ) {
14554        let selection = self.selections.newest::<Point>(cx);
14555
14556        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14557        let range = if selection.is_empty() {
14558            let point = selection.head().to_display_point(&display_map);
14559            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14560            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14561                .to_point(&display_map);
14562            start..end
14563        } else {
14564            selection.range()
14565        };
14566        if display_map.folds_in_range(range).next().is_some() {
14567            self.unfold_recursive(&Default::default(), window, cx)
14568        } else {
14569            self.fold_recursive(&Default::default(), window, cx)
14570        }
14571    }
14572
14573    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14574        if self.is_singleton(cx) {
14575            let mut to_fold = Vec::new();
14576            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14577            let selections = self.selections.all_adjusted(cx);
14578
14579            for selection in selections {
14580                let range = selection.range().sorted();
14581                let buffer_start_row = range.start.row;
14582
14583                if range.start.row != range.end.row {
14584                    let mut found = false;
14585                    let mut row = range.start.row;
14586                    while row <= range.end.row {
14587                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14588                        {
14589                            found = true;
14590                            row = crease.range().end.row + 1;
14591                            to_fold.push(crease);
14592                        } else {
14593                            row += 1
14594                        }
14595                    }
14596                    if found {
14597                        continue;
14598                    }
14599                }
14600
14601                for row in (0..=range.start.row).rev() {
14602                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14603                        if crease.range().end.row >= buffer_start_row {
14604                            to_fold.push(crease);
14605                            if row <= range.start.row {
14606                                break;
14607                            }
14608                        }
14609                    }
14610                }
14611            }
14612
14613            self.fold_creases(to_fold, true, window, cx);
14614        } else {
14615            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14616            let buffer_ids = self
14617                .selections
14618                .disjoint_anchor_ranges()
14619                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14620                .collect::<HashSet<_>>();
14621            for buffer_id in buffer_ids {
14622                self.fold_buffer(buffer_id, cx);
14623            }
14624        }
14625    }
14626
14627    fn fold_at_level(
14628        &mut self,
14629        fold_at: &FoldAtLevel,
14630        window: &mut Window,
14631        cx: &mut Context<Self>,
14632    ) {
14633        if !self.buffer.read(cx).is_singleton() {
14634            return;
14635        }
14636
14637        let fold_at_level = fold_at.0;
14638        let snapshot = self.buffer.read(cx).snapshot(cx);
14639        let mut to_fold = Vec::new();
14640        let mut stack = vec![(0, snapshot.max_row().0, 1)];
14641
14642        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14643            while start_row < end_row {
14644                match self
14645                    .snapshot(window, cx)
14646                    .crease_for_buffer_row(MultiBufferRow(start_row))
14647                {
14648                    Some(crease) => {
14649                        let nested_start_row = crease.range().start.row + 1;
14650                        let nested_end_row = crease.range().end.row;
14651
14652                        if current_level < fold_at_level {
14653                            stack.push((nested_start_row, nested_end_row, current_level + 1));
14654                        } else if current_level == fold_at_level {
14655                            to_fold.push(crease);
14656                        }
14657
14658                        start_row = nested_end_row + 1;
14659                    }
14660                    None => start_row += 1,
14661                }
14662            }
14663        }
14664
14665        self.fold_creases(to_fold, true, window, cx);
14666    }
14667
14668    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14669        if self.buffer.read(cx).is_singleton() {
14670            let mut fold_ranges = Vec::new();
14671            let snapshot = self.buffer.read(cx).snapshot(cx);
14672
14673            for row in 0..snapshot.max_row().0 {
14674                if let Some(foldable_range) = self
14675                    .snapshot(window, cx)
14676                    .crease_for_buffer_row(MultiBufferRow(row))
14677                {
14678                    fold_ranges.push(foldable_range);
14679                }
14680            }
14681
14682            self.fold_creases(fold_ranges, true, window, cx);
14683        } else {
14684            self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14685                editor
14686                    .update_in(cx, |editor, _, cx| {
14687                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14688                            editor.fold_buffer(buffer_id, cx);
14689                        }
14690                    })
14691                    .ok();
14692            });
14693        }
14694    }
14695
14696    pub fn fold_function_bodies(
14697        &mut self,
14698        _: &actions::FoldFunctionBodies,
14699        window: &mut Window,
14700        cx: &mut Context<Self>,
14701    ) {
14702        let snapshot = self.buffer.read(cx).snapshot(cx);
14703
14704        let ranges = snapshot
14705            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14706            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14707            .collect::<Vec<_>>();
14708
14709        let creases = ranges
14710            .into_iter()
14711            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14712            .collect();
14713
14714        self.fold_creases(creases, true, window, cx);
14715    }
14716
14717    pub fn fold_recursive(
14718        &mut self,
14719        _: &actions::FoldRecursive,
14720        window: &mut Window,
14721        cx: &mut Context<Self>,
14722    ) {
14723        let mut to_fold = Vec::new();
14724        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14725        let selections = self.selections.all_adjusted(cx);
14726
14727        for selection in selections {
14728            let range = selection.range().sorted();
14729            let buffer_start_row = range.start.row;
14730
14731            if range.start.row != range.end.row {
14732                let mut found = false;
14733                for row in range.start.row..=range.end.row {
14734                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14735                        found = true;
14736                        to_fold.push(crease);
14737                    }
14738                }
14739                if found {
14740                    continue;
14741                }
14742            }
14743
14744            for row in (0..=range.start.row).rev() {
14745                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14746                    if crease.range().end.row >= buffer_start_row {
14747                        to_fold.push(crease);
14748                    } else {
14749                        break;
14750                    }
14751                }
14752            }
14753        }
14754
14755        self.fold_creases(to_fold, true, window, cx);
14756    }
14757
14758    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14759        let buffer_row = fold_at.buffer_row;
14760        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14761
14762        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14763            let autoscroll = self
14764                .selections
14765                .all::<Point>(cx)
14766                .iter()
14767                .any(|selection| crease.range().overlaps(&selection.range()));
14768
14769            self.fold_creases(vec![crease], autoscroll, window, cx);
14770        }
14771    }
14772
14773    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14774        if self.is_singleton(cx) {
14775            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14776            let buffer = &display_map.buffer_snapshot;
14777            let selections = self.selections.all::<Point>(cx);
14778            let ranges = selections
14779                .iter()
14780                .map(|s| {
14781                    let range = s.display_range(&display_map).sorted();
14782                    let mut start = range.start.to_point(&display_map);
14783                    let mut end = range.end.to_point(&display_map);
14784                    start.column = 0;
14785                    end.column = buffer.line_len(MultiBufferRow(end.row));
14786                    start..end
14787                })
14788                .collect::<Vec<_>>();
14789
14790            self.unfold_ranges(&ranges, true, true, cx);
14791        } else {
14792            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14793            let buffer_ids = self
14794                .selections
14795                .disjoint_anchor_ranges()
14796                .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14797                .collect::<HashSet<_>>();
14798            for buffer_id in buffer_ids {
14799                self.unfold_buffer(buffer_id, cx);
14800            }
14801        }
14802    }
14803
14804    pub fn unfold_recursive(
14805        &mut self,
14806        _: &UnfoldRecursive,
14807        _window: &mut Window,
14808        cx: &mut Context<Self>,
14809    ) {
14810        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14811        let selections = self.selections.all::<Point>(cx);
14812        let ranges = selections
14813            .iter()
14814            .map(|s| {
14815                let mut range = s.display_range(&display_map).sorted();
14816                *range.start.column_mut() = 0;
14817                *range.end.column_mut() = display_map.line_len(range.end.row());
14818                let start = range.start.to_point(&display_map);
14819                let end = range.end.to_point(&display_map);
14820                start..end
14821            })
14822            .collect::<Vec<_>>();
14823
14824        self.unfold_ranges(&ranges, true, true, cx);
14825    }
14826
14827    pub fn unfold_at(
14828        &mut self,
14829        unfold_at: &UnfoldAt,
14830        _window: &mut Window,
14831        cx: &mut Context<Self>,
14832    ) {
14833        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14834
14835        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14836            ..Point::new(
14837                unfold_at.buffer_row.0,
14838                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14839            );
14840
14841        let autoscroll = self
14842            .selections
14843            .all::<Point>(cx)
14844            .iter()
14845            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14846
14847        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14848    }
14849
14850    pub fn unfold_all(
14851        &mut self,
14852        _: &actions::UnfoldAll,
14853        _window: &mut Window,
14854        cx: &mut Context<Self>,
14855    ) {
14856        if self.buffer.read(cx).is_singleton() {
14857            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14858            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14859        } else {
14860            self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14861                editor
14862                    .update(cx, |editor, cx| {
14863                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14864                            editor.unfold_buffer(buffer_id, cx);
14865                        }
14866                    })
14867                    .ok();
14868            });
14869        }
14870    }
14871
14872    pub fn fold_selected_ranges(
14873        &mut self,
14874        _: &FoldSelectedRanges,
14875        window: &mut Window,
14876        cx: &mut Context<Self>,
14877    ) {
14878        let selections = self.selections.all_adjusted(cx);
14879        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14880        let ranges = selections
14881            .into_iter()
14882            .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
14883            .collect::<Vec<_>>();
14884        self.fold_creases(ranges, true, window, cx);
14885    }
14886
14887    pub fn fold_ranges<T: ToOffset + Clone>(
14888        &mut self,
14889        ranges: Vec<Range<T>>,
14890        auto_scroll: bool,
14891        window: &mut Window,
14892        cx: &mut Context<Self>,
14893    ) {
14894        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14895        let ranges = ranges
14896            .into_iter()
14897            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14898            .collect::<Vec<_>>();
14899        self.fold_creases(ranges, auto_scroll, window, cx);
14900    }
14901
14902    pub fn fold_creases<T: ToOffset + Clone>(
14903        &mut self,
14904        creases: Vec<Crease<T>>,
14905        auto_scroll: bool,
14906        window: &mut Window,
14907        cx: &mut Context<Self>,
14908    ) {
14909        if creases.is_empty() {
14910            return;
14911        }
14912
14913        let mut buffers_affected = HashSet::default();
14914        let multi_buffer = self.buffer().read(cx);
14915        for crease in &creases {
14916            if let Some((_, buffer, _)) =
14917                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14918            {
14919                buffers_affected.insert(buffer.read(cx).remote_id());
14920            };
14921        }
14922
14923        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14924
14925        if auto_scroll {
14926            self.request_autoscroll(Autoscroll::fit(), cx);
14927        }
14928
14929        cx.notify();
14930
14931        if let Some(active_diagnostics) = self.active_diagnostics.take() {
14932            // Clear diagnostics block when folding a range that contains it.
14933            let snapshot = self.snapshot(window, cx);
14934            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14935                drop(snapshot);
14936                self.active_diagnostics = Some(active_diagnostics);
14937                self.dismiss_diagnostics(cx);
14938            } else {
14939                self.active_diagnostics = Some(active_diagnostics);
14940            }
14941        }
14942
14943        self.scrollbar_marker_state.dirty = true;
14944        self.folds_did_change(cx);
14945    }
14946
14947    /// Removes any folds whose ranges intersect any of the given ranges.
14948    pub fn unfold_ranges<T: ToOffset + Clone>(
14949        &mut self,
14950        ranges: &[Range<T>],
14951        inclusive: bool,
14952        auto_scroll: bool,
14953        cx: &mut Context<Self>,
14954    ) {
14955        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14956            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14957        });
14958        self.folds_did_change(cx);
14959    }
14960
14961    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14962        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14963            return;
14964        }
14965        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14966        self.display_map.update(cx, |display_map, cx| {
14967            display_map.fold_buffers([buffer_id], cx)
14968        });
14969        cx.emit(EditorEvent::BufferFoldToggled {
14970            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14971            folded: true,
14972        });
14973        cx.notify();
14974    }
14975
14976    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14977        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14978            return;
14979        }
14980        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14981        self.display_map.update(cx, |display_map, cx| {
14982            display_map.unfold_buffers([buffer_id], cx);
14983        });
14984        cx.emit(EditorEvent::BufferFoldToggled {
14985            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14986            folded: false,
14987        });
14988        cx.notify();
14989    }
14990
14991    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14992        self.display_map.read(cx).is_buffer_folded(buffer)
14993    }
14994
14995    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14996        self.display_map.read(cx).folded_buffers()
14997    }
14998
14999    pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15000        self.display_map.update(cx, |display_map, cx| {
15001            display_map.disable_header_for_buffer(buffer_id, cx);
15002        });
15003        cx.notify();
15004    }
15005
15006    /// Removes any folds with the given ranges.
15007    pub fn remove_folds_with_type<T: ToOffset + Clone>(
15008        &mut self,
15009        ranges: &[Range<T>],
15010        type_id: TypeId,
15011        auto_scroll: bool,
15012        cx: &mut Context<Self>,
15013    ) {
15014        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15015            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15016        });
15017        self.folds_did_change(cx);
15018    }
15019
15020    fn remove_folds_with<T: ToOffset + Clone>(
15021        &mut self,
15022        ranges: &[Range<T>],
15023        auto_scroll: bool,
15024        cx: &mut Context<Self>,
15025        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15026    ) {
15027        if ranges.is_empty() {
15028            return;
15029        }
15030
15031        let mut buffers_affected = HashSet::default();
15032        let multi_buffer = self.buffer().read(cx);
15033        for range in ranges {
15034            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15035                buffers_affected.insert(buffer.read(cx).remote_id());
15036            };
15037        }
15038
15039        self.display_map.update(cx, update);
15040
15041        if auto_scroll {
15042            self.request_autoscroll(Autoscroll::fit(), cx);
15043        }
15044
15045        cx.notify();
15046        self.scrollbar_marker_state.dirty = true;
15047        self.active_indent_guides_state.dirty = true;
15048    }
15049
15050    pub fn update_fold_widths(
15051        &mut self,
15052        widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15053        cx: &mut Context<Self>,
15054    ) -> bool {
15055        self.display_map
15056            .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15057    }
15058
15059    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15060        self.display_map.read(cx).fold_placeholder.clone()
15061    }
15062
15063    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15064        self.buffer.update(cx, |buffer, cx| {
15065            buffer.set_all_diff_hunks_expanded(cx);
15066        });
15067    }
15068
15069    pub fn expand_all_diff_hunks(
15070        &mut self,
15071        _: &ExpandAllDiffHunks,
15072        _window: &mut Window,
15073        cx: &mut Context<Self>,
15074    ) {
15075        self.buffer.update(cx, |buffer, cx| {
15076            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15077        });
15078    }
15079
15080    pub fn toggle_selected_diff_hunks(
15081        &mut self,
15082        _: &ToggleSelectedDiffHunks,
15083        _window: &mut Window,
15084        cx: &mut Context<Self>,
15085    ) {
15086        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15087        self.toggle_diff_hunks_in_ranges(ranges, cx);
15088    }
15089
15090    pub fn diff_hunks_in_ranges<'a>(
15091        &'a self,
15092        ranges: &'a [Range<Anchor>],
15093        buffer: &'a MultiBufferSnapshot,
15094    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15095        ranges.iter().flat_map(move |range| {
15096            let end_excerpt_id = range.end.excerpt_id;
15097            let range = range.to_point(buffer);
15098            let mut peek_end = range.end;
15099            if range.end.row < buffer.max_row().0 {
15100                peek_end = Point::new(range.end.row + 1, 0);
15101            }
15102            buffer
15103                .diff_hunks_in_range(range.start..peek_end)
15104                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15105        })
15106    }
15107
15108    pub fn has_stageable_diff_hunks_in_ranges(
15109        &self,
15110        ranges: &[Range<Anchor>],
15111        snapshot: &MultiBufferSnapshot,
15112    ) -> bool {
15113        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15114        hunks.any(|hunk| hunk.status().has_secondary_hunk())
15115    }
15116
15117    pub fn toggle_staged_selected_diff_hunks(
15118        &mut self,
15119        _: &::git::ToggleStaged,
15120        _: &mut Window,
15121        cx: &mut Context<Self>,
15122    ) {
15123        let snapshot = self.buffer.read(cx).snapshot(cx);
15124        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15125        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15126        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15127    }
15128
15129    pub fn set_render_diff_hunk_controls(
15130        &mut self,
15131        render_diff_hunk_controls: RenderDiffHunkControlsFn,
15132        cx: &mut Context<Self>,
15133    ) {
15134        self.render_diff_hunk_controls = render_diff_hunk_controls;
15135        cx.notify();
15136    }
15137
15138    pub fn stage_and_next(
15139        &mut self,
15140        _: &::git::StageAndNext,
15141        window: &mut Window,
15142        cx: &mut Context<Self>,
15143    ) {
15144        self.do_stage_or_unstage_and_next(true, window, cx);
15145    }
15146
15147    pub fn unstage_and_next(
15148        &mut self,
15149        _: &::git::UnstageAndNext,
15150        window: &mut Window,
15151        cx: &mut Context<Self>,
15152    ) {
15153        self.do_stage_or_unstage_and_next(false, window, cx);
15154    }
15155
15156    pub fn stage_or_unstage_diff_hunks(
15157        &mut self,
15158        stage: bool,
15159        ranges: Vec<Range<Anchor>>,
15160        cx: &mut Context<Self>,
15161    ) {
15162        let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15163        cx.spawn(async move |this, cx| {
15164            task.await?;
15165            this.update(cx, |this, cx| {
15166                let snapshot = this.buffer.read(cx).snapshot(cx);
15167                let chunk_by = this
15168                    .diff_hunks_in_ranges(&ranges, &snapshot)
15169                    .chunk_by(|hunk| hunk.buffer_id);
15170                for (buffer_id, hunks) in &chunk_by {
15171                    this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15172                }
15173            })
15174        })
15175        .detach_and_log_err(cx);
15176    }
15177
15178    fn save_buffers_for_ranges_if_needed(
15179        &mut self,
15180        ranges: &[Range<Anchor>],
15181        cx: &mut Context<Editor>,
15182    ) -> Task<Result<()>> {
15183        let multibuffer = self.buffer.read(cx);
15184        let snapshot = multibuffer.read(cx);
15185        let buffer_ids: HashSet<_> = ranges
15186            .iter()
15187            .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15188            .collect();
15189        drop(snapshot);
15190
15191        let mut buffers = HashSet::default();
15192        for buffer_id in buffer_ids {
15193            if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15194                let buffer = buffer_entity.read(cx);
15195                if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15196                {
15197                    buffers.insert(buffer_entity);
15198                }
15199            }
15200        }
15201
15202        if let Some(project) = &self.project {
15203            project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15204        } else {
15205            Task::ready(Ok(()))
15206        }
15207    }
15208
15209    fn do_stage_or_unstage_and_next(
15210        &mut self,
15211        stage: bool,
15212        window: &mut Window,
15213        cx: &mut Context<Self>,
15214    ) {
15215        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15216
15217        if ranges.iter().any(|range| range.start != range.end) {
15218            self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15219            return;
15220        }
15221
15222        self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15223        let snapshot = self.snapshot(window, cx);
15224        let position = self.selections.newest::<Point>(cx).head();
15225        let mut row = snapshot
15226            .buffer_snapshot
15227            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15228            .find(|hunk| hunk.row_range.start.0 > position.row)
15229            .map(|hunk| hunk.row_range.start);
15230
15231        let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15232        // Outside of the project diff editor, wrap around to the beginning.
15233        if !all_diff_hunks_expanded {
15234            row = row.or_else(|| {
15235                snapshot
15236                    .buffer_snapshot
15237                    .diff_hunks_in_range(Point::zero()..position)
15238                    .find(|hunk| hunk.row_range.end.0 < position.row)
15239                    .map(|hunk| hunk.row_range.start)
15240            });
15241        }
15242
15243        if let Some(row) = row {
15244            let destination = Point::new(row.0, 0);
15245            let autoscroll = Autoscroll::center();
15246
15247            self.unfold_ranges(&[destination..destination], false, false, cx);
15248            self.change_selections(Some(autoscroll), window, cx, |s| {
15249                s.select_ranges([destination..destination]);
15250            });
15251        }
15252    }
15253
15254    fn do_stage_or_unstage(
15255        &self,
15256        stage: bool,
15257        buffer_id: BufferId,
15258        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15259        cx: &mut App,
15260    ) -> Option<()> {
15261        let project = self.project.as_ref()?;
15262        let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15263        let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15264        let buffer_snapshot = buffer.read(cx).snapshot();
15265        let file_exists = buffer_snapshot
15266            .file()
15267            .is_some_and(|file| file.disk_state().exists());
15268        diff.update(cx, |diff, cx| {
15269            diff.stage_or_unstage_hunks(
15270                stage,
15271                &hunks
15272                    .map(|hunk| buffer_diff::DiffHunk {
15273                        buffer_range: hunk.buffer_range,
15274                        diff_base_byte_range: hunk.diff_base_byte_range,
15275                        secondary_status: hunk.secondary_status,
15276                        range: Point::zero()..Point::zero(), // unused
15277                    })
15278                    .collect::<Vec<_>>(),
15279                &buffer_snapshot,
15280                file_exists,
15281                cx,
15282            )
15283        });
15284        None
15285    }
15286
15287    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15288        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15289        self.buffer
15290            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15291    }
15292
15293    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15294        self.buffer.update(cx, |buffer, cx| {
15295            let ranges = vec![Anchor::min()..Anchor::max()];
15296            if !buffer.all_diff_hunks_expanded()
15297                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15298            {
15299                buffer.collapse_diff_hunks(ranges, cx);
15300                true
15301            } else {
15302                false
15303            }
15304        })
15305    }
15306
15307    fn toggle_diff_hunks_in_ranges(
15308        &mut self,
15309        ranges: Vec<Range<Anchor>>,
15310        cx: &mut Context<Editor>,
15311    ) {
15312        self.buffer.update(cx, |buffer, cx| {
15313            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15314            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15315        })
15316    }
15317
15318    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15319        self.buffer.update(cx, |buffer, cx| {
15320            let snapshot = buffer.snapshot(cx);
15321            let excerpt_id = range.end.excerpt_id;
15322            let point_range = range.to_point(&snapshot);
15323            let expand = !buffer.single_hunk_is_expanded(range, cx);
15324            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15325        })
15326    }
15327
15328    pub(crate) fn apply_all_diff_hunks(
15329        &mut self,
15330        _: &ApplyAllDiffHunks,
15331        window: &mut Window,
15332        cx: &mut Context<Self>,
15333    ) {
15334        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15335
15336        let buffers = self.buffer.read(cx).all_buffers();
15337        for branch_buffer in buffers {
15338            branch_buffer.update(cx, |branch_buffer, cx| {
15339                branch_buffer.merge_into_base(Vec::new(), cx);
15340            });
15341        }
15342
15343        if let Some(project) = self.project.clone() {
15344            self.save(true, project, window, cx).detach_and_log_err(cx);
15345        }
15346    }
15347
15348    pub(crate) fn apply_selected_diff_hunks(
15349        &mut self,
15350        _: &ApplyDiffHunk,
15351        window: &mut Window,
15352        cx: &mut Context<Self>,
15353    ) {
15354        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15355        let snapshot = self.snapshot(window, cx);
15356        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15357        let mut ranges_by_buffer = HashMap::default();
15358        self.transact(window, cx, |editor, _window, cx| {
15359            for hunk in hunks {
15360                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15361                    ranges_by_buffer
15362                        .entry(buffer.clone())
15363                        .or_insert_with(Vec::new)
15364                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15365                }
15366            }
15367
15368            for (buffer, ranges) in ranges_by_buffer {
15369                buffer.update(cx, |buffer, cx| {
15370                    buffer.merge_into_base(ranges, cx);
15371                });
15372            }
15373        });
15374
15375        if let Some(project) = self.project.clone() {
15376            self.save(true, project, window, cx).detach_and_log_err(cx);
15377        }
15378    }
15379
15380    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15381        if hovered != self.gutter_hovered {
15382            self.gutter_hovered = hovered;
15383            cx.notify();
15384        }
15385    }
15386
15387    pub fn insert_blocks(
15388        &mut self,
15389        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15390        autoscroll: Option<Autoscroll>,
15391        cx: &mut Context<Self>,
15392    ) -> Vec<CustomBlockId> {
15393        let blocks = self
15394            .display_map
15395            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15396        if let Some(autoscroll) = autoscroll {
15397            self.request_autoscroll(autoscroll, cx);
15398        }
15399        cx.notify();
15400        blocks
15401    }
15402
15403    pub fn resize_blocks(
15404        &mut self,
15405        heights: HashMap<CustomBlockId, u32>,
15406        autoscroll: Option<Autoscroll>,
15407        cx: &mut Context<Self>,
15408    ) {
15409        self.display_map
15410            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15411        if let Some(autoscroll) = autoscroll {
15412            self.request_autoscroll(autoscroll, cx);
15413        }
15414        cx.notify();
15415    }
15416
15417    pub fn replace_blocks(
15418        &mut self,
15419        renderers: HashMap<CustomBlockId, RenderBlock>,
15420        autoscroll: Option<Autoscroll>,
15421        cx: &mut Context<Self>,
15422    ) {
15423        self.display_map
15424            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15425        if let Some(autoscroll) = autoscroll {
15426            self.request_autoscroll(autoscroll, cx);
15427        }
15428        cx.notify();
15429    }
15430
15431    pub fn remove_blocks(
15432        &mut self,
15433        block_ids: HashSet<CustomBlockId>,
15434        autoscroll: Option<Autoscroll>,
15435        cx: &mut Context<Self>,
15436    ) {
15437        self.display_map.update(cx, |display_map, cx| {
15438            display_map.remove_blocks(block_ids, cx)
15439        });
15440        if let Some(autoscroll) = autoscroll {
15441            self.request_autoscroll(autoscroll, cx);
15442        }
15443        cx.notify();
15444    }
15445
15446    pub fn row_for_block(
15447        &self,
15448        block_id: CustomBlockId,
15449        cx: &mut Context<Self>,
15450    ) -> Option<DisplayRow> {
15451        self.display_map
15452            .update(cx, |map, cx| map.row_for_block(block_id, cx))
15453    }
15454
15455    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15456        self.focused_block = Some(focused_block);
15457    }
15458
15459    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15460        self.focused_block.take()
15461    }
15462
15463    pub fn insert_creases(
15464        &mut self,
15465        creases: impl IntoIterator<Item = Crease<Anchor>>,
15466        cx: &mut Context<Self>,
15467    ) -> Vec<CreaseId> {
15468        self.display_map
15469            .update(cx, |map, cx| map.insert_creases(creases, cx))
15470    }
15471
15472    pub fn remove_creases(
15473        &mut self,
15474        ids: impl IntoIterator<Item = CreaseId>,
15475        cx: &mut Context<Self>,
15476    ) {
15477        self.display_map
15478            .update(cx, |map, cx| map.remove_creases(ids, cx));
15479    }
15480
15481    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15482        self.display_map
15483            .update(cx, |map, cx| map.snapshot(cx))
15484            .longest_row()
15485    }
15486
15487    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15488        self.display_map
15489            .update(cx, |map, cx| map.snapshot(cx))
15490            .max_point()
15491    }
15492
15493    pub fn text(&self, cx: &App) -> String {
15494        self.buffer.read(cx).read(cx).text()
15495    }
15496
15497    pub fn is_empty(&self, cx: &App) -> bool {
15498        self.buffer.read(cx).read(cx).is_empty()
15499    }
15500
15501    pub fn text_option(&self, cx: &App) -> Option<String> {
15502        let text = self.text(cx);
15503        let text = text.trim();
15504
15505        if text.is_empty() {
15506            return None;
15507        }
15508
15509        Some(text.to_string())
15510    }
15511
15512    pub fn set_text(
15513        &mut self,
15514        text: impl Into<Arc<str>>,
15515        window: &mut Window,
15516        cx: &mut Context<Self>,
15517    ) {
15518        self.transact(window, cx, |this, _, cx| {
15519            this.buffer
15520                .read(cx)
15521                .as_singleton()
15522                .expect("you can only call set_text on editors for singleton buffers")
15523                .update(cx, |buffer, cx| buffer.set_text(text, cx));
15524        });
15525    }
15526
15527    pub fn display_text(&self, cx: &mut App) -> String {
15528        self.display_map
15529            .update(cx, |map, cx| map.snapshot(cx))
15530            .text()
15531    }
15532
15533    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15534        let mut wrap_guides = smallvec::smallvec![];
15535
15536        if self.show_wrap_guides == Some(false) {
15537            return wrap_guides;
15538        }
15539
15540        let settings = self.buffer.read(cx).language_settings(cx);
15541        if settings.show_wrap_guides {
15542            match self.soft_wrap_mode(cx) {
15543                SoftWrap::Column(soft_wrap) => {
15544                    wrap_guides.push((soft_wrap as usize, true));
15545                }
15546                SoftWrap::Bounded(soft_wrap) => {
15547                    wrap_guides.push((soft_wrap as usize, true));
15548                }
15549                SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15550            }
15551            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15552        }
15553
15554        wrap_guides
15555    }
15556
15557    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15558        let settings = self.buffer.read(cx).language_settings(cx);
15559        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15560        match mode {
15561            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15562                SoftWrap::None
15563            }
15564            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15565            language_settings::SoftWrap::PreferredLineLength => {
15566                SoftWrap::Column(settings.preferred_line_length)
15567            }
15568            language_settings::SoftWrap::Bounded => {
15569                SoftWrap::Bounded(settings.preferred_line_length)
15570            }
15571        }
15572    }
15573
15574    pub fn set_soft_wrap_mode(
15575        &mut self,
15576        mode: language_settings::SoftWrap,
15577
15578        cx: &mut Context<Self>,
15579    ) {
15580        self.soft_wrap_mode_override = Some(mode);
15581        cx.notify();
15582    }
15583
15584    pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15585        self.hard_wrap = hard_wrap;
15586        cx.notify();
15587    }
15588
15589    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15590        self.text_style_refinement = Some(style);
15591    }
15592
15593    /// called by the Element so we know what style we were most recently rendered with.
15594    pub(crate) fn set_style(
15595        &mut self,
15596        style: EditorStyle,
15597        window: &mut Window,
15598        cx: &mut Context<Self>,
15599    ) {
15600        let rem_size = window.rem_size();
15601        self.display_map.update(cx, |map, cx| {
15602            map.set_font(
15603                style.text.font(),
15604                style.text.font_size.to_pixels(rem_size),
15605                cx,
15606            )
15607        });
15608        self.style = Some(style);
15609    }
15610
15611    pub fn style(&self) -> Option<&EditorStyle> {
15612        self.style.as_ref()
15613    }
15614
15615    // Called by the element. This method is not designed to be called outside of the editor
15616    // element's layout code because it does not notify when rewrapping is computed synchronously.
15617    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15618        self.display_map
15619            .update(cx, |map, cx| map.set_wrap_width(width, cx))
15620    }
15621
15622    pub fn set_soft_wrap(&mut self) {
15623        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15624    }
15625
15626    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15627        if self.soft_wrap_mode_override.is_some() {
15628            self.soft_wrap_mode_override.take();
15629        } else {
15630            let soft_wrap = match self.soft_wrap_mode(cx) {
15631                SoftWrap::GitDiff => return,
15632                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15633                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15634                    language_settings::SoftWrap::None
15635                }
15636            };
15637            self.soft_wrap_mode_override = Some(soft_wrap);
15638        }
15639        cx.notify();
15640    }
15641
15642    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15643        let Some(workspace) = self.workspace() else {
15644            return;
15645        };
15646        let fs = workspace.read(cx).app_state().fs.clone();
15647        let current_show = TabBarSettings::get_global(cx).show;
15648        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15649            setting.show = Some(!current_show);
15650        });
15651    }
15652
15653    pub fn toggle_indent_guides(
15654        &mut self,
15655        _: &ToggleIndentGuides,
15656        _: &mut Window,
15657        cx: &mut Context<Self>,
15658    ) {
15659        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15660            self.buffer
15661                .read(cx)
15662                .language_settings(cx)
15663                .indent_guides
15664                .enabled
15665        });
15666        self.show_indent_guides = Some(!currently_enabled);
15667        cx.notify();
15668    }
15669
15670    fn should_show_indent_guides(&self) -> Option<bool> {
15671        self.show_indent_guides
15672    }
15673
15674    pub fn toggle_line_numbers(
15675        &mut self,
15676        _: &ToggleLineNumbers,
15677        _: &mut Window,
15678        cx: &mut Context<Self>,
15679    ) {
15680        let mut editor_settings = EditorSettings::get_global(cx).clone();
15681        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15682        EditorSettings::override_global(editor_settings, cx);
15683    }
15684
15685    pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15686        if let Some(show_line_numbers) = self.show_line_numbers {
15687            return show_line_numbers;
15688        }
15689        EditorSettings::get_global(cx).gutter.line_numbers
15690    }
15691
15692    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15693        self.use_relative_line_numbers
15694            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15695    }
15696
15697    pub fn toggle_relative_line_numbers(
15698        &mut self,
15699        _: &ToggleRelativeLineNumbers,
15700        _: &mut Window,
15701        cx: &mut Context<Self>,
15702    ) {
15703        let is_relative = self.should_use_relative_line_numbers(cx);
15704        self.set_relative_line_number(Some(!is_relative), cx)
15705    }
15706
15707    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15708        self.use_relative_line_numbers = is_relative;
15709        cx.notify();
15710    }
15711
15712    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15713        self.show_gutter = show_gutter;
15714        cx.notify();
15715    }
15716
15717    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15718        self.show_scrollbars = show_scrollbars;
15719        cx.notify();
15720    }
15721
15722    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15723        self.show_line_numbers = Some(show_line_numbers);
15724        cx.notify();
15725    }
15726
15727    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15728        self.show_git_diff_gutter = Some(show_git_diff_gutter);
15729        cx.notify();
15730    }
15731
15732    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15733        self.show_code_actions = Some(show_code_actions);
15734        cx.notify();
15735    }
15736
15737    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15738        self.show_runnables = Some(show_runnables);
15739        cx.notify();
15740    }
15741
15742    pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15743        self.show_breakpoints = Some(show_breakpoints);
15744        cx.notify();
15745    }
15746
15747    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15748        if self.display_map.read(cx).masked != masked {
15749            self.display_map.update(cx, |map, _| map.masked = masked);
15750        }
15751        cx.notify()
15752    }
15753
15754    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15755        self.show_wrap_guides = Some(show_wrap_guides);
15756        cx.notify();
15757    }
15758
15759    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15760        self.show_indent_guides = Some(show_indent_guides);
15761        cx.notify();
15762    }
15763
15764    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15765        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15766            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15767                if let Some(dir) = file.abs_path(cx).parent() {
15768                    return Some(dir.to_owned());
15769                }
15770            }
15771
15772            if let Some(project_path) = buffer.read(cx).project_path(cx) {
15773                return Some(project_path.path.to_path_buf());
15774            }
15775        }
15776
15777        None
15778    }
15779
15780    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15781        self.active_excerpt(cx)?
15782            .1
15783            .read(cx)
15784            .file()
15785            .and_then(|f| f.as_local())
15786    }
15787
15788    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15789        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15790            let buffer = buffer.read(cx);
15791            if let Some(project_path) = buffer.project_path(cx) {
15792                let project = self.project.as_ref()?.read(cx);
15793                project.absolute_path(&project_path, cx)
15794            } else {
15795                buffer
15796                    .file()
15797                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15798            }
15799        })
15800    }
15801
15802    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15803        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15804            let project_path = buffer.read(cx).project_path(cx)?;
15805            let project = self.project.as_ref()?.read(cx);
15806            let entry = project.entry_for_path(&project_path, cx)?;
15807            let path = entry.path.to_path_buf();
15808            Some(path)
15809        })
15810    }
15811
15812    pub fn reveal_in_finder(
15813        &mut self,
15814        _: &RevealInFileManager,
15815        _window: &mut Window,
15816        cx: &mut Context<Self>,
15817    ) {
15818        if let Some(target) = self.target_file(cx) {
15819            cx.reveal_path(&target.abs_path(cx));
15820        }
15821    }
15822
15823    pub fn copy_path(
15824        &mut self,
15825        _: &zed_actions::workspace::CopyPath,
15826        _window: &mut Window,
15827        cx: &mut Context<Self>,
15828    ) {
15829        if let Some(path) = self.target_file_abs_path(cx) {
15830            if let Some(path) = path.to_str() {
15831                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15832            }
15833        }
15834    }
15835
15836    pub fn copy_relative_path(
15837        &mut self,
15838        _: &zed_actions::workspace::CopyRelativePath,
15839        _window: &mut Window,
15840        cx: &mut Context<Self>,
15841    ) {
15842        if let Some(path) = self.target_file_path(cx) {
15843            if let Some(path) = path.to_str() {
15844                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15845            }
15846        }
15847    }
15848
15849    pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
15850        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15851            buffer.read(cx).project_path(cx)
15852        } else {
15853            None
15854        }
15855    }
15856
15857    pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15858        let _ = maybe!({
15859            let breakpoint_store = self.breakpoint_store.as_ref()?;
15860
15861            let Some((_, _, active_position)) =
15862                breakpoint_store.read(cx).active_position().cloned()
15863            else {
15864                self.clear_row_highlights::<DebugCurrentRowHighlight>();
15865                return None;
15866            };
15867
15868            let snapshot = self
15869                .project
15870                .as_ref()?
15871                .read(cx)
15872                .buffer_for_id(active_position.buffer_id?, cx)?
15873                .read(cx)
15874                .snapshot();
15875
15876            for (id, ExcerptRange { context, .. }) in self
15877                .buffer
15878                .read(cx)
15879                .excerpts_for_buffer(active_position.buffer_id?, cx)
15880            {
15881                if context.start.cmp(&active_position, &snapshot).is_ge()
15882                    || context.end.cmp(&active_position, &snapshot).is_lt()
15883                {
15884                    continue;
15885                }
15886                let snapshot = self.buffer.read(cx).snapshot(cx);
15887                let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15888
15889                self.clear_row_highlights::<DebugCurrentRowHighlight>();
15890                self.go_to_line::<DebugCurrentRowHighlight>(
15891                    multibuffer_anchor,
15892                    Some(cx.theme().colors().editor_debugger_active_line_background),
15893                    window,
15894                    cx,
15895                );
15896
15897                cx.notify();
15898            }
15899
15900            Some(())
15901        });
15902    }
15903
15904    pub fn copy_file_name_without_extension(
15905        &mut self,
15906        _: &CopyFileNameWithoutExtension,
15907        _: &mut Window,
15908        cx: &mut Context<Self>,
15909    ) {
15910        if let Some(file) = self.target_file(cx) {
15911            if let Some(file_stem) = file.path().file_stem() {
15912                if let Some(name) = file_stem.to_str() {
15913                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15914                }
15915            }
15916        }
15917    }
15918
15919    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15920        if let Some(file) = self.target_file(cx) {
15921            if let Some(file_name) = file.path().file_name() {
15922                if let Some(name) = file_name.to_str() {
15923                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15924                }
15925            }
15926        }
15927    }
15928
15929    pub fn toggle_git_blame(
15930        &mut self,
15931        _: &::git::Blame,
15932        window: &mut Window,
15933        cx: &mut Context<Self>,
15934    ) {
15935        self.show_git_blame_gutter = !self.show_git_blame_gutter;
15936
15937        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15938            self.start_git_blame(true, window, cx);
15939        }
15940
15941        cx.notify();
15942    }
15943
15944    pub fn toggle_git_blame_inline(
15945        &mut self,
15946        _: &ToggleGitBlameInline,
15947        window: &mut Window,
15948        cx: &mut Context<Self>,
15949    ) {
15950        self.toggle_git_blame_inline_internal(true, window, cx);
15951        cx.notify();
15952    }
15953
15954    pub fn open_git_blame_commit(
15955        &mut self,
15956        _: &OpenGitBlameCommit,
15957        window: &mut Window,
15958        cx: &mut Context<Self>,
15959    ) {
15960        self.open_git_blame_commit_internal(window, cx);
15961    }
15962
15963    fn open_git_blame_commit_internal(
15964        &mut self,
15965        window: &mut Window,
15966        cx: &mut Context<Self>,
15967    ) -> Option<()> {
15968        let blame = self.blame.as_ref()?;
15969        let snapshot = self.snapshot(window, cx);
15970        let cursor = self.selections.newest::<Point>(cx).head();
15971        let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
15972        let blame_entry = blame
15973            .update(cx, |blame, cx| {
15974                blame
15975                    .blame_for_rows(
15976                        &[RowInfo {
15977                            buffer_id: Some(buffer.remote_id()),
15978                            buffer_row: Some(point.row),
15979                            ..Default::default()
15980                        }],
15981                        cx,
15982                    )
15983                    .next()
15984            })
15985            .flatten()?;
15986        let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
15987        let repo = blame.read(cx).repository(cx)?;
15988        let workspace = self.workspace()?.downgrade();
15989        renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
15990        None
15991    }
15992
15993    pub fn git_blame_inline_enabled(&self) -> bool {
15994        self.git_blame_inline_enabled
15995    }
15996
15997    pub fn toggle_selection_menu(
15998        &mut self,
15999        _: &ToggleSelectionMenu,
16000        _: &mut Window,
16001        cx: &mut Context<Self>,
16002    ) {
16003        self.show_selection_menu = self
16004            .show_selection_menu
16005            .map(|show_selections_menu| !show_selections_menu)
16006            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16007
16008        cx.notify();
16009    }
16010
16011    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16012        self.show_selection_menu
16013            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16014    }
16015
16016    fn start_git_blame(
16017        &mut self,
16018        user_triggered: bool,
16019        window: &mut Window,
16020        cx: &mut Context<Self>,
16021    ) {
16022        if let Some(project) = self.project.as_ref() {
16023            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16024                return;
16025            };
16026
16027            if buffer.read(cx).file().is_none() {
16028                return;
16029            }
16030
16031            let focused = self.focus_handle(cx).contains_focused(window, cx);
16032
16033            let project = project.clone();
16034            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16035            self.blame_subscription =
16036                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16037            self.blame = Some(blame);
16038        }
16039    }
16040
16041    fn toggle_git_blame_inline_internal(
16042        &mut self,
16043        user_triggered: bool,
16044        window: &mut Window,
16045        cx: &mut Context<Self>,
16046    ) {
16047        if self.git_blame_inline_enabled {
16048            self.git_blame_inline_enabled = false;
16049            self.show_git_blame_inline = false;
16050            self.show_git_blame_inline_delay_task.take();
16051        } else {
16052            self.git_blame_inline_enabled = true;
16053            self.start_git_blame_inline(user_triggered, window, cx);
16054        }
16055
16056        cx.notify();
16057    }
16058
16059    fn start_git_blame_inline(
16060        &mut self,
16061        user_triggered: bool,
16062        window: &mut Window,
16063        cx: &mut Context<Self>,
16064    ) {
16065        self.start_git_blame(user_triggered, window, cx);
16066
16067        if ProjectSettings::get_global(cx)
16068            .git
16069            .inline_blame_delay()
16070            .is_some()
16071        {
16072            self.start_inline_blame_timer(window, cx);
16073        } else {
16074            self.show_git_blame_inline = true
16075        }
16076    }
16077
16078    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16079        self.blame.as_ref()
16080    }
16081
16082    pub fn show_git_blame_gutter(&self) -> bool {
16083        self.show_git_blame_gutter
16084    }
16085
16086    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16087        self.show_git_blame_gutter && self.has_blame_entries(cx)
16088    }
16089
16090    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16091        self.show_git_blame_inline
16092            && (self.focus_handle.is_focused(window)
16093                || self
16094                    .git_blame_inline_tooltip
16095                    .as_ref()
16096                    .and_then(|t| t.upgrade())
16097                    .is_some())
16098            && !self.newest_selection_head_on_empty_line(cx)
16099            && self.has_blame_entries(cx)
16100    }
16101
16102    fn has_blame_entries(&self, cx: &App) -> bool {
16103        self.blame()
16104            .map_or(false, |blame| blame.read(cx).has_generated_entries())
16105    }
16106
16107    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16108        let cursor_anchor = self.selections.newest_anchor().head();
16109
16110        let snapshot = self.buffer.read(cx).snapshot(cx);
16111        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16112
16113        snapshot.line_len(buffer_row) == 0
16114    }
16115
16116    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16117        let buffer_and_selection = maybe!({
16118            let selection = self.selections.newest::<Point>(cx);
16119            let selection_range = selection.range();
16120
16121            let multi_buffer = self.buffer().read(cx);
16122            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16123            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16124
16125            let (buffer, range, _) = if selection.reversed {
16126                buffer_ranges.first()
16127            } else {
16128                buffer_ranges.last()
16129            }?;
16130
16131            let selection = text::ToPoint::to_point(&range.start, &buffer).row
16132                ..text::ToPoint::to_point(&range.end, &buffer).row;
16133            Some((
16134                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16135                selection,
16136            ))
16137        });
16138
16139        let Some((buffer, selection)) = buffer_and_selection else {
16140            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16141        };
16142
16143        let Some(project) = self.project.as_ref() else {
16144            return Task::ready(Err(anyhow!("editor does not have project")));
16145        };
16146
16147        project.update(cx, |project, cx| {
16148            project.get_permalink_to_line(&buffer, selection, cx)
16149        })
16150    }
16151
16152    pub fn copy_permalink_to_line(
16153        &mut self,
16154        _: &CopyPermalinkToLine,
16155        window: &mut Window,
16156        cx: &mut Context<Self>,
16157    ) {
16158        let permalink_task = self.get_permalink_to_line(cx);
16159        let workspace = self.workspace();
16160
16161        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16162            Ok(permalink) => {
16163                cx.update(|_, cx| {
16164                    cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16165                })
16166                .ok();
16167            }
16168            Err(err) => {
16169                let message = format!("Failed to copy permalink: {err}");
16170
16171                Err::<(), anyhow::Error>(err).log_err();
16172
16173                if let Some(workspace) = workspace {
16174                    workspace
16175                        .update_in(cx, |workspace, _, cx| {
16176                            struct CopyPermalinkToLine;
16177
16178                            workspace.show_toast(
16179                                Toast::new(
16180                                    NotificationId::unique::<CopyPermalinkToLine>(),
16181                                    message,
16182                                ),
16183                                cx,
16184                            )
16185                        })
16186                        .ok();
16187                }
16188            }
16189        })
16190        .detach();
16191    }
16192
16193    pub fn copy_file_location(
16194        &mut self,
16195        _: &CopyFileLocation,
16196        _: &mut Window,
16197        cx: &mut Context<Self>,
16198    ) {
16199        let selection = self.selections.newest::<Point>(cx).start.row + 1;
16200        if let Some(file) = self.target_file(cx) {
16201            if let Some(path) = file.path().to_str() {
16202                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16203            }
16204        }
16205    }
16206
16207    pub fn open_permalink_to_line(
16208        &mut self,
16209        _: &OpenPermalinkToLine,
16210        window: &mut Window,
16211        cx: &mut Context<Self>,
16212    ) {
16213        let permalink_task = self.get_permalink_to_line(cx);
16214        let workspace = self.workspace();
16215
16216        cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16217            Ok(permalink) => {
16218                cx.update(|_, cx| {
16219                    cx.open_url(permalink.as_ref());
16220                })
16221                .ok();
16222            }
16223            Err(err) => {
16224                let message = format!("Failed to open permalink: {err}");
16225
16226                Err::<(), anyhow::Error>(err).log_err();
16227
16228                if let Some(workspace) = workspace {
16229                    workspace
16230                        .update(cx, |workspace, cx| {
16231                            struct OpenPermalinkToLine;
16232
16233                            workspace.show_toast(
16234                                Toast::new(
16235                                    NotificationId::unique::<OpenPermalinkToLine>(),
16236                                    message,
16237                                ),
16238                                cx,
16239                            )
16240                        })
16241                        .ok();
16242                }
16243            }
16244        })
16245        .detach();
16246    }
16247
16248    pub fn insert_uuid_v4(
16249        &mut self,
16250        _: &InsertUuidV4,
16251        window: &mut Window,
16252        cx: &mut Context<Self>,
16253    ) {
16254        self.insert_uuid(UuidVersion::V4, window, cx);
16255    }
16256
16257    pub fn insert_uuid_v7(
16258        &mut self,
16259        _: &InsertUuidV7,
16260        window: &mut Window,
16261        cx: &mut Context<Self>,
16262    ) {
16263        self.insert_uuid(UuidVersion::V7, window, cx);
16264    }
16265
16266    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16267        self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16268        self.transact(window, cx, |this, window, cx| {
16269            let edits = this
16270                .selections
16271                .all::<Point>(cx)
16272                .into_iter()
16273                .map(|selection| {
16274                    let uuid = match version {
16275                        UuidVersion::V4 => uuid::Uuid::new_v4(),
16276                        UuidVersion::V7 => uuid::Uuid::now_v7(),
16277                    };
16278
16279                    (selection.range(), uuid.to_string())
16280                });
16281            this.edit(edits, cx);
16282            this.refresh_inline_completion(true, false, window, cx);
16283        });
16284    }
16285
16286    pub fn open_selections_in_multibuffer(
16287        &mut self,
16288        _: &OpenSelectionsInMultibuffer,
16289        window: &mut Window,
16290        cx: &mut Context<Self>,
16291    ) {
16292        let multibuffer = self.buffer.read(cx);
16293
16294        let Some(buffer) = multibuffer.as_singleton() else {
16295            return;
16296        };
16297
16298        let Some(workspace) = self.workspace() else {
16299            return;
16300        };
16301
16302        let locations = self
16303            .selections
16304            .disjoint_anchors()
16305            .iter()
16306            .map(|range| Location {
16307                buffer: buffer.clone(),
16308                range: range.start.text_anchor..range.end.text_anchor,
16309            })
16310            .collect::<Vec<_>>();
16311
16312        let title = multibuffer.title(cx).to_string();
16313
16314        cx.spawn_in(window, async move |_, cx| {
16315            workspace.update_in(cx, |workspace, window, cx| {
16316                Self::open_locations_in_multibuffer(
16317                    workspace,
16318                    locations,
16319                    format!("Selections for '{title}'"),
16320                    false,
16321                    MultibufferSelectionMode::All,
16322                    window,
16323                    cx,
16324                );
16325            })
16326        })
16327        .detach();
16328    }
16329
16330    /// Adds a row highlight for the given range. If a row has multiple highlights, the
16331    /// last highlight added will be used.
16332    ///
16333    /// If the range ends at the beginning of a line, then that line will not be highlighted.
16334    pub fn highlight_rows<T: 'static>(
16335        &mut self,
16336        range: Range<Anchor>,
16337        color: Hsla,
16338        should_autoscroll: bool,
16339        cx: &mut Context<Self>,
16340    ) {
16341        let snapshot = self.buffer().read(cx).snapshot(cx);
16342        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16343        let ix = row_highlights.binary_search_by(|highlight| {
16344            Ordering::Equal
16345                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16346                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16347        });
16348
16349        if let Err(mut ix) = ix {
16350            let index = post_inc(&mut self.highlight_order);
16351
16352            // If this range intersects with the preceding highlight, then merge it with
16353            // the preceding highlight. Otherwise insert a new highlight.
16354            let mut merged = false;
16355            if ix > 0 {
16356                let prev_highlight = &mut row_highlights[ix - 1];
16357                if prev_highlight
16358                    .range
16359                    .end
16360                    .cmp(&range.start, &snapshot)
16361                    .is_ge()
16362                {
16363                    ix -= 1;
16364                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16365                        prev_highlight.range.end = range.end;
16366                    }
16367                    merged = true;
16368                    prev_highlight.index = index;
16369                    prev_highlight.color = color;
16370                    prev_highlight.should_autoscroll = should_autoscroll;
16371                }
16372            }
16373
16374            if !merged {
16375                row_highlights.insert(
16376                    ix,
16377                    RowHighlight {
16378                        range: range.clone(),
16379                        index,
16380                        color,
16381                        should_autoscroll,
16382                    },
16383                );
16384            }
16385
16386            // If any of the following highlights intersect with this one, merge them.
16387            while let Some(next_highlight) = row_highlights.get(ix + 1) {
16388                let highlight = &row_highlights[ix];
16389                if next_highlight
16390                    .range
16391                    .start
16392                    .cmp(&highlight.range.end, &snapshot)
16393                    .is_le()
16394                {
16395                    if next_highlight
16396                        .range
16397                        .end
16398                        .cmp(&highlight.range.end, &snapshot)
16399                        .is_gt()
16400                    {
16401                        row_highlights[ix].range.end = next_highlight.range.end;
16402                    }
16403                    row_highlights.remove(ix + 1);
16404                } else {
16405                    break;
16406                }
16407            }
16408        }
16409    }
16410
16411    /// Remove any highlighted row ranges of the given type that intersect the
16412    /// given ranges.
16413    pub fn remove_highlighted_rows<T: 'static>(
16414        &mut self,
16415        ranges_to_remove: Vec<Range<Anchor>>,
16416        cx: &mut Context<Self>,
16417    ) {
16418        let snapshot = self.buffer().read(cx).snapshot(cx);
16419        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16420        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16421        row_highlights.retain(|highlight| {
16422            while let Some(range_to_remove) = ranges_to_remove.peek() {
16423                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16424                    Ordering::Less | Ordering::Equal => {
16425                        ranges_to_remove.next();
16426                    }
16427                    Ordering::Greater => {
16428                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16429                            Ordering::Less | Ordering::Equal => {
16430                                return false;
16431                            }
16432                            Ordering::Greater => break,
16433                        }
16434                    }
16435                }
16436            }
16437
16438            true
16439        })
16440    }
16441
16442    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16443    pub fn clear_row_highlights<T: 'static>(&mut self) {
16444        self.highlighted_rows.remove(&TypeId::of::<T>());
16445    }
16446
16447    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16448    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16449        self.highlighted_rows
16450            .get(&TypeId::of::<T>())
16451            .map_or(&[] as &[_], |vec| vec.as_slice())
16452            .iter()
16453            .map(|highlight| (highlight.range.clone(), highlight.color))
16454    }
16455
16456    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16457    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16458    /// Allows to ignore certain kinds of highlights.
16459    pub fn highlighted_display_rows(
16460        &self,
16461        window: &mut Window,
16462        cx: &mut App,
16463    ) -> BTreeMap<DisplayRow, LineHighlight> {
16464        let snapshot = self.snapshot(window, cx);
16465        let mut used_highlight_orders = HashMap::default();
16466        self.highlighted_rows
16467            .iter()
16468            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16469            .fold(
16470                BTreeMap::<DisplayRow, LineHighlight>::new(),
16471                |mut unique_rows, highlight| {
16472                    let start = highlight.range.start.to_display_point(&snapshot);
16473                    let end = highlight.range.end.to_display_point(&snapshot);
16474                    let start_row = start.row().0;
16475                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16476                        && end.column() == 0
16477                    {
16478                        end.row().0.saturating_sub(1)
16479                    } else {
16480                        end.row().0
16481                    };
16482                    for row in start_row..=end_row {
16483                        let used_index =
16484                            used_highlight_orders.entry(row).or_insert(highlight.index);
16485                        if highlight.index >= *used_index {
16486                            *used_index = highlight.index;
16487                            unique_rows.insert(DisplayRow(row), highlight.color.into());
16488                        }
16489                    }
16490                    unique_rows
16491                },
16492            )
16493    }
16494
16495    pub fn highlighted_display_row_for_autoscroll(
16496        &self,
16497        snapshot: &DisplaySnapshot,
16498    ) -> Option<DisplayRow> {
16499        self.highlighted_rows
16500            .values()
16501            .flat_map(|highlighted_rows| highlighted_rows.iter())
16502            .filter_map(|highlight| {
16503                if highlight.should_autoscroll {
16504                    Some(highlight.range.start.to_display_point(snapshot).row())
16505                } else {
16506                    None
16507                }
16508            })
16509            .min()
16510    }
16511
16512    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16513        self.highlight_background::<SearchWithinRange>(
16514            ranges,
16515            |colors| colors.editor_document_highlight_read_background,
16516            cx,
16517        )
16518    }
16519
16520    pub fn set_breadcrumb_header(&mut self, new_header: String) {
16521        self.breadcrumb_header = Some(new_header);
16522    }
16523
16524    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16525        self.clear_background_highlights::<SearchWithinRange>(cx);
16526    }
16527
16528    pub fn highlight_background<T: 'static>(
16529        &mut self,
16530        ranges: &[Range<Anchor>],
16531        color_fetcher: fn(&ThemeColors) -> Hsla,
16532        cx: &mut Context<Self>,
16533    ) {
16534        self.background_highlights
16535            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16536        self.scrollbar_marker_state.dirty = true;
16537        cx.notify();
16538    }
16539
16540    pub fn clear_background_highlights<T: 'static>(
16541        &mut self,
16542        cx: &mut Context<Self>,
16543    ) -> Option<BackgroundHighlight> {
16544        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16545        if !text_highlights.1.is_empty() {
16546            self.scrollbar_marker_state.dirty = true;
16547            cx.notify();
16548        }
16549        Some(text_highlights)
16550    }
16551
16552    pub fn highlight_gutter<T: 'static>(
16553        &mut self,
16554        ranges: &[Range<Anchor>],
16555        color_fetcher: fn(&App) -> Hsla,
16556        cx: &mut Context<Self>,
16557    ) {
16558        self.gutter_highlights
16559            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16560        cx.notify();
16561    }
16562
16563    pub fn clear_gutter_highlights<T: 'static>(
16564        &mut self,
16565        cx: &mut Context<Self>,
16566    ) -> Option<GutterHighlight> {
16567        cx.notify();
16568        self.gutter_highlights.remove(&TypeId::of::<T>())
16569    }
16570
16571    #[cfg(feature = "test-support")]
16572    pub fn all_text_background_highlights(
16573        &self,
16574        window: &mut Window,
16575        cx: &mut Context<Self>,
16576    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16577        let snapshot = self.snapshot(window, cx);
16578        let buffer = &snapshot.buffer_snapshot;
16579        let start = buffer.anchor_before(0);
16580        let end = buffer.anchor_after(buffer.len());
16581        let theme = cx.theme().colors();
16582        self.background_highlights_in_range(start..end, &snapshot, theme)
16583    }
16584
16585    #[cfg(feature = "test-support")]
16586    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16587        let snapshot = self.buffer().read(cx).snapshot(cx);
16588
16589        let highlights = self
16590            .background_highlights
16591            .get(&TypeId::of::<items::BufferSearchHighlights>());
16592
16593        if let Some((_color, ranges)) = highlights {
16594            ranges
16595                .iter()
16596                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16597                .collect_vec()
16598        } else {
16599            vec![]
16600        }
16601    }
16602
16603    fn document_highlights_for_position<'a>(
16604        &'a self,
16605        position: Anchor,
16606        buffer: &'a MultiBufferSnapshot,
16607    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16608        let read_highlights = self
16609            .background_highlights
16610            .get(&TypeId::of::<DocumentHighlightRead>())
16611            .map(|h| &h.1);
16612        let write_highlights = self
16613            .background_highlights
16614            .get(&TypeId::of::<DocumentHighlightWrite>())
16615            .map(|h| &h.1);
16616        let left_position = position.bias_left(buffer);
16617        let right_position = position.bias_right(buffer);
16618        read_highlights
16619            .into_iter()
16620            .chain(write_highlights)
16621            .flat_map(move |ranges| {
16622                let start_ix = match ranges.binary_search_by(|probe| {
16623                    let cmp = probe.end.cmp(&left_position, buffer);
16624                    if cmp.is_ge() {
16625                        Ordering::Greater
16626                    } else {
16627                        Ordering::Less
16628                    }
16629                }) {
16630                    Ok(i) | Err(i) => i,
16631                };
16632
16633                ranges[start_ix..]
16634                    .iter()
16635                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16636            })
16637    }
16638
16639    pub fn has_background_highlights<T: 'static>(&self) -> bool {
16640        self.background_highlights
16641            .get(&TypeId::of::<T>())
16642            .map_or(false, |(_, highlights)| !highlights.is_empty())
16643    }
16644
16645    pub fn background_highlights_in_range(
16646        &self,
16647        search_range: Range<Anchor>,
16648        display_snapshot: &DisplaySnapshot,
16649        theme: &ThemeColors,
16650    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16651        let mut results = Vec::new();
16652        for (color_fetcher, ranges) in self.background_highlights.values() {
16653            let color = color_fetcher(theme);
16654            let start_ix = match ranges.binary_search_by(|probe| {
16655                let cmp = probe
16656                    .end
16657                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16658                if cmp.is_gt() {
16659                    Ordering::Greater
16660                } else {
16661                    Ordering::Less
16662                }
16663            }) {
16664                Ok(i) | Err(i) => i,
16665            };
16666            for range in &ranges[start_ix..] {
16667                if range
16668                    .start
16669                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16670                    .is_ge()
16671                {
16672                    break;
16673                }
16674
16675                let start = range.start.to_display_point(display_snapshot);
16676                let end = range.end.to_display_point(display_snapshot);
16677                results.push((start..end, color))
16678            }
16679        }
16680        results
16681    }
16682
16683    pub fn background_highlight_row_ranges<T: 'static>(
16684        &self,
16685        search_range: Range<Anchor>,
16686        display_snapshot: &DisplaySnapshot,
16687        count: usize,
16688    ) -> Vec<RangeInclusive<DisplayPoint>> {
16689        let mut results = Vec::new();
16690        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16691            return vec![];
16692        };
16693
16694        let start_ix = match ranges.binary_search_by(|probe| {
16695            let cmp = probe
16696                .end
16697                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16698            if cmp.is_gt() {
16699                Ordering::Greater
16700            } else {
16701                Ordering::Less
16702            }
16703        }) {
16704            Ok(i) | Err(i) => i,
16705        };
16706        let mut push_region = |start: Option<Point>, end: Option<Point>| {
16707            if let (Some(start_display), Some(end_display)) = (start, end) {
16708                results.push(
16709                    start_display.to_display_point(display_snapshot)
16710                        ..=end_display.to_display_point(display_snapshot),
16711                );
16712            }
16713        };
16714        let mut start_row: Option<Point> = None;
16715        let mut end_row: Option<Point> = None;
16716        if ranges.len() > count {
16717            return Vec::new();
16718        }
16719        for range in &ranges[start_ix..] {
16720            if range
16721                .start
16722                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16723                .is_ge()
16724            {
16725                break;
16726            }
16727            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16728            if let Some(current_row) = &end_row {
16729                if end.row == current_row.row {
16730                    continue;
16731                }
16732            }
16733            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16734            if start_row.is_none() {
16735                assert_eq!(end_row, None);
16736                start_row = Some(start);
16737                end_row = Some(end);
16738                continue;
16739            }
16740            if let Some(current_end) = end_row.as_mut() {
16741                if start.row > current_end.row + 1 {
16742                    push_region(start_row, end_row);
16743                    start_row = Some(start);
16744                    end_row = Some(end);
16745                } else {
16746                    // Merge two hunks.
16747                    *current_end = end;
16748                }
16749            } else {
16750                unreachable!();
16751            }
16752        }
16753        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16754        push_region(start_row, end_row);
16755        results
16756    }
16757
16758    pub fn gutter_highlights_in_range(
16759        &self,
16760        search_range: Range<Anchor>,
16761        display_snapshot: &DisplaySnapshot,
16762        cx: &App,
16763    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16764        let mut results = Vec::new();
16765        for (color_fetcher, ranges) in self.gutter_highlights.values() {
16766            let color = color_fetcher(cx);
16767            let start_ix = match ranges.binary_search_by(|probe| {
16768                let cmp = probe
16769                    .end
16770                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16771                if cmp.is_gt() {
16772                    Ordering::Greater
16773                } else {
16774                    Ordering::Less
16775                }
16776            }) {
16777                Ok(i) | Err(i) => i,
16778            };
16779            for range in &ranges[start_ix..] {
16780                if range
16781                    .start
16782                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16783                    .is_ge()
16784                {
16785                    break;
16786                }
16787
16788                let start = range.start.to_display_point(display_snapshot);
16789                let end = range.end.to_display_point(display_snapshot);
16790                results.push((start..end, color))
16791            }
16792        }
16793        results
16794    }
16795
16796    /// Get the text ranges corresponding to the redaction query
16797    pub fn redacted_ranges(
16798        &self,
16799        search_range: Range<Anchor>,
16800        display_snapshot: &DisplaySnapshot,
16801        cx: &App,
16802    ) -> Vec<Range<DisplayPoint>> {
16803        display_snapshot
16804            .buffer_snapshot
16805            .redacted_ranges(search_range, |file| {
16806                if let Some(file) = file {
16807                    file.is_private()
16808                        && EditorSettings::get(
16809                            Some(SettingsLocation {
16810                                worktree_id: file.worktree_id(cx),
16811                                path: file.path().as_ref(),
16812                            }),
16813                            cx,
16814                        )
16815                        .redact_private_values
16816                } else {
16817                    false
16818                }
16819            })
16820            .map(|range| {
16821                range.start.to_display_point(display_snapshot)
16822                    ..range.end.to_display_point(display_snapshot)
16823            })
16824            .collect()
16825    }
16826
16827    pub fn highlight_text<T: 'static>(
16828        &mut self,
16829        ranges: Vec<Range<Anchor>>,
16830        style: HighlightStyle,
16831        cx: &mut Context<Self>,
16832    ) {
16833        self.display_map.update(cx, |map, _| {
16834            map.highlight_text(TypeId::of::<T>(), ranges, style)
16835        });
16836        cx.notify();
16837    }
16838
16839    pub(crate) fn highlight_inlays<T: 'static>(
16840        &mut self,
16841        highlights: Vec<InlayHighlight>,
16842        style: HighlightStyle,
16843        cx: &mut Context<Self>,
16844    ) {
16845        self.display_map.update(cx, |map, _| {
16846            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16847        });
16848        cx.notify();
16849    }
16850
16851    pub fn text_highlights<'a, T: 'static>(
16852        &'a self,
16853        cx: &'a App,
16854    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16855        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16856    }
16857
16858    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16859        let cleared = self
16860            .display_map
16861            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16862        if cleared {
16863            cx.notify();
16864        }
16865    }
16866
16867    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16868        (self.read_only(cx) || self.blink_manager.read(cx).visible())
16869            && self.focus_handle.is_focused(window)
16870    }
16871
16872    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16873        self.show_cursor_when_unfocused = is_enabled;
16874        cx.notify();
16875    }
16876
16877    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16878        cx.notify();
16879    }
16880
16881    fn on_buffer_event(
16882        &mut self,
16883        multibuffer: &Entity<MultiBuffer>,
16884        event: &multi_buffer::Event,
16885        window: &mut Window,
16886        cx: &mut Context<Self>,
16887    ) {
16888        match event {
16889            multi_buffer::Event::Edited {
16890                singleton_buffer_edited,
16891                edited_buffer: buffer_edited,
16892            } => {
16893                self.scrollbar_marker_state.dirty = true;
16894                self.active_indent_guides_state.dirty = true;
16895                self.refresh_active_diagnostics(cx);
16896                self.refresh_code_actions(window, cx);
16897                if self.has_active_inline_completion() {
16898                    self.update_visible_inline_completion(window, cx);
16899                }
16900                if let Some(buffer) = buffer_edited {
16901                    let buffer_id = buffer.read(cx).remote_id();
16902                    if !self.registered_buffers.contains_key(&buffer_id) {
16903                        if let Some(project) = self.project.as_ref() {
16904                            project.update(cx, |project, cx| {
16905                                self.registered_buffers.insert(
16906                                    buffer_id,
16907                                    project.register_buffer_with_language_servers(&buffer, cx),
16908                                );
16909                            })
16910                        }
16911                    }
16912                }
16913                cx.emit(EditorEvent::BufferEdited);
16914                cx.emit(SearchEvent::MatchesInvalidated);
16915                if *singleton_buffer_edited {
16916                    if let Some(project) = &self.project {
16917                        #[allow(clippy::mutable_key_type)]
16918                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16919                            multibuffer
16920                                .all_buffers()
16921                                .into_iter()
16922                                .filter_map(|buffer| {
16923                                    buffer.update(cx, |buffer, cx| {
16924                                        let language = buffer.language()?;
16925                                        let should_discard = project.update(cx, |project, cx| {
16926                                            project.is_local()
16927                                                && !project.has_language_servers_for(buffer, cx)
16928                                        });
16929                                        should_discard.not().then_some(language.clone())
16930                                    })
16931                                })
16932                                .collect::<HashSet<_>>()
16933                        });
16934                        if !languages_affected.is_empty() {
16935                            self.refresh_inlay_hints(
16936                                InlayHintRefreshReason::BufferEdited(languages_affected),
16937                                cx,
16938                            );
16939                        }
16940                    }
16941                }
16942
16943                let Some(project) = &self.project else { return };
16944                let (telemetry, is_via_ssh) = {
16945                    let project = project.read(cx);
16946                    let telemetry = project.client().telemetry().clone();
16947                    let is_via_ssh = project.is_via_ssh();
16948                    (telemetry, is_via_ssh)
16949                };
16950                refresh_linked_ranges(self, window, cx);
16951                telemetry.log_edit_event("editor", is_via_ssh);
16952            }
16953            multi_buffer::Event::ExcerptsAdded {
16954                buffer,
16955                predecessor,
16956                excerpts,
16957            } => {
16958                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16959                let buffer_id = buffer.read(cx).remote_id();
16960                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16961                    if let Some(project) = &self.project {
16962                        get_uncommitted_diff_for_buffer(
16963                            project,
16964                            [buffer.clone()],
16965                            self.buffer.clone(),
16966                            cx,
16967                        )
16968                        .detach();
16969                    }
16970                }
16971                cx.emit(EditorEvent::ExcerptsAdded {
16972                    buffer: buffer.clone(),
16973                    predecessor: *predecessor,
16974                    excerpts: excerpts.clone(),
16975                });
16976                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16977            }
16978            multi_buffer::Event::ExcerptsRemoved { ids } => {
16979                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16980                let buffer = self.buffer.read(cx);
16981                self.registered_buffers
16982                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16983                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16984                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16985            }
16986            multi_buffer::Event::ExcerptsEdited {
16987                excerpt_ids,
16988                buffer_ids,
16989            } => {
16990                self.display_map.update(cx, |map, cx| {
16991                    map.unfold_buffers(buffer_ids.iter().copied(), cx)
16992                });
16993                cx.emit(EditorEvent::ExcerptsEdited {
16994                    ids: excerpt_ids.clone(),
16995                })
16996            }
16997            multi_buffer::Event::ExcerptsExpanded { ids } => {
16998                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16999                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17000            }
17001            multi_buffer::Event::Reparsed(buffer_id) => {
17002                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17003                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17004
17005                cx.emit(EditorEvent::Reparsed(*buffer_id));
17006            }
17007            multi_buffer::Event::DiffHunksToggled => {
17008                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17009            }
17010            multi_buffer::Event::LanguageChanged(buffer_id) => {
17011                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17012                jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17013                cx.emit(EditorEvent::Reparsed(*buffer_id));
17014                cx.notify();
17015            }
17016            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17017            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17018            multi_buffer::Event::FileHandleChanged
17019            | multi_buffer::Event::Reloaded
17020            | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17021            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17022            multi_buffer::Event::DiagnosticsUpdated => {
17023                self.refresh_active_diagnostics(cx);
17024                self.refresh_inline_diagnostics(true, window, cx);
17025                self.scrollbar_marker_state.dirty = true;
17026                cx.notify();
17027            }
17028            _ => {}
17029        };
17030    }
17031
17032    fn on_display_map_changed(
17033        &mut self,
17034        _: Entity<DisplayMap>,
17035        _: &mut Window,
17036        cx: &mut Context<Self>,
17037    ) {
17038        cx.notify();
17039    }
17040
17041    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17042        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17043        self.update_edit_prediction_settings(cx);
17044        self.refresh_inline_completion(true, false, window, cx);
17045        self.refresh_inlay_hints(
17046            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17047                self.selections.newest_anchor().head(),
17048                &self.buffer.read(cx).snapshot(cx),
17049                cx,
17050            )),
17051            cx,
17052        );
17053
17054        let old_cursor_shape = self.cursor_shape;
17055
17056        {
17057            let editor_settings = EditorSettings::get_global(cx);
17058            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17059            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17060            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17061            self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17062        }
17063
17064        if old_cursor_shape != self.cursor_shape {
17065            cx.emit(EditorEvent::CursorShapeChanged);
17066        }
17067
17068        let project_settings = ProjectSettings::get_global(cx);
17069        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17070
17071        if self.mode == EditorMode::Full {
17072            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17073            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17074            if self.show_inline_diagnostics != show_inline_diagnostics {
17075                self.show_inline_diagnostics = show_inline_diagnostics;
17076                self.refresh_inline_diagnostics(false, window, cx);
17077            }
17078
17079            if self.git_blame_inline_enabled != inline_blame_enabled {
17080                self.toggle_git_blame_inline_internal(false, window, cx);
17081            }
17082        }
17083
17084        cx.notify();
17085    }
17086
17087    pub fn set_searchable(&mut self, searchable: bool) {
17088        self.searchable = searchable;
17089    }
17090
17091    pub fn searchable(&self) -> bool {
17092        self.searchable
17093    }
17094
17095    fn open_proposed_changes_editor(
17096        &mut self,
17097        _: &OpenProposedChangesEditor,
17098        window: &mut Window,
17099        cx: &mut Context<Self>,
17100    ) {
17101        let Some(workspace) = self.workspace() else {
17102            cx.propagate();
17103            return;
17104        };
17105
17106        let selections = self.selections.all::<usize>(cx);
17107        let multi_buffer = self.buffer.read(cx);
17108        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17109        let mut new_selections_by_buffer = HashMap::default();
17110        for selection in selections {
17111            for (buffer, range, _) in
17112                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17113            {
17114                let mut range = range.to_point(buffer);
17115                range.start.column = 0;
17116                range.end.column = buffer.line_len(range.end.row);
17117                new_selections_by_buffer
17118                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17119                    .or_insert(Vec::new())
17120                    .push(range)
17121            }
17122        }
17123
17124        let proposed_changes_buffers = new_selections_by_buffer
17125            .into_iter()
17126            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17127            .collect::<Vec<_>>();
17128        let proposed_changes_editor = cx.new(|cx| {
17129            ProposedChangesEditor::new(
17130                "Proposed changes",
17131                proposed_changes_buffers,
17132                self.project.clone(),
17133                window,
17134                cx,
17135            )
17136        });
17137
17138        window.defer(cx, move |window, cx| {
17139            workspace.update(cx, |workspace, cx| {
17140                workspace.active_pane().update(cx, |pane, cx| {
17141                    pane.add_item(
17142                        Box::new(proposed_changes_editor),
17143                        true,
17144                        true,
17145                        None,
17146                        window,
17147                        cx,
17148                    );
17149                });
17150            });
17151        });
17152    }
17153
17154    pub fn open_excerpts_in_split(
17155        &mut self,
17156        _: &OpenExcerptsSplit,
17157        window: &mut Window,
17158        cx: &mut Context<Self>,
17159    ) {
17160        self.open_excerpts_common(None, true, window, cx)
17161    }
17162
17163    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17164        self.open_excerpts_common(None, false, window, cx)
17165    }
17166
17167    fn open_excerpts_common(
17168        &mut self,
17169        jump_data: Option<JumpData>,
17170        split: bool,
17171        window: &mut Window,
17172        cx: &mut Context<Self>,
17173    ) {
17174        let Some(workspace) = self.workspace() else {
17175            cx.propagate();
17176            return;
17177        };
17178
17179        if self.buffer.read(cx).is_singleton() {
17180            cx.propagate();
17181            return;
17182        }
17183
17184        let mut new_selections_by_buffer = HashMap::default();
17185        match &jump_data {
17186            Some(JumpData::MultiBufferPoint {
17187                excerpt_id,
17188                position,
17189                anchor,
17190                line_offset_from_top,
17191            }) => {
17192                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17193                if let Some(buffer) = multi_buffer_snapshot
17194                    .buffer_id_for_excerpt(*excerpt_id)
17195                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17196                {
17197                    let buffer_snapshot = buffer.read(cx).snapshot();
17198                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17199                        language::ToPoint::to_point(anchor, &buffer_snapshot)
17200                    } else {
17201                        buffer_snapshot.clip_point(*position, Bias::Left)
17202                    };
17203                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17204                    new_selections_by_buffer.insert(
17205                        buffer,
17206                        (
17207                            vec![jump_to_offset..jump_to_offset],
17208                            Some(*line_offset_from_top),
17209                        ),
17210                    );
17211                }
17212            }
17213            Some(JumpData::MultiBufferRow {
17214                row,
17215                line_offset_from_top,
17216            }) => {
17217                let point = MultiBufferPoint::new(row.0, 0);
17218                if let Some((buffer, buffer_point, _)) =
17219                    self.buffer.read(cx).point_to_buffer_point(point, cx)
17220                {
17221                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17222                    new_selections_by_buffer
17223                        .entry(buffer)
17224                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
17225                        .0
17226                        .push(buffer_offset..buffer_offset)
17227                }
17228            }
17229            None => {
17230                let selections = self.selections.all::<usize>(cx);
17231                let multi_buffer = self.buffer.read(cx);
17232                for selection in selections {
17233                    for (snapshot, range, _, anchor) in multi_buffer
17234                        .snapshot(cx)
17235                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17236                    {
17237                        if let Some(anchor) = anchor {
17238                            // selection is in a deleted hunk
17239                            let Some(buffer_id) = anchor.buffer_id else {
17240                                continue;
17241                            };
17242                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17243                                continue;
17244                            };
17245                            let offset = text::ToOffset::to_offset(
17246                                &anchor.text_anchor,
17247                                &buffer_handle.read(cx).snapshot(),
17248                            );
17249                            let range = offset..offset;
17250                            new_selections_by_buffer
17251                                .entry(buffer_handle)
17252                                .or_insert((Vec::new(), None))
17253                                .0
17254                                .push(range)
17255                        } else {
17256                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17257                            else {
17258                                continue;
17259                            };
17260                            new_selections_by_buffer
17261                                .entry(buffer_handle)
17262                                .or_insert((Vec::new(), None))
17263                                .0
17264                                .push(range)
17265                        }
17266                    }
17267                }
17268            }
17269        }
17270
17271        new_selections_by_buffer
17272            .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17273
17274        if new_selections_by_buffer.is_empty() {
17275            return;
17276        }
17277
17278        // We defer the pane interaction because we ourselves are a workspace item
17279        // and activating a new item causes the pane to call a method on us reentrantly,
17280        // which panics if we're on the stack.
17281        window.defer(cx, move |window, cx| {
17282            workspace.update(cx, |workspace, cx| {
17283                let pane = if split {
17284                    workspace.adjacent_pane(window, cx)
17285                } else {
17286                    workspace.active_pane().clone()
17287                };
17288
17289                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17290                    let editor = buffer
17291                        .read(cx)
17292                        .file()
17293                        .is_none()
17294                        .then(|| {
17295                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17296                            // so `workspace.open_project_item` will never find them, always opening a new editor.
17297                            // Instead, we try to activate the existing editor in the pane first.
17298                            let (editor, pane_item_index) =
17299                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
17300                                    let editor = item.downcast::<Editor>()?;
17301                                    let singleton_buffer =
17302                                        editor.read(cx).buffer().read(cx).as_singleton()?;
17303                                    if singleton_buffer == buffer {
17304                                        Some((editor, i))
17305                                    } else {
17306                                        None
17307                                    }
17308                                })?;
17309                            pane.update(cx, |pane, cx| {
17310                                pane.activate_item(pane_item_index, true, true, window, cx)
17311                            });
17312                            Some(editor)
17313                        })
17314                        .flatten()
17315                        .unwrap_or_else(|| {
17316                            workspace.open_project_item::<Self>(
17317                                pane.clone(),
17318                                buffer,
17319                                true,
17320                                true,
17321                                window,
17322                                cx,
17323                            )
17324                        });
17325
17326                    editor.update(cx, |editor, cx| {
17327                        let autoscroll = match scroll_offset {
17328                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17329                            None => Autoscroll::newest(),
17330                        };
17331                        let nav_history = editor.nav_history.take();
17332                        editor.change_selections(Some(autoscroll), window, cx, |s| {
17333                            s.select_ranges(ranges);
17334                        });
17335                        editor.nav_history = nav_history;
17336                    });
17337                }
17338            })
17339        });
17340    }
17341
17342    // For now, don't allow opening excerpts in buffers that aren't backed by
17343    // regular project files.
17344    fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17345        file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17346    }
17347
17348    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17349        let snapshot = self.buffer.read(cx).read(cx);
17350        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17351        Some(
17352            ranges
17353                .iter()
17354                .map(move |range| {
17355                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17356                })
17357                .collect(),
17358        )
17359    }
17360
17361    fn selection_replacement_ranges(
17362        &self,
17363        range: Range<OffsetUtf16>,
17364        cx: &mut App,
17365    ) -> Vec<Range<OffsetUtf16>> {
17366        let selections = self.selections.all::<OffsetUtf16>(cx);
17367        let newest_selection = selections
17368            .iter()
17369            .max_by_key(|selection| selection.id)
17370            .unwrap();
17371        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17372        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17373        let snapshot = self.buffer.read(cx).read(cx);
17374        selections
17375            .into_iter()
17376            .map(|mut selection| {
17377                selection.start.0 =
17378                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
17379                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17380                snapshot.clip_offset_utf16(selection.start, Bias::Left)
17381                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17382            })
17383            .collect()
17384    }
17385
17386    fn report_editor_event(
17387        &self,
17388        event_type: &'static str,
17389        file_extension: Option<String>,
17390        cx: &App,
17391    ) {
17392        if cfg!(any(test, feature = "test-support")) {
17393            return;
17394        }
17395
17396        let Some(project) = &self.project else { return };
17397
17398        // If None, we are in a file without an extension
17399        let file = self
17400            .buffer
17401            .read(cx)
17402            .as_singleton()
17403            .and_then(|b| b.read(cx).file());
17404        let file_extension = file_extension.or(file
17405            .as_ref()
17406            .and_then(|file| Path::new(file.file_name(cx)).extension())
17407            .and_then(|e| e.to_str())
17408            .map(|a| a.to_string()));
17409
17410        let vim_mode = cx
17411            .global::<SettingsStore>()
17412            .raw_user_settings()
17413            .get("vim_mode")
17414            == Some(&serde_json::Value::Bool(true));
17415
17416        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17417        let copilot_enabled = edit_predictions_provider
17418            == language::language_settings::EditPredictionProvider::Copilot;
17419        let copilot_enabled_for_language = self
17420            .buffer
17421            .read(cx)
17422            .language_settings(cx)
17423            .show_edit_predictions;
17424
17425        let project = project.read(cx);
17426        telemetry::event!(
17427            event_type,
17428            file_extension,
17429            vim_mode,
17430            copilot_enabled,
17431            copilot_enabled_for_language,
17432            edit_predictions_provider,
17433            is_via_ssh = project.is_via_ssh(),
17434        );
17435    }
17436
17437    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17438    /// with each line being an array of {text, highlight} objects.
17439    fn copy_highlight_json(
17440        &mut self,
17441        _: &CopyHighlightJson,
17442        window: &mut Window,
17443        cx: &mut Context<Self>,
17444    ) {
17445        #[derive(Serialize)]
17446        struct Chunk<'a> {
17447            text: String,
17448            highlight: Option<&'a str>,
17449        }
17450
17451        let snapshot = self.buffer.read(cx).snapshot(cx);
17452        let range = self
17453            .selected_text_range(false, window, cx)
17454            .and_then(|selection| {
17455                if selection.range.is_empty() {
17456                    None
17457                } else {
17458                    Some(selection.range)
17459                }
17460            })
17461            .unwrap_or_else(|| 0..snapshot.len());
17462
17463        let chunks = snapshot.chunks(range, true);
17464        let mut lines = Vec::new();
17465        let mut line: VecDeque<Chunk> = VecDeque::new();
17466
17467        let Some(style) = self.style.as_ref() else {
17468            return;
17469        };
17470
17471        for chunk in chunks {
17472            let highlight = chunk
17473                .syntax_highlight_id
17474                .and_then(|id| id.name(&style.syntax));
17475            let mut chunk_lines = chunk.text.split('\n').peekable();
17476            while let Some(text) = chunk_lines.next() {
17477                let mut merged_with_last_token = false;
17478                if let Some(last_token) = line.back_mut() {
17479                    if last_token.highlight == highlight {
17480                        last_token.text.push_str(text);
17481                        merged_with_last_token = true;
17482                    }
17483                }
17484
17485                if !merged_with_last_token {
17486                    line.push_back(Chunk {
17487                        text: text.into(),
17488                        highlight,
17489                    });
17490                }
17491
17492                if chunk_lines.peek().is_some() {
17493                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
17494                        line.pop_front();
17495                    }
17496                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
17497                        line.pop_back();
17498                    }
17499
17500                    lines.push(mem::take(&mut line));
17501                }
17502            }
17503        }
17504
17505        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17506            return;
17507        };
17508        cx.write_to_clipboard(ClipboardItem::new_string(lines));
17509    }
17510
17511    pub fn open_context_menu(
17512        &mut self,
17513        _: &OpenContextMenu,
17514        window: &mut Window,
17515        cx: &mut Context<Self>,
17516    ) {
17517        self.request_autoscroll(Autoscroll::newest(), cx);
17518        let position = self.selections.newest_display(cx).start;
17519        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17520    }
17521
17522    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17523        &self.inlay_hint_cache
17524    }
17525
17526    pub fn replay_insert_event(
17527        &mut self,
17528        text: &str,
17529        relative_utf16_range: Option<Range<isize>>,
17530        window: &mut Window,
17531        cx: &mut Context<Self>,
17532    ) {
17533        if !self.input_enabled {
17534            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17535            return;
17536        }
17537        if let Some(relative_utf16_range) = relative_utf16_range {
17538            let selections = self.selections.all::<OffsetUtf16>(cx);
17539            self.change_selections(None, window, cx, |s| {
17540                let new_ranges = selections.into_iter().map(|range| {
17541                    let start = OffsetUtf16(
17542                        range
17543                            .head()
17544                            .0
17545                            .saturating_add_signed(relative_utf16_range.start),
17546                    );
17547                    let end = OffsetUtf16(
17548                        range
17549                            .head()
17550                            .0
17551                            .saturating_add_signed(relative_utf16_range.end),
17552                    );
17553                    start..end
17554                });
17555                s.select_ranges(new_ranges);
17556            });
17557        }
17558
17559        self.handle_input(text, window, cx);
17560    }
17561
17562    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17563        let Some(provider) = self.semantics_provider.as_ref() else {
17564            return false;
17565        };
17566
17567        let mut supports = false;
17568        self.buffer().update(cx, |this, cx| {
17569            this.for_each_buffer(|buffer| {
17570                supports |= provider.supports_inlay_hints(buffer, cx);
17571            });
17572        });
17573
17574        supports
17575    }
17576
17577    pub fn is_focused(&self, window: &Window) -> bool {
17578        self.focus_handle.is_focused(window)
17579    }
17580
17581    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17582        cx.emit(EditorEvent::Focused);
17583
17584        if let Some(descendant) = self
17585            .last_focused_descendant
17586            .take()
17587            .and_then(|descendant| descendant.upgrade())
17588        {
17589            window.focus(&descendant);
17590        } else {
17591            if let Some(blame) = self.blame.as_ref() {
17592                blame.update(cx, GitBlame::focus)
17593            }
17594
17595            self.blink_manager.update(cx, BlinkManager::enable);
17596            self.show_cursor_names(window, cx);
17597            self.buffer.update(cx, |buffer, cx| {
17598                buffer.finalize_last_transaction(cx);
17599                if self.leader_peer_id.is_none() {
17600                    buffer.set_active_selections(
17601                        &self.selections.disjoint_anchors(),
17602                        self.selections.line_mode,
17603                        self.cursor_shape,
17604                        cx,
17605                    );
17606                }
17607            });
17608        }
17609    }
17610
17611    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17612        cx.emit(EditorEvent::FocusedIn)
17613    }
17614
17615    fn handle_focus_out(
17616        &mut self,
17617        event: FocusOutEvent,
17618        _window: &mut Window,
17619        cx: &mut Context<Self>,
17620    ) {
17621        if event.blurred != self.focus_handle {
17622            self.last_focused_descendant = Some(event.blurred);
17623        }
17624        self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17625    }
17626
17627    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17628        self.blink_manager.update(cx, BlinkManager::disable);
17629        self.buffer
17630            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17631
17632        if let Some(blame) = self.blame.as_ref() {
17633            blame.update(cx, GitBlame::blur)
17634        }
17635        if !self.hover_state.focused(window, cx) {
17636            hide_hover(self, cx);
17637        }
17638        if !self
17639            .context_menu
17640            .borrow()
17641            .as_ref()
17642            .is_some_and(|context_menu| context_menu.focused(window, cx))
17643        {
17644            self.hide_context_menu(window, cx);
17645        }
17646        self.discard_inline_completion(false, cx);
17647        cx.emit(EditorEvent::Blurred);
17648        cx.notify();
17649    }
17650
17651    pub fn register_action<A: Action>(
17652        &mut self,
17653        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17654    ) -> Subscription {
17655        let id = self.next_editor_action_id.post_inc();
17656        let listener = Arc::new(listener);
17657        self.editor_actions.borrow_mut().insert(
17658            id,
17659            Box::new(move |window, _| {
17660                let listener = listener.clone();
17661                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17662                    let action = action.downcast_ref().unwrap();
17663                    if phase == DispatchPhase::Bubble {
17664                        listener(action, window, cx)
17665                    }
17666                })
17667            }),
17668        );
17669
17670        let editor_actions = self.editor_actions.clone();
17671        Subscription::new(move || {
17672            editor_actions.borrow_mut().remove(&id);
17673        })
17674    }
17675
17676    pub fn file_header_size(&self) -> u32 {
17677        FILE_HEADER_HEIGHT
17678    }
17679
17680    pub fn restore(
17681        &mut self,
17682        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17683        window: &mut Window,
17684        cx: &mut Context<Self>,
17685    ) {
17686        let workspace = self.workspace();
17687        let project = self.project.as_ref();
17688        let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17689            let mut tasks = Vec::new();
17690            for (buffer_id, changes) in revert_changes {
17691                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17692                    buffer.update(cx, |buffer, cx| {
17693                        buffer.edit(
17694                            changes
17695                                .into_iter()
17696                                .map(|(range, text)| (range, text.to_string())),
17697                            None,
17698                            cx,
17699                        );
17700                    });
17701
17702                    if let Some(project) =
17703                        project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17704                    {
17705                        project.update(cx, |project, cx| {
17706                            tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17707                        })
17708                    }
17709                }
17710            }
17711            tasks
17712        });
17713        cx.spawn_in(window, async move |_, cx| {
17714            for (buffer, task) in save_tasks {
17715                let result = task.await;
17716                if result.is_err() {
17717                    let Some(path) = buffer
17718                        .read_with(cx, |buffer, cx| buffer.project_path(cx))
17719                        .ok()
17720                    else {
17721                        continue;
17722                    };
17723                    if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17724                        let Some(task) = cx
17725                            .update_window_entity(&workspace, |workspace, window, cx| {
17726                                workspace
17727                                    .open_path_preview(path, None, false, false, false, window, cx)
17728                            })
17729                            .ok()
17730                        else {
17731                            continue;
17732                        };
17733                        task.await.log_err();
17734                    }
17735                }
17736            }
17737        })
17738        .detach();
17739        self.change_selections(None, window, cx, |selections| selections.refresh());
17740    }
17741
17742    pub fn to_pixel_point(
17743        &self,
17744        source: multi_buffer::Anchor,
17745        editor_snapshot: &EditorSnapshot,
17746        window: &mut Window,
17747    ) -> Option<gpui::Point<Pixels>> {
17748        let source_point = source.to_display_point(editor_snapshot);
17749        self.display_to_pixel_point(source_point, editor_snapshot, window)
17750    }
17751
17752    pub fn display_to_pixel_point(
17753        &self,
17754        source: DisplayPoint,
17755        editor_snapshot: &EditorSnapshot,
17756        window: &mut Window,
17757    ) -> Option<gpui::Point<Pixels>> {
17758        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17759        let text_layout_details = self.text_layout_details(window);
17760        let scroll_top = text_layout_details
17761            .scroll_anchor
17762            .scroll_position(editor_snapshot)
17763            .y;
17764
17765        if source.row().as_f32() < scroll_top.floor() {
17766            return None;
17767        }
17768        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17769        let source_y = line_height * (source.row().as_f32() - scroll_top);
17770        Some(gpui::Point::new(source_x, source_y))
17771    }
17772
17773    pub fn has_visible_completions_menu(&self) -> bool {
17774        !self.edit_prediction_preview_is_active()
17775            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17776                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17777            })
17778    }
17779
17780    pub fn register_addon<T: Addon>(&mut self, instance: T) {
17781        self.addons
17782            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17783    }
17784
17785    pub fn unregister_addon<T: Addon>(&mut self) {
17786        self.addons.remove(&std::any::TypeId::of::<T>());
17787    }
17788
17789    pub fn addon<T: Addon>(&self) -> Option<&T> {
17790        let type_id = std::any::TypeId::of::<T>();
17791        self.addons
17792            .get(&type_id)
17793            .and_then(|item| item.to_any().downcast_ref::<T>())
17794    }
17795
17796    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17797        let text_layout_details = self.text_layout_details(window);
17798        let style = &text_layout_details.editor_style;
17799        let font_id = window.text_system().resolve_font(&style.text.font());
17800        let font_size = style.text.font_size.to_pixels(window.rem_size());
17801        let line_height = style.text.line_height_in_pixels(window.rem_size());
17802        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17803
17804        gpui::Size::new(em_width, line_height)
17805    }
17806
17807    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17808        self.load_diff_task.clone()
17809    }
17810
17811    fn read_metadata_from_db(
17812        &mut self,
17813        item_id: u64,
17814        workspace_id: WorkspaceId,
17815        window: &mut Window,
17816        cx: &mut Context<Editor>,
17817    ) {
17818        if self.is_singleton(cx)
17819            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17820        {
17821            let buffer_snapshot = OnceCell::new();
17822
17823            if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17824                if !folds.is_empty() {
17825                    let snapshot =
17826                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17827                    self.fold_ranges(
17828                        folds
17829                            .into_iter()
17830                            .map(|(start, end)| {
17831                                snapshot.clip_offset(start, Bias::Left)
17832                                    ..snapshot.clip_offset(end, Bias::Right)
17833                            })
17834                            .collect(),
17835                        false,
17836                        window,
17837                        cx,
17838                    );
17839                }
17840            }
17841
17842            if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17843                if !selections.is_empty() {
17844                    let snapshot =
17845                        buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17846                    self.change_selections(None, window, cx, |s| {
17847                        s.select_ranges(selections.into_iter().map(|(start, end)| {
17848                            snapshot.clip_offset(start, Bias::Left)
17849                                ..snapshot.clip_offset(end, Bias::Right)
17850                        }));
17851                    });
17852                }
17853            };
17854        }
17855
17856        self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17857    }
17858}
17859
17860fn insert_extra_newline_brackets(
17861    buffer: &MultiBufferSnapshot,
17862    range: Range<usize>,
17863    language: &language::LanguageScope,
17864) -> bool {
17865    let leading_whitespace_len = buffer
17866        .reversed_chars_at(range.start)
17867        .take_while(|c| c.is_whitespace() && *c != '\n')
17868        .map(|c| c.len_utf8())
17869        .sum::<usize>();
17870    let trailing_whitespace_len = buffer
17871        .chars_at(range.end)
17872        .take_while(|c| c.is_whitespace() && *c != '\n')
17873        .map(|c| c.len_utf8())
17874        .sum::<usize>();
17875    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17876
17877    language.brackets().any(|(pair, enabled)| {
17878        let pair_start = pair.start.trim_end();
17879        let pair_end = pair.end.trim_start();
17880
17881        enabled
17882            && pair.newline
17883            && buffer.contains_str_at(range.end, pair_end)
17884            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17885    })
17886}
17887
17888fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17889    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17890        [(buffer, range, _)] => (*buffer, range.clone()),
17891        _ => return false,
17892    };
17893    let pair = {
17894        let mut result: Option<BracketMatch> = None;
17895
17896        for pair in buffer
17897            .all_bracket_ranges(range.clone())
17898            .filter(move |pair| {
17899                pair.open_range.start <= range.start && pair.close_range.end >= range.end
17900            })
17901        {
17902            let len = pair.close_range.end - pair.open_range.start;
17903
17904            if let Some(existing) = &result {
17905                let existing_len = existing.close_range.end - existing.open_range.start;
17906                if len > existing_len {
17907                    continue;
17908                }
17909            }
17910
17911            result = Some(pair);
17912        }
17913
17914        result
17915    };
17916    let Some(pair) = pair else {
17917        return false;
17918    };
17919    pair.newline_only
17920        && buffer
17921            .chars_for_range(pair.open_range.end..range.start)
17922            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17923            .all(|c| c.is_whitespace() && c != '\n')
17924}
17925
17926fn get_uncommitted_diff_for_buffer(
17927    project: &Entity<Project>,
17928    buffers: impl IntoIterator<Item = Entity<Buffer>>,
17929    buffer: Entity<MultiBuffer>,
17930    cx: &mut App,
17931) -> Task<()> {
17932    let mut tasks = Vec::new();
17933    project.update(cx, |project, cx| {
17934        for buffer in buffers {
17935            if project::File::from_dyn(buffer.read(cx).file()).is_some() {
17936                tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17937            }
17938        }
17939    });
17940    cx.spawn(async move |cx| {
17941        let diffs = future::join_all(tasks).await;
17942        buffer
17943            .update(cx, |buffer, cx| {
17944                for diff in diffs.into_iter().flatten() {
17945                    buffer.add_diff(diff, cx);
17946                }
17947            })
17948            .ok();
17949    })
17950}
17951
17952fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17953    let tab_size = tab_size.get() as usize;
17954    let mut width = offset;
17955
17956    for ch in text.chars() {
17957        width += if ch == '\t' {
17958            tab_size - (width % tab_size)
17959        } else {
17960            1
17961        };
17962    }
17963
17964    width - offset
17965}
17966
17967#[cfg(test)]
17968mod tests {
17969    use super::*;
17970
17971    #[test]
17972    fn test_string_size_with_expanded_tabs() {
17973        let nz = |val| NonZeroU32::new(val).unwrap();
17974        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17975        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17976        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17977        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17978        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17979        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17980        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17981        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17982    }
17983}
17984
17985/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17986struct WordBreakingTokenizer<'a> {
17987    input: &'a str,
17988}
17989
17990impl<'a> WordBreakingTokenizer<'a> {
17991    fn new(input: &'a str) -> Self {
17992        Self { input }
17993    }
17994}
17995
17996fn is_char_ideographic(ch: char) -> bool {
17997    use unicode_script::Script::*;
17998    use unicode_script::UnicodeScript;
17999    matches!(ch.script(), Han | Tangut | Yi)
18000}
18001
18002fn is_grapheme_ideographic(text: &str) -> bool {
18003    text.chars().any(is_char_ideographic)
18004}
18005
18006fn is_grapheme_whitespace(text: &str) -> bool {
18007    text.chars().any(|x| x.is_whitespace())
18008}
18009
18010fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18011    text.chars().next().map_or(false, |ch| {
18012        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18013    })
18014}
18015
18016#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18017enum WordBreakToken<'a> {
18018    Word { token: &'a str, grapheme_len: usize },
18019    InlineWhitespace { token: &'a str, grapheme_len: usize },
18020    Newline,
18021}
18022
18023impl<'a> Iterator for WordBreakingTokenizer<'a> {
18024    /// Yields a span, the count of graphemes in the token, and whether it was
18025    /// whitespace. Note that it also breaks at word boundaries.
18026    type Item = WordBreakToken<'a>;
18027
18028    fn next(&mut self) -> Option<Self::Item> {
18029        use unicode_segmentation::UnicodeSegmentation;
18030        if self.input.is_empty() {
18031            return None;
18032        }
18033
18034        let mut iter = self.input.graphemes(true).peekable();
18035        let mut offset = 0;
18036        let mut grapheme_len = 0;
18037        if let Some(first_grapheme) = iter.next() {
18038            let is_newline = first_grapheme == "\n";
18039            let is_whitespace = is_grapheme_whitespace(first_grapheme);
18040            offset += first_grapheme.len();
18041            grapheme_len += 1;
18042            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18043                if let Some(grapheme) = iter.peek().copied() {
18044                    if should_stay_with_preceding_ideograph(grapheme) {
18045                        offset += grapheme.len();
18046                        grapheme_len += 1;
18047                    }
18048                }
18049            } else {
18050                let mut words = self.input[offset..].split_word_bound_indices().peekable();
18051                let mut next_word_bound = words.peek().copied();
18052                if next_word_bound.map_or(false, |(i, _)| i == 0) {
18053                    next_word_bound = words.next();
18054                }
18055                while let Some(grapheme) = iter.peek().copied() {
18056                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
18057                        break;
18058                    };
18059                    if is_grapheme_whitespace(grapheme) != is_whitespace
18060                        || (grapheme == "\n") != is_newline
18061                    {
18062                        break;
18063                    };
18064                    offset += grapheme.len();
18065                    grapheme_len += 1;
18066                    iter.next();
18067                }
18068            }
18069            let token = &self.input[..offset];
18070            self.input = &self.input[offset..];
18071            if token == "\n" {
18072                Some(WordBreakToken::Newline)
18073            } else if is_whitespace {
18074                Some(WordBreakToken::InlineWhitespace {
18075                    token,
18076                    grapheme_len,
18077                })
18078            } else {
18079                Some(WordBreakToken::Word {
18080                    token,
18081                    grapheme_len,
18082                })
18083            }
18084        } else {
18085            None
18086        }
18087    }
18088}
18089
18090#[test]
18091fn test_word_breaking_tokenizer() {
18092    let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18093        ("", &[]),
18094        ("  ", &[whitespace("  ", 2)]),
18095        ("Ʒ", &[word("Ʒ", 1)]),
18096        ("Ǽ", &[word("Ǽ", 1)]),
18097        ("", &[word("", 1)]),
18098        ("⋑⋑", &[word("⋑⋑", 2)]),
18099        (
18100            "原理,进而",
18101            &[word("", 1), word("理,", 2), word("", 1), word("", 1)],
18102        ),
18103        (
18104            "hello world",
18105            &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18106        ),
18107        (
18108            "hello, world",
18109            &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18110        ),
18111        (
18112            "  hello world",
18113            &[
18114                whitespace("  ", 2),
18115                word("hello", 5),
18116                whitespace(" ", 1),
18117                word("world", 5),
18118            ],
18119        ),
18120        (
18121            "这是什么 \n 钢笔",
18122            &[
18123                word("", 1),
18124                word("", 1),
18125                word("", 1),
18126                word("", 1),
18127                whitespace(" ", 1),
18128                newline(),
18129                whitespace(" ", 1),
18130                word("", 1),
18131                word("", 1),
18132            ],
18133        ),
18134        (" mutton", &[whitespace("", 1), word("mutton", 6)]),
18135    ];
18136
18137    fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18138        WordBreakToken::Word {
18139            token,
18140            grapheme_len,
18141        }
18142    }
18143
18144    fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18145        WordBreakToken::InlineWhitespace {
18146            token,
18147            grapheme_len,
18148        }
18149    }
18150
18151    fn newline() -> WordBreakToken<'static> {
18152        WordBreakToken::Newline
18153    }
18154
18155    for (input, result) in tests {
18156        assert_eq!(
18157            WordBreakingTokenizer::new(input)
18158                .collect::<Vec<_>>()
18159                .as_slice(),
18160            *result,
18161        );
18162    }
18163}
18164
18165fn wrap_with_prefix(
18166    line_prefix: String,
18167    unwrapped_text: String,
18168    wrap_column: usize,
18169    tab_size: NonZeroU32,
18170    preserve_existing_whitespace: bool,
18171) -> String {
18172    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18173    let mut wrapped_text = String::new();
18174    let mut current_line = line_prefix.clone();
18175
18176    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18177    let mut current_line_len = line_prefix_len;
18178    let mut in_whitespace = false;
18179    for token in tokenizer {
18180        let have_preceding_whitespace = in_whitespace;
18181        match token {
18182            WordBreakToken::Word {
18183                token,
18184                grapheme_len,
18185            } => {
18186                in_whitespace = false;
18187                if current_line_len + grapheme_len > wrap_column
18188                    && current_line_len != line_prefix_len
18189                {
18190                    wrapped_text.push_str(current_line.trim_end());
18191                    wrapped_text.push('\n');
18192                    current_line.truncate(line_prefix.len());
18193                    current_line_len = line_prefix_len;
18194                }
18195                current_line.push_str(token);
18196                current_line_len += grapheme_len;
18197            }
18198            WordBreakToken::InlineWhitespace {
18199                mut token,
18200                mut grapheme_len,
18201            } => {
18202                in_whitespace = true;
18203                if have_preceding_whitespace && !preserve_existing_whitespace {
18204                    continue;
18205                }
18206                if !preserve_existing_whitespace {
18207                    token = " ";
18208                    grapheme_len = 1;
18209                }
18210                if current_line_len + grapheme_len > wrap_column {
18211                    wrapped_text.push_str(current_line.trim_end());
18212                    wrapped_text.push('\n');
18213                    current_line.truncate(line_prefix.len());
18214                    current_line_len = line_prefix_len;
18215                } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18216                    current_line.push_str(token);
18217                    current_line_len += grapheme_len;
18218                }
18219            }
18220            WordBreakToken::Newline => {
18221                in_whitespace = true;
18222                if preserve_existing_whitespace {
18223                    wrapped_text.push_str(current_line.trim_end());
18224                    wrapped_text.push('\n');
18225                    current_line.truncate(line_prefix.len());
18226                    current_line_len = line_prefix_len;
18227                } else if have_preceding_whitespace {
18228                    continue;
18229                } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18230                {
18231                    wrapped_text.push_str(current_line.trim_end());
18232                    wrapped_text.push('\n');
18233                    current_line.truncate(line_prefix.len());
18234                    current_line_len = line_prefix_len;
18235                } else if current_line_len != line_prefix_len {
18236                    current_line.push(' ');
18237                    current_line_len += 1;
18238                }
18239            }
18240        }
18241    }
18242
18243    if !current_line.is_empty() {
18244        wrapped_text.push_str(&current_line);
18245    }
18246    wrapped_text
18247}
18248
18249#[test]
18250fn test_wrap_with_prefix() {
18251    assert_eq!(
18252        wrap_with_prefix(
18253            "# ".to_string(),
18254            "abcdefg".to_string(),
18255            4,
18256            NonZeroU32::new(4).unwrap(),
18257            false,
18258        ),
18259        "# abcdefg"
18260    );
18261    assert_eq!(
18262        wrap_with_prefix(
18263            "".to_string(),
18264            "\thello world".to_string(),
18265            8,
18266            NonZeroU32::new(4).unwrap(),
18267            false,
18268        ),
18269        "hello\nworld"
18270    );
18271    assert_eq!(
18272        wrap_with_prefix(
18273            "// ".to_string(),
18274            "xx \nyy zz aa bb cc".to_string(),
18275            12,
18276            NonZeroU32::new(4).unwrap(),
18277            false,
18278        ),
18279        "// xx yy zz\n// aa bb cc"
18280    );
18281    assert_eq!(
18282        wrap_with_prefix(
18283            String::new(),
18284            "这是什么 \n 钢笔".to_string(),
18285            3,
18286            NonZeroU32::new(4).unwrap(),
18287            false,
18288        ),
18289        "这是什\n么 钢\n"
18290    );
18291}
18292
18293pub trait CollaborationHub {
18294    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18295    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18296    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18297}
18298
18299impl CollaborationHub for Entity<Project> {
18300    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18301        self.read(cx).collaborators()
18302    }
18303
18304    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18305        self.read(cx).user_store().read(cx).participant_indices()
18306    }
18307
18308    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18309        let this = self.read(cx);
18310        let user_ids = this.collaborators().values().map(|c| c.user_id);
18311        this.user_store().read_with(cx, |user_store, cx| {
18312            user_store.participant_names(user_ids, cx)
18313        })
18314    }
18315}
18316
18317pub trait SemanticsProvider {
18318    fn hover(
18319        &self,
18320        buffer: &Entity<Buffer>,
18321        position: text::Anchor,
18322        cx: &mut App,
18323    ) -> Option<Task<Vec<project::Hover>>>;
18324
18325    fn inlay_hints(
18326        &self,
18327        buffer_handle: Entity<Buffer>,
18328        range: Range<text::Anchor>,
18329        cx: &mut App,
18330    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18331
18332    fn resolve_inlay_hint(
18333        &self,
18334        hint: InlayHint,
18335        buffer_handle: Entity<Buffer>,
18336        server_id: LanguageServerId,
18337        cx: &mut App,
18338    ) -> Option<Task<anyhow::Result<InlayHint>>>;
18339
18340    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18341
18342    fn document_highlights(
18343        &self,
18344        buffer: &Entity<Buffer>,
18345        position: text::Anchor,
18346        cx: &mut App,
18347    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18348
18349    fn definitions(
18350        &self,
18351        buffer: &Entity<Buffer>,
18352        position: text::Anchor,
18353        kind: GotoDefinitionKind,
18354        cx: &mut App,
18355    ) -> Option<Task<Result<Vec<LocationLink>>>>;
18356
18357    fn range_for_rename(
18358        &self,
18359        buffer: &Entity<Buffer>,
18360        position: text::Anchor,
18361        cx: &mut App,
18362    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18363
18364    fn perform_rename(
18365        &self,
18366        buffer: &Entity<Buffer>,
18367        position: text::Anchor,
18368        new_name: String,
18369        cx: &mut App,
18370    ) -> Option<Task<Result<ProjectTransaction>>>;
18371}
18372
18373pub trait CompletionProvider {
18374    fn completions(
18375        &self,
18376        excerpt_id: ExcerptId,
18377        buffer: &Entity<Buffer>,
18378        buffer_position: text::Anchor,
18379        trigger: CompletionContext,
18380        window: &mut Window,
18381        cx: &mut Context<Editor>,
18382    ) -> Task<Result<Option<Vec<Completion>>>>;
18383
18384    fn resolve_completions(
18385        &self,
18386        buffer: Entity<Buffer>,
18387        completion_indices: Vec<usize>,
18388        completions: Rc<RefCell<Box<[Completion]>>>,
18389        cx: &mut Context<Editor>,
18390    ) -> Task<Result<bool>>;
18391
18392    fn apply_additional_edits_for_completion(
18393        &self,
18394        _buffer: Entity<Buffer>,
18395        _completions: Rc<RefCell<Box<[Completion]>>>,
18396        _completion_index: usize,
18397        _push_to_history: bool,
18398        _cx: &mut Context<Editor>,
18399    ) -> Task<Result<Option<language::Transaction>>> {
18400        Task::ready(Ok(None))
18401    }
18402
18403    fn is_completion_trigger(
18404        &self,
18405        buffer: &Entity<Buffer>,
18406        position: language::Anchor,
18407        text: &str,
18408        trigger_in_words: bool,
18409        cx: &mut Context<Editor>,
18410    ) -> bool;
18411
18412    fn sort_completions(&self) -> bool {
18413        true
18414    }
18415
18416    fn filter_completions(&self) -> bool {
18417        true
18418    }
18419}
18420
18421pub trait CodeActionProvider {
18422    fn id(&self) -> Arc<str>;
18423
18424    fn code_actions(
18425        &self,
18426        buffer: &Entity<Buffer>,
18427        range: Range<text::Anchor>,
18428        window: &mut Window,
18429        cx: &mut App,
18430    ) -> Task<Result<Vec<CodeAction>>>;
18431
18432    fn apply_code_action(
18433        &self,
18434        buffer_handle: Entity<Buffer>,
18435        action: CodeAction,
18436        excerpt_id: ExcerptId,
18437        push_to_history: bool,
18438        window: &mut Window,
18439        cx: &mut App,
18440    ) -> Task<Result<ProjectTransaction>>;
18441}
18442
18443impl CodeActionProvider for Entity<Project> {
18444    fn id(&self) -> Arc<str> {
18445        "project".into()
18446    }
18447
18448    fn code_actions(
18449        &self,
18450        buffer: &Entity<Buffer>,
18451        range: Range<text::Anchor>,
18452        _window: &mut Window,
18453        cx: &mut App,
18454    ) -> Task<Result<Vec<CodeAction>>> {
18455        self.update(cx, |project, cx| {
18456            let code_lens = project.code_lens(buffer, range.clone(), cx);
18457            let code_actions = project.code_actions(buffer, range, None, cx);
18458            cx.background_spawn(async move {
18459                let (code_lens, code_actions) = join(code_lens, code_actions).await;
18460                Ok(code_lens
18461                    .context("code lens fetch")?
18462                    .into_iter()
18463                    .chain(code_actions.context("code action fetch")?)
18464                    .collect())
18465            })
18466        })
18467    }
18468
18469    fn apply_code_action(
18470        &self,
18471        buffer_handle: Entity<Buffer>,
18472        action: CodeAction,
18473        _excerpt_id: ExcerptId,
18474        push_to_history: bool,
18475        _window: &mut Window,
18476        cx: &mut App,
18477    ) -> Task<Result<ProjectTransaction>> {
18478        self.update(cx, |project, cx| {
18479            project.apply_code_action(buffer_handle, action, push_to_history, cx)
18480        })
18481    }
18482}
18483
18484fn snippet_completions(
18485    project: &Project,
18486    buffer: &Entity<Buffer>,
18487    buffer_position: text::Anchor,
18488    cx: &mut App,
18489) -> Task<Result<Vec<Completion>>> {
18490    let language = buffer.read(cx).language_at(buffer_position);
18491    let language_name = language.as_ref().map(|language| language.lsp_id());
18492    let snippet_store = project.snippets().read(cx);
18493    let snippets = snippet_store.snippets_for(language_name, cx);
18494
18495    if snippets.is_empty() {
18496        return Task::ready(Ok(vec![]));
18497    }
18498    let snapshot = buffer.read(cx).text_snapshot();
18499    let chars: String = snapshot
18500        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18501        .collect();
18502
18503    let scope = language.map(|language| language.default_scope());
18504    let executor = cx.background_executor().clone();
18505
18506    cx.background_spawn(async move {
18507        let classifier = CharClassifier::new(scope).for_completion(true);
18508        let mut last_word = chars
18509            .chars()
18510            .take_while(|c| classifier.is_word(*c))
18511            .collect::<String>();
18512        last_word = last_word.chars().rev().collect();
18513
18514        if last_word.is_empty() {
18515            return Ok(vec![]);
18516        }
18517
18518        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18519        let to_lsp = |point: &text::Anchor| {
18520            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18521            point_to_lsp(end)
18522        };
18523        let lsp_end = to_lsp(&buffer_position);
18524
18525        let candidates = snippets
18526            .iter()
18527            .enumerate()
18528            .flat_map(|(ix, snippet)| {
18529                snippet
18530                    .prefix
18531                    .iter()
18532                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18533            })
18534            .collect::<Vec<StringMatchCandidate>>();
18535
18536        let mut matches = fuzzy::match_strings(
18537            &candidates,
18538            &last_word,
18539            last_word.chars().any(|c| c.is_uppercase()),
18540            100,
18541            &Default::default(),
18542            executor,
18543        )
18544        .await;
18545
18546        // Remove all candidates where the query's start does not match the start of any word in the candidate
18547        if let Some(query_start) = last_word.chars().next() {
18548            matches.retain(|string_match| {
18549                split_words(&string_match.string).any(|word| {
18550                    // Check that the first codepoint of the word as lowercase matches the first
18551                    // codepoint of the query as lowercase
18552                    word.chars()
18553                        .flat_map(|codepoint| codepoint.to_lowercase())
18554                        .zip(query_start.to_lowercase())
18555                        .all(|(word_cp, query_cp)| word_cp == query_cp)
18556                })
18557            });
18558        }
18559
18560        let matched_strings = matches
18561            .into_iter()
18562            .map(|m| m.string)
18563            .collect::<HashSet<_>>();
18564
18565        let result: Vec<Completion> = snippets
18566            .into_iter()
18567            .filter_map(|snippet| {
18568                let matching_prefix = snippet
18569                    .prefix
18570                    .iter()
18571                    .find(|prefix| matched_strings.contains(*prefix))?;
18572                let start = as_offset - last_word.len();
18573                let start = snapshot.anchor_before(start);
18574                let range = start..buffer_position;
18575                let lsp_start = to_lsp(&start);
18576                let lsp_range = lsp::Range {
18577                    start: lsp_start,
18578                    end: lsp_end,
18579                };
18580                Some(Completion {
18581                    old_range: range,
18582                    new_text: snippet.body.clone(),
18583                    source: CompletionSource::Lsp {
18584                        server_id: LanguageServerId(usize::MAX),
18585                        resolved: true,
18586                        lsp_completion: Box::new(lsp::CompletionItem {
18587                            label: snippet.prefix.first().unwrap().clone(),
18588                            kind: Some(CompletionItemKind::SNIPPET),
18589                            label_details: snippet.description.as_ref().map(|description| {
18590                                lsp::CompletionItemLabelDetails {
18591                                    detail: Some(description.clone()),
18592                                    description: None,
18593                                }
18594                            }),
18595                            insert_text_format: Some(InsertTextFormat::SNIPPET),
18596                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18597                                lsp::InsertReplaceEdit {
18598                                    new_text: snippet.body.clone(),
18599                                    insert: lsp_range,
18600                                    replace: lsp_range,
18601                                },
18602                            )),
18603                            filter_text: Some(snippet.body.clone()),
18604                            sort_text: Some(char::MAX.to_string()),
18605                            ..lsp::CompletionItem::default()
18606                        }),
18607                        lsp_defaults: None,
18608                    },
18609                    label: CodeLabel {
18610                        text: matching_prefix.clone(),
18611                        runs: Vec::new(),
18612                        filter_range: 0..matching_prefix.len(),
18613                    },
18614                    icon_path: None,
18615                    documentation: snippet
18616                        .description
18617                        .clone()
18618                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
18619                    confirm: None,
18620                })
18621            })
18622            .collect();
18623
18624        Ok(result)
18625    })
18626}
18627
18628impl CompletionProvider for Entity<Project> {
18629    fn completions(
18630        &self,
18631        _excerpt_id: ExcerptId,
18632        buffer: &Entity<Buffer>,
18633        buffer_position: text::Anchor,
18634        options: CompletionContext,
18635        _window: &mut Window,
18636        cx: &mut Context<Editor>,
18637    ) -> Task<Result<Option<Vec<Completion>>>> {
18638        self.update(cx, |project, cx| {
18639            let snippets = snippet_completions(project, buffer, buffer_position, cx);
18640            let project_completions = project.completions(buffer, buffer_position, options, cx);
18641            cx.background_spawn(async move {
18642                let snippets_completions = snippets.await?;
18643                match project_completions.await? {
18644                    Some(mut completions) => {
18645                        completions.extend(snippets_completions);
18646                        Ok(Some(completions))
18647                    }
18648                    None => {
18649                        if snippets_completions.is_empty() {
18650                            Ok(None)
18651                        } else {
18652                            Ok(Some(snippets_completions))
18653                        }
18654                    }
18655                }
18656            })
18657        })
18658    }
18659
18660    fn resolve_completions(
18661        &self,
18662        buffer: Entity<Buffer>,
18663        completion_indices: Vec<usize>,
18664        completions: Rc<RefCell<Box<[Completion]>>>,
18665        cx: &mut Context<Editor>,
18666    ) -> Task<Result<bool>> {
18667        self.update(cx, |project, cx| {
18668            project.lsp_store().update(cx, |lsp_store, cx| {
18669                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18670            })
18671        })
18672    }
18673
18674    fn apply_additional_edits_for_completion(
18675        &self,
18676        buffer: Entity<Buffer>,
18677        completions: Rc<RefCell<Box<[Completion]>>>,
18678        completion_index: usize,
18679        push_to_history: bool,
18680        cx: &mut Context<Editor>,
18681    ) -> Task<Result<Option<language::Transaction>>> {
18682        self.update(cx, |project, cx| {
18683            project.lsp_store().update(cx, |lsp_store, cx| {
18684                lsp_store.apply_additional_edits_for_completion(
18685                    buffer,
18686                    completions,
18687                    completion_index,
18688                    push_to_history,
18689                    cx,
18690                )
18691            })
18692        })
18693    }
18694
18695    fn is_completion_trigger(
18696        &self,
18697        buffer: &Entity<Buffer>,
18698        position: language::Anchor,
18699        text: &str,
18700        trigger_in_words: bool,
18701        cx: &mut Context<Editor>,
18702    ) -> bool {
18703        let mut chars = text.chars();
18704        let char = if let Some(char) = chars.next() {
18705            char
18706        } else {
18707            return false;
18708        };
18709        if chars.next().is_some() {
18710            return false;
18711        }
18712
18713        let buffer = buffer.read(cx);
18714        let snapshot = buffer.snapshot();
18715        if !snapshot.settings_at(position, cx).show_completions_on_input {
18716            return false;
18717        }
18718        let classifier = snapshot.char_classifier_at(position).for_completion(true);
18719        if trigger_in_words && classifier.is_word(char) {
18720            return true;
18721        }
18722
18723        buffer.completion_triggers().contains(text)
18724    }
18725}
18726
18727impl SemanticsProvider for Entity<Project> {
18728    fn hover(
18729        &self,
18730        buffer: &Entity<Buffer>,
18731        position: text::Anchor,
18732        cx: &mut App,
18733    ) -> Option<Task<Vec<project::Hover>>> {
18734        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18735    }
18736
18737    fn document_highlights(
18738        &self,
18739        buffer: &Entity<Buffer>,
18740        position: text::Anchor,
18741        cx: &mut App,
18742    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18743        Some(self.update(cx, |project, cx| {
18744            project.document_highlights(buffer, position, cx)
18745        }))
18746    }
18747
18748    fn definitions(
18749        &self,
18750        buffer: &Entity<Buffer>,
18751        position: text::Anchor,
18752        kind: GotoDefinitionKind,
18753        cx: &mut App,
18754    ) -> Option<Task<Result<Vec<LocationLink>>>> {
18755        Some(self.update(cx, |project, cx| match kind {
18756            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18757            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18758            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18759            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18760        }))
18761    }
18762
18763    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18764        // TODO: make this work for remote projects
18765        self.update(cx, |this, cx| {
18766            buffer.update(cx, |buffer, cx| {
18767                this.any_language_server_supports_inlay_hints(buffer, cx)
18768            })
18769        })
18770    }
18771
18772    fn inlay_hints(
18773        &self,
18774        buffer_handle: Entity<Buffer>,
18775        range: Range<text::Anchor>,
18776        cx: &mut App,
18777    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18778        Some(self.update(cx, |project, cx| {
18779            project.inlay_hints(buffer_handle, range, cx)
18780        }))
18781    }
18782
18783    fn resolve_inlay_hint(
18784        &self,
18785        hint: InlayHint,
18786        buffer_handle: Entity<Buffer>,
18787        server_id: LanguageServerId,
18788        cx: &mut App,
18789    ) -> Option<Task<anyhow::Result<InlayHint>>> {
18790        Some(self.update(cx, |project, cx| {
18791            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18792        }))
18793    }
18794
18795    fn range_for_rename(
18796        &self,
18797        buffer: &Entity<Buffer>,
18798        position: text::Anchor,
18799        cx: &mut App,
18800    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18801        Some(self.update(cx, |project, cx| {
18802            let buffer = buffer.clone();
18803            let task = project.prepare_rename(buffer.clone(), position, cx);
18804            cx.spawn(async move |_, cx| {
18805                Ok(match task.await? {
18806                    PrepareRenameResponse::Success(range) => Some(range),
18807                    PrepareRenameResponse::InvalidPosition => None,
18808                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18809                        // Fallback on using TreeSitter info to determine identifier range
18810                        buffer.update(cx, |buffer, _| {
18811                            let snapshot = buffer.snapshot();
18812                            let (range, kind) = snapshot.surrounding_word(position);
18813                            if kind != Some(CharKind::Word) {
18814                                return None;
18815                            }
18816                            Some(
18817                                snapshot.anchor_before(range.start)
18818                                    ..snapshot.anchor_after(range.end),
18819                            )
18820                        })?
18821                    }
18822                })
18823            })
18824        }))
18825    }
18826
18827    fn perform_rename(
18828        &self,
18829        buffer: &Entity<Buffer>,
18830        position: text::Anchor,
18831        new_name: String,
18832        cx: &mut App,
18833    ) -> Option<Task<Result<ProjectTransaction>>> {
18834        Some(self.update(cx, |project, cx| {
18835            project.perform_rename(buffer.clone(), position, new_name, cx)
18836        }))
18837    }
18838}
18839
18840fn inlay_hint_settings(
18841    location: Anchor,
18842    snapshot: &MultiBufferSnapshot,
18843    cx: &mut Context<Editor>,
18844) -> InlayHintSettings {
18845    let file = snapshot.file_at(location);
18846    let language = snapshot.language_at(location).map(|l| l.name());
18847    language_settings(language, file, cx).inlay_hints
18848}
18849
18850fn consume_contiguous_rows(
18851    contiguous_row_selections: &mut Vec<Selection<Point>>,
18852    selection: &Selection<Point>,
18853    display_map: &DisplaySnapshot,
18854    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18855) -> (MultiBufferRow, MultiBufferRow) {
18856    contiguous_row_selections.push(selection.clone());
18857    let start_row = MultiBufferRow(selection.start.row);
18858    let mut end_row = ending_row(selection, display_map);
18859
18860    while let Some(next_selection) = selections.peek() {
18861        if next_selection.start.row <= end_row.0 {
18862            end_row = ending_row(next_selection, display_map);
18863            contiguous_row_selections.push(selections.next().unwrap().clone());
18864        } else {
18865            break;
18866        }
18867    }
18868    (start_row, end_row)
18869}
18870
18871fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18872    if next_selection.end.column > 0 || next_selection.is_empty() {
18873        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18874    } else {
18875        MultiBufferRow(next_selection.end.row)
18876    }
18877}
18878
18879impl EditorSnapshot {
18880    pub fn remote_selections_in_range<'a>(
18881        &'a self,
18882        range: &'a Range<Anchor>,
18883        collaboration_hub: &dyn CollaborationHub,
18884        cx: &'a App,
18885    ) -> impl 'a + Iterator<Item = RemoteSelection> {
18886        let participant_names = collaboration_hub.user_names(cx);
18887        let participant_indices = collaboration_hub.user_participant_indices(cx);
18888        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18889        let collaborators_by_replica_id = collaborators_by_peer_id
18890            .iter()
18891            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18892            .collect::<HashMap<_, _>>();
18893        self.buffer_snapshot
18894            .selections_in_range(range, false)
18895            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18896                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18897                let participant_index = participant_indices.get(&collaborator.user_id).copied();
18898                let user_name = participant_names.get(&collaborator.user_id).cloned();
18899                Some(RemoteSelection {
18900                    replica_id,
18901                    selection,
18902                    cursor_shape,
18903                    line_mode,
18904                    participant_index,
18905                    peer_id: collaborator.peer_id,
18906                    user_name,
18907                })
18908            })
18909    }
18910
18911    pub fn hunks_for_ranges(
18912        &self,
18913        ranges: impl IntoIterator<Item = Range<Point>>,
18914    ) -> Vec<MultiBufferDiffHunk> {
18915        let mut hunks = Vec::new();
18916        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18917            HashMap::default();
18918        for query_range in ranges {
18919            let query_rows =
18920                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18921            for hunk in self.buffer_snapshot.diff_hunks_in_range(
18922                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18923            ) {
18924                // Include deleted hunks that are adjacent to the query range, because
18925                // otherwise they would be missed.
18926                let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18927                if hunk.status().is_deleted() {
18928                    intersects_range |= hunk.row_range.start == query_rows.end;
18929                    intersects_range |= hunk.row_range.end == query_rows.start;
18930                }
18931                if intersects_range {
18932                    if !processed_buffer_rows
18933                        .entry(hunk.buffer_id)
18934                        .or_default()
18935                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18936                    {
18937                        continue;
18938                    }
18939                    hunks.push(hunk);
18940                }
18941            }
18942        }
18943
18944        hunks
18945    }
18946
18947    fn display_diff_hunks_for_rows<'a>(
18948        &'a self,
18949        display_rows: Range<DisplayRow>,
18950        folded_buffers: &'a HashSet<BufferId>,
18951    ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18952        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18953        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18954
18955        self.buffer_snapshot
18956            .diff_hunks_in_range(buffer_start..buffer_end)
18957            .filter_map(|hunk| {
18958                if folded_buffers.contains(&hunk.buffer_id) {
18959                    return None;
18960                }
18961
18962                let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18963                let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18964
18965                let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18966                let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18967
18968                let display_hunk = if hunk_display_start.column() != 0 {
18969                    DisplayDiffHunk::Folded {
18970                        display_row: hunk_display_start.row(),
18971                    }
18972                } else {
18973                    let mut end_row = hunk_display_end.row();
18974                    if hunk_display_end.column() > 0 {
18975                        end_row.0 += 1;
18976                    }
18977                    let is_created_file = hunk.is_created_file();
18978                    DisplayDiffHunk::Unfolded {
18979                        status: hunk.status(),
18980                        diff_base_byte_range: hunk.diff_base_byte_range,
18981                        display_row_range: hunk_display_start.row()..end_row,
18982                        multi_buffer_range: Anchor::range_in_buffer(
18983                            hunk.excerpt_id,
18984                            hunk.buffer_id,
18985                            hunk.buffer_range,
18986                        ),
18987                        is_created_file,
18988                    }
18989                };
18990
18991                Some(display_hunk)
18992            })
18993    }
18994
18995    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18996        self.display_snapshot.buffer_snapshot.language_at(position)
18997    }
18998
18999    pub fn is_focused(&self) -> bool {
19000        self.is_focused
19001    }
19002
19003    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19004        self.placeholder_text.as_ref()
19005    }
19006
19007    pub fn scroll_position(&self) -> gpui::Point<f32> {
19008        self.scroll_anchor.scroll_position(&self.display_snapshot)
19009    }
19010
19011    fn gutter_dimensions(
19012        &self,
19013        font_id: FontId,
19014        font_size: Pixels,
19015        max_line_number_width: Pixels,
19016        cx: &App,
19017    ) -> Option<GutterDimensions> {
19018        if !self.show_gutter {
19019            return None;
19020        }
19021
19022        let descent = cx.text_system().descent(font_id, font_size);
19023        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19024        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19025
19026        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19027            matches!(
19028                ProjectSettings::get_global(cx).git.git_gutter,
19029                Some(GitGutterSetting::TrackedFiles)
19030            )
19031        });
19032        let gutter_settings = EditorSettings::get_global(cx).gutter;
19033        let show_line_numbers = self
19034            .show_line_numbers
19035            .unwrap_or(gutter_settings.line_numbers);
19036        let line_gutter_width = if show_line_numbers {
19037            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19038            let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19039            max_line_number_width.max(min_width_for_number_on_gutter)
19040        } else {
19041            0.0.into()
19042        };
19043
19044        let show_code_actions = self
19045            .show_code_actions
19046            .unwrap_or(gutter_settings.code_actions);
19047
19048        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19049        let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19050
19051        let git_blame_entries_width =
19052            self.git_blame_gutter_max_author_length
19053                .map(|max_author_length| {
19054                    let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19055                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19056
19057                    /// The number of characters to dedicate to gaps and margins.
19058                    const SPACING_WIDTH: usize = 4;
19059
19060                    let max_char_count = max_author_length.min(renderer.max_author_length())
19061                        + ::git::SHORT_SHA_LENGTH
19062                        + MAX_RELATIVE_TIMESTAMP.len()
19063                        + SPACING_WIDTH;
19064
19065                    em_advance * max_char_count
19066                });
19067
19068        let is_singleton = self.buffer_snapshot.is_singleton();
19069
19070        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19071        left_padding += if !is_singleton {
19072            em_width * 4.0
19073        } else if show_code_actions || show_runnables || show_breakpoints {
19074            em_width * 3.0
19075        } else if show_git_gutter && show_line_numbers {
19076            em_width * 2.0
19077        } else if show_git_gutter || show_line_numbers {
19078            em_width
19079        } else {
19080            px(0.)
19081        };
19082
19083        let shows_folds = is_singleton && gutter_settings.folds;
19084
19085        let right_padding = if shows_folds && show_line_numbers {
19086            em_width * 4.0
19087        } else if shows_folds || (!is_singleton && show_line_numbers) {
19088            em_width * 3.0
19089        } else if show_line_numbers {
19090            em_width
19091        } else {
19092            px(0.)
19093        };
19094
19095        Some(GutterDimensions {
19096            left_padding,
19097            right_padding,
19098            width: line_gutter_width + left_padding + right_padding,
19099            margin: -descent,
19100            git_blame_entries_width,
19101        })
19102    }
19103
19104    pub fn render_crease_toggle(
19105        &self,
19106        buffer_row: MultiBufferRow,
19107        row_contains_cursor: bool,
19108        editor: Entity<Editor>,
19109        window: &mut Window,
19110        cx: &mut App,
19111    ) -> Option<AnyElement> {
19112        let folded = self.is_line_folded(buffer_row);
19113        let mut is_foldable = false;
19114
19115        if let Some(crease) = self
19116            .crease_snapshot
19117            .query_row(buffer_row, &self.buffer_snapshot)
19118        {
19119            is_foldable = true;
19120            match crease {
19121                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19122                    if let Some(render_toggle) = render_toggle {
19123                        let toggle_callback =
19124                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19125                                if folded {
19126                                    editor.update(cx, |editor, cx| {
19127                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
19128                                    });
19129                                } else {
19130                                    editor.update(cx, |editor, cx| {
19131                                        editor.unfold_at(
19132                                            &crate::UnfoldAt { buffer_row },
19133                                            window,
19134                                            cx,
19135                                        )
19136                                    });
19137                                }
19138                            });
19139                        return Some((render_toggle)(
19140                            buffer_row,
19141                            folded,
19142                            toggle_callback,
19143                            window,
19144                            cx,
19145                        ));
19146                    }
19147                }
19148            }
19149        }
19150
19151        is_foldable |= self.starts_indent(buffer_row);
19152
19153        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19154            Some(
19155                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19156                    .toggle_state(folded)
19157                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19158                        if folded {
19159                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
19160                        } else {
19161                            this.fold_at(&FoldAt { buffer_row }, window, cx);
19162                        }
19163                    }))
19164                    .into_any_element(),
19165            )
19166        } else {
19167            None
19168        }
19169    }
19170
19171    pub fn render_crease_trailer(
19172        &self,
19173        buffer_row: MultiBufferRow,
19174        window: &mut Window,
19175        cx: &mut App,
19176    ) -> Option<AnyElement> {
19177        let folded = self.is_line_folded(buffer_row);
19178        if let Crease::Inline { render_trailer, .. } = self
19179            .crease_snapshot
19180            .query_row(buffer_row, &self.buffer_snapshot)?
19181        {
19182            let render_trailer = render_trailer.as_ref()?;
19183            Some(render_trailer(buffer_row, folded, window, cx))
19184        } else {
19185            None
19186        }
19187    }
19188}
19189
19190impl Deref for EditorSnapshot {
19191    type Target = DisplaySnapshot;
19192
19193    fn deref(&self) -> &Self::Target {
19194        &self.display_snapshot
19195    }
19196}
19197
19198#[derive(Clone, Debug, PartialEq, Eq)]
19199pub enum EditorEvent {
19200    InputIgnored {
19201        text: Arc<str>,
19202    },
19203    InputHandled {
19204        utf16_range_to_replace: Option<Range<isize>>,
19205        text: Arc<str>,
19206    },
19207    ExcerptsAdded {
19208        buffer: Entity<Buffer>,
19209        predecessor: ExcerptId,
19210        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19211    },
19212    ExcerptsRemoved {
19213        ids: Vec<ExcerptId>,
19214    },
19215    BufferFoldToggled {
19216        ids: Vec<ExcerptId>,
19217        folded: bool,
19218    },
19219    ExcerptsEdited {
19220        ids: Vec<ExcerptId>,
19221    },
19222    ExcerptsExpanded {
19223        ids: Vec<ExcerptId>,
19224    },
19225    BufferEdited,
19226    Edited {
19227        transaction_id: clock::Lamport,
19228    },
19229    Reparsed(BufferId),
19230    Focused,
19231    FocusedIn,
19232    Blurred,
19233    DirtyChanged,
19234    Saved,
19235    TitleChanged,
19236    DiffBaseChanged,
19237    SelectionsChanged {
19238        local: bool,
19239    },
19240    ScrollPositionChanged {
19241        local: bool,
19242        autoscroll: bool,
19243    },
19244    Closed,
19245    TransactionUndone {
19246        transaction_id: clock::Lamport,
19247    },
19248    TransactionBegun {
19249        transaction_id: clock::Lamport,
19250    },
19251    Reloaded,
19252    CursorShapeChanged,
19253    PushedToNavHistory {
19254        anchor: Anchor,
19255        is_deactivate: bool,
19256    },
19257}
19258
19259impl EventEmitter<EditorEvent> for Editor {}
19260
19261impl Focusable for Editor {
19262    fn focus_handle(&self, _cx: &App) -> FocusHandle {
19263        self.focus_handle.clone()
19264    }
19265}
19266
19267impl Render for Editor {
19268    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19269        let settings = ThemeSettings::get_global(cx);
19270
19271        let mut text_style = match self.mode {
19272            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19273                color: cx.theme().colors().editor_foreground,
19274                font_family: settings.ui_font.family.clone(),
19275                font_features: settings.ui_font.features.clone(),
19276                font_fallbacks: settings.ui_font.fallbacks.clone(),
19277                font_size: rems(0.875).into(),
19278                font_weight: settings.ui_font.weight,
19279                line_height: relative(settings.buffer_line_height.value()),
19280                ..Default::default()
19281            },
19282            EditorMode::Full => TextStyle {
19283                color: cx.theme().colors().editor_foreground,
19284                font_family: settings.buffer_font.family.clone(),
19285                font_features: settings.buffer_font.features.clone(),
19286                font_fallbacks: settings.buffer_font.fallbacks.clone(),
19287                font_size: settings.buffer_font_size(cx).into(),
19288                font_weight: settings.buffer_font.weight,
19289                line_height: relative(settings.buffer_line_height.value()),
19290                ..Default::default()
19291            },
19292        };
19293        if let Some(text_style_refinement) = &self.text_style_refinement {
19294            text_style.refine(text_style_refinement)
19295        }
19296
19297        let background = match self.mode {
19298            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19299            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19300            EditorMode::Full => cx.theme().colors().editor_background,
19301        };
19302
19303        EditorElement::new(
19304            &cx.entity(),
19305            EditorStyle {
19306                background,
19307                local_player: cx.theme().players().local(),
19308                text: text_style,
19309                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19310                syntax: cx.theme().syntax().clone(),
19311                status: cx.theme().status().clone(),
19312                inlay_hints_style: make_inlay_hints_style(cx),
19313                inline_completion_styles: make_suggestion_styles(cx),
19314                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19315            },
19316        )
19317    }
19318}
19319
19320impl EntityInputHandler for Editor {
19321    fn text_for_range(
19322        &mut self,
19323        range_utf16: Range<usize>,
19324        adjusted_range: &mut Option<Range<usize>>,
19325        _: &mut Window,
19326        cx: &mut Context<Self>,
19327    ) -> Option<String> {
19328        let snapshot = self.buffer.read(cx).read(cx);
19329        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19330        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19331        if (start.0..end.0) != range_utf16 {
19332            adjusted_range.replace(start.0..end.0);
19333        }
19334        Some(snapshot.text_for_range(start..end).collect())
19335    }
19336
19337    fn selected_text_range(
19338        &mut self,
19339        ignore_disabled_input: bool,
19340        _: &mut Window,
19341        cx: &mut Context<Self>,
19342    ) -> Option<UTF16Selection> {
19343        // Prevent the IME menu from appearing when holding down an alphabetic key
19344        // while input is disabled.
19345        if !ignore_disabled_input && !self.input_enabled {
19346            return None;
19347        }
19348
19349        let selection = self.selections.newest::<OffsetUtf16>(cx);
19350        let range = selection.range();
19351
19352        Some(UTF16Selection {
19353            range: range.start.0..range.end.0,
19354            reversed: selection.reversed,
19355        })
19356    }
19357
19358    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19359        let snapshot = self.buffer.read(cx).read(cx);
19360        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19361        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19362    }
19363
19364    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19365        self.clear_highlights::<InputComposition>(cx);
19366        self.ime_transaction.take();
19367    }
19368
19369    fn replace_text_in_range(
19370        &mut self,
19371        range_utf16: Option<Range<usize>>,
19372        text: &str,
19373        window: &mut Window,
19374        cx: &mut Context<Self>,
19375    ) {
19376        if !self.input_enabled {
19377            cx.emit(EditorEvent::InputIgnored { text: text.into() });
19378            return;
19379        }
19380
19381        self.transact(window, cx, |this, window, cx| {
19382            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19383                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19384                Some(this.selection_replacement_ranges(range_utf16, cx))
19385            } else {
19386                this.marked_text_ranges(cx)
19387            };
19388
19389            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19390                let newest_selection_id = this.selections.newest_anchor().id;
19391                this.selections
19392                    .all::<OffsetUtf16>(cx)
19393                    .iter()
19394                    .zip(ranges_to_replace.iter())
19395                    .find_map(|(selection, range)| {
19396                        if selection.id == newest_selection_id {
19397                            Some(
19398                                (range.start.0 as isize - selection.head().0 as isize)
19399                                    ..(range.end.0 as isize - selection.head().0 as isize),
19400                            )
19401                        } else {
19402                            None
19403                        }
19404                    })
19405            });
19406
19407            cx.emit(EditorEvent::InputHandled {
19408                utf16_range_to_replace: range_to_replace,
19409                text: text.into(),
19410            });
19411
19412            if let Some(new_selected_ranges) = new_selected_ranges {
19413                this.change_selections(None, window, cx, |selections| {
19414                    selections.select_ranges(new_selected_ranges)
19415                });
19416                this.backspace(&Default::default(), window, cx);
19417            }
19418
19419            this.handle_input(text, window, cx);
19420        });
19421
19422        if let Some(transaction) = self.ime_transaction {
19423            self.buffer.update(cx, |buffer, cx| {
19424                buffer.group_until_transaction(transaction, cx);
19425            });
19426        }
19427
19428        self.unmark_text(window, cx);
19429    }
19430
19431    fn replace_and_mark_text_in_range(
19432        &mut self,
19433        range_utf16: Option<Range<usize>>,
19434        text: &str,
19435        new_selected_range_utf16: Option<Range<usize>>,
19436        window: &mut Window,
19437        cx: &mut Context<Self>,
19438    ) {
19439        if !self.input_enabled {
19440            return;
19441        }
19442
19443        let transaction = self.transact(window, cx, |this, window, cx| {
19444            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19445                let snapshot = this.buffer.read(cx).read(cx);
19446                if let Some(relative_range_utf16) = range_utf16.as_ref() {
19447                    for marked_range in &mut marked_ranges {
19448                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19449                        marked_range.start.0 += relative_range_utf16.start;
19450                        marked_range.start =
19451                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19452                        marked_range.end =
19453                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19454                    }
19455                }
19456                Some(marked_ranges)
19457            } else if let Some(range_utf16) = range_utf16 {
19458                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19459                Some(this.selection_replacement_ranges(range_utf16, cx))
19460            } else {
19461                None
19462            };
19463
19464            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19465                let newest_selection_id = this.selections.newest_anchor().id;
19466                this.selections
19467                    .all::<OffsetUtf16>(cx)
19468                    .iter()
19469                    .zip(ranges_to_replace.iter())
19470                    .find_map(|(selection, range)| {
19471                        if selection.id == newest_selection_id {
19472                            Some(
19473                                (range.start.0 as isize - selection.head().0 as isize)
19474                                    ..(range.end.0 as isize - selection.head().0 as isize),
19475                            )
19476                        } else {
19477                            None
19478                        }
19479                    })
19480            });
19481
19482            cx.emit(EditorEvent::InputHandled {
19483                utf16_range_to_replace: range_to_replace,
19484                text: text.into(),
19485            });
19486
19487            if let Some(ranges) = ranges_to_replace {
19488                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19489            }
19490
19491            let marked_ranges = {
19492                let snapshot = this.buffer.read(cx).read(cx);
19493                this.selections
19494                    .disjoint_anchors()
19495                    .iter()
19496                    .map(|selection| {
19497                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19498                    })
19499                    .collect::<Vec<_>>()
19500            };
19501
19502            if text.is_empty() {
19503                this.unmark_text(window, cx);
19504            } else {
19505                this.highlight_text::<InputComposition>(
19506                    marked_ranges.clone(),
19507                    HighlightStyle {
19508                        underline: Some(UnderlineStyle {
19509                            thickness: px(1.),
19510                            color: None,
19511                            wavy: false,
19512                        }),
19513                        ..Default::default()
19514                    },
19515                    cx,
19516                );
19517            }
19518
19519            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19520            let use_autoclose = this.use_autoclose;
19521            let use_auto_surround = this.use_auto_surround;
19522            this.set_use_autoclose(false);
19523            this.set_use_auto_surround(false);
19524            this.handle_input(text, window, cx);
19525            this.set_use_autoclose(use_autoclose);
19526            this.set_use_auto_surround(use_auto_surround);
19527
19528            if let Some(new_selected_range) = new_selected_range_utf16 {
19529                let snapshot = this.buffer.read(cx).read(cx);
19530                let new_selected_ranges = marked_ranges
19531                    .into_iter()
19532                    .map(|marked_range| {
19533                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19534                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19535                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19536                        snapshot.clip_offset_utf16(new_start, Bias::Left)
19537                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19538                    })
19539                    .collect::<Vec<_>>();
19540
19541                drop(snapshot);
19542                this.change_selections(None, window, cx, |selections| {
19543                    selections.select_ranges(new_selected_ranges)
19544                });
19545            }
19546        });
19547
19548        self.ime_transaction = self.ime_transaction.or(transaction);
19549        if let Some(transaction) = self.ime_transaction {
19550            self.buffer.update(cx, |buffer, cx| {
19551                buffer.group_until_transaction(transaction, cx);
19552            });
19553        }
19554
19555        if self.text_highlights::<InputComposition>(cx).is_none() {
19556            self.ime_transaction.take();
19557        }
19558    }
19559
19560    fn bounds_for_range(
19561        &mut self,
19562        range_utf16: Range<usize>,
19563        element_bounds: gpui::Bounds<Pixels>,
19564        window: &mut Window,
19565        cx: &mut Context<Self>,
19566    ) -> Option<gpui::Bounds<Pixels>> {
19567        let text_layout_details = self.text_layout_details(window);
19568        let gpui::Size {
19569            width: em_width,
19570            height: line_height,
19571        } = self.character_size(window);
19572
19573        let snapshot = self.snapshot(window, cx);
19574        let scroll_position = snapshot.scroll_position();
19575        let scroll_left = scroll_position.x * em_width;
19576
19577        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19578        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19579            + self.gutter_dimensions.width
19580            + self.gutter_dimensions.margin;
19581        let y = line_height * (start.row().as_f32() - scroll_position.y);
19582
19583        Some(Bounds {
19584            origin: element_bounds.origin + point(x, y),
19585            size: size(em_width, line_height),
19586        })
19587    }
19588
19589    fn character_index_for_point(
19590        &mut self,
19591        point: gpui::Point<Pixels>,
19592        _window: &mut Window,
19593        _cx: &mut Context<Self>,
19594    ) -> Option<usize> {
19595        let position_map = self.last_position_map.as_ref()?;
19596        if !position_map.text_hitbox.contains(&point) {
19597            return None;
19598        }
19599        let display_point = position_map.point_for_position(point).previous_valid;
19600        let anchor = position_map
19601            .snapshot
19602            .display_point_to_anchor(display_point, Bias::Left);
19603        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19604        Some(utf16_offset.0)
19605    }
19606}
19607
19608trait SelectionExt {
19609    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19610    fn spanned_rows(
19611        &self,
19612        include_end_if_at_line_start: bool,
19613        map: &DisplaySnapshot,
19614    ) -> Range<MultiBufferRow>;
19615}
19616
19617impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19618    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19619        let start = self
19620            .start
19621            .to_point(&map.buffer_snapshot)
19622            .to_display_point(map);
19623        let end = self
19624            .end
19625            .to_point(&map.buffer_snapshot)
19626            .to_display_point(map);
19627        if self.reversed {
19628            end..start
19629        } else {
19630            start..end
19631        }
19632    }
19633
19634    fn spanned_rows(
19635        &self,
19636        include_end_if_at_line_start: bool,
19637        map: &DisplaySnapshot,
19638    ) -> Range<MultiBufferRow> {
19639        let start = self.start.to_point(&map.buffer_snapshot);
19640        let mut end = self.end.to_point(&map.buffer_snapshot);
19641        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19642            end.row -= 1;
19643        }
19644
19645        let buffer_start = map.prev_line_boundary(start).0;
19646        let buffer_end = map.next_line_boundary(end).0;
19647        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19648    }
19649}
19650
19651impl<T: InvalidationRegion> InvalidationStack<T> {
19652    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19653    where
19654        S: Clone + ToOffset,
19655    {
19656        while let Some(region) = self.last() {
19657            let all_selections_inside_invalidation_ranges =
19658                if selections.len() == region.ranges().len() {
19659                    selections
19660                        .iter()
19661                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19662                        .all(|(selection, invalidation_range)| {
19663                            let head = selection.head().to_offset(buffer);
19664                            invalidation_range.start <= head && invalidation_range.end >= head
19665                        })
19666                } else {
19667                    false
19668                };
19669
19670            if all_selections_inside_invalidation_ranges {
19671                break;
19672            } else {
19673                self.pop();
19674            }
19675        }
19676    }
19677}
19678
19679impl<T> Default for InvalidationStack<T> {
19680    fn default() -> Self {
19681        Self(Default::default())
19682    }
19683}
19684
19685impl<T> Deref for InvalidationStack<T> {
19686    type Target = Vec<T>;
19687
19688    fn deref(&self) -> &Self::Target {
19689        &self.0
19690    }
19691}
19692
19693impl<T> DerefMut for InvalidationStack<T> {
19694    fn deref_mut(&mut self) -> &mut Self::Target {
19695        &mut self.0
19696    }
19697}
19698
19699impl InvalidationRegion for SnippetState {
19700    fn ranges(&self) -> &[Range<Anchor>] {
19701        &self.ranges[self.active_index]
19702    }
19703}
19704
19705pub fn diagnostic_block_renderer(
19706    diagnostic: Diagnostic,
19707    max_message_rows: Option<u8>,
19708    allow_closing: bool,
19709) -> RenderBlock {
19710    let (text_without_backticks, code_ranges) =
19711        highlight_diagnostic_message(&diagnostic, max_message_rows);
19712
19713    Arc::new(move |cx: &mut BlockContext| {
19714        let group_id: SharedString = cx.block_id.to_string().into();
19715
19716        let mut text_style = cx.window.text_style().clone();
19717        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19718        let theme_settings = ThemeSettings::get_global(cx);
19719        text_style.font_family = theme_settings.buffer_font.family.clone();
19720        text_style.font_style = theme_settings.buffer_font.style;
19721        text_style.font_features = theme_settings.buffer_font.features.clone();
19722        text_style.font_weight = theme_settings.buffer_font.weight;
19723
19724        let multi_line_diagnostic = diagnostic.message.contains('\n');
19725
19726        let buttons = |diagnostic: &Diagnostic| {
19727            if multi_line_diagnostic {
19728                v_flex()
19729            } else {
19730                h_flex()
19731            }
19732            .when(allow_closing, |div| {
19733                div.children(diagnostic.is_primary.then(|| {
19734                    IconButton::new("close-block", IconName::XCircle)
19735                        .icon_color(Color::Muted)
19736                        .size(ButtonSize::Compact)
19737                        .style(ButtonStyle::Transparent)
19738                        .visible_on_hover(group_id.clone())
19739                        .on_click(move |_click, window, cx| {
19740                            window.dispatch_action(Box::new(Cancel), cx)
19741                        })
19742                        .tooltip(|window, cx| {
19743                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19744                        })
19745                }))
19746            })
19747            .child(
19748                IconButton::new("copy-block", IconName::Copy)
19749                    .icon_color(Color::Muted)
19750                    .size(ButtonSize::Compact)
19751                    .style(ButtonStyle::Transparent)
19752                    .visible_on_hover(group_id.clone())
19753                    .on_click({
19754                        let message = diagnostic.message.clone();
19755                        move |_click, _, cx| {
19756                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19757                        }
19758                    })
19759                    .tooltip(Tooltip::text("Copy diagnostic message")),
19760            )
19761        };
19762
19763        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19764            AvailableSpace::min_size(),
19765            cx.window,
19766            cx.app,
19767        );
19768
19769        h_flex()
19770            .id(cx.block_id)
19771            .group(group_id.clone())
19772            .relative()
19773            .size_full()
19774            .block_mouse_down()
19775            .pl(cx.gutter_dimensions.width)
19776            .w(cx.max_width - cx.gutter_dimensions.full_width())
19777            .child(
19778                div()
19779                    .flex()
19780                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19781                    .flex_shrink(),
19782            )
19783            .child(buttons(&diagnostic))
19784            .child(div().flex().flex_shrink_0().child(
19785                StyledText::new(text_without_backticks.clone()).with_default_highlights(
19786                    &text_style,
19787                    code_ranges.iter().map(|range| {
19788                        (
19789                            range.clone(),
19790                            HighlightStyle {
19791                                font_weight: Some(FontWeight::BOLD),
19792                                ..Default::default()
19793                            },
19794                        )
19795                    }),
19796                ),
19797            ))
19798            .into_any_element()
19799    })
19800}
19801
19802fn inline_completion_edit_text(
19803    current_snapshot: &BufferSnapshot,
19804    edits: &[(Range<Anchor>, String)],
19805    edit_preview: &EditPreview,
19806    include_deletions: bool,
19807    cx: &App,
19808) -> HighlightedText {
19809    let edits = edits
19810        .iter()
19811        .map(|(anchor, text)| {
19812            (
19813                anchor.start.text_anchor..anchor.end.text_anchor,
19814                text.clone(),
19815            )
19816        })
19817        .collect::<Vec<_>>();
19818
19819    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19820}
19821
19822pub fn highlight_diagnostic_message(
19823    diagnostic: &Diagnostic,
19824    mut max_message_rows: Option<u8>,
19825) -> (SharedString, Vec<Range<usize>>) {
19826    let mut text_without_backticks = String::new();
19827    let mut code_ranges = Vec::new();
19828
19829    if let Some(source) = &diagnostic.source {
19830        text_without_backticks.push_str(source);
19831        code_ranges.push(0..source.len());
19832        text_without_backticks.push_str(": ");
19833    }
19834
19835    let mut prev_offset = 0;
19836    let mut in_code_block = false;
19837    let has_row_limit = max_message_rows.is_some();
19838    let mut newline_indices = diagnostic
19839        .message
19840        .match_indices('\n')
19841        .filter(|_| has_row_limit)
19842        .map(|(ix, _)| ix)
19843        .fuse()
19844        .peekable();
19845
19846    for (quote_ix, _) in diagnostic
19847        .message
19848        .match_indices('`')
19849        .chain([(diagnostic.message.len(), "")])
19850    {
19851        let mut first_newline_ix = None;
19852        let mut last_newline_ix = None;
19853        while let Some(newline_ix) = newline_indices.peek() {
19854            if *newline_ix < quote_ix {
19855                if first_newline_ix.is_none() {
19856                    first_newline_ix = Some(*newline_ix);
19857                }
19858                last_newline_ix = Some(*newline_ix);
19859
19860                if let Some(rows_left) = &mut max_message_rows {
19861                    if *rows_left == 0 {
19862                        break;
19863                    } else {
19864                        *rows_left -= 1;
19865                    }
19866                }
19867                let _ = newline_indices.next();
19868            } else {
19869                break;
19870            }
19871        }
19872        let prev_len = text_without_backticks.len();
19873        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19874        text_without_backticks.push_str(new_text);
19875        if in_code_block {
19876            code_ranges.push(prev_len..text_without_backticks.len());
19877        }
19878        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19879        in_code_block = !in_code_block;
19880        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19881            text_without_backticks.push_str("...");
19882            break;
19883        }
19884    }
19885
19886    (text_without_backticks.into(), code_ranges)
19887}
19888
19889fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19890    match severity {
19891        DiagnosticSeverity::ERROR => colors.error,
19892        DiagnosticSeverity::WARNING => colors.warning,
19893        DiagnosticSeverity::INFORMATION => colors.info,
19894        DiagnosticSeverity::HINT => colors.info,
19895        _ => colors.ignored,
19896    }
19897}
19898
19899pub fn styled_runs_for_code_label<'a>(
19900    label: &'a CodeLabel,
19901    syntax_theme: &'a theme::SyntaxTheme,
19902) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19903    let fade_out = HighlightStyle {
19904        fade_out: Some(0.35),
19905        ..Default::default()
19906    };
19907
19908    let mut prev_end = label.filter_range.end;
19909    label
19910        .runs
19911        .iter()
19912        .enumerate()
19913        .flat_map(move |(ix, (range, highlight_id))| {
19914            let style = if let Some(style) = highlight_id.style(syntax_theme) {
19915                style
19916            } else {
19917                return Default::default();
19918            };
19919            let mut muted_style = style;
19920            muted_style.highlight(fade_out);
19921
19922            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19923            if range.start >= label.filter_range.end {
19924                if range.start > prev_end {
19925                    runs.push((prev_end..range.start, fade_out));
19926                }
19927                runs.push((range.clone(), muted_style));
19928            } else if range.end <= label.filter_range.end {
19929                runs.push((range.clone(), style));
19930            } else {
19931                runs.push((range.start..label.filter_range.end, style));
19932                runs.push((label.filter_range.end..range.end, muted_style));
19933            }
19934            prev_end = cmp::max(prev_end, range.end);
19935
19936            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19937                runs.push((prev_end..label.text.len(), fade_out));
19938            }
19939
19940            runs
19941        })
19942}
19943
19944pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19945    let mut prev_index = 0;
19946    let mut prev_codepoint: Option<char> = None;
19947    text.char_indices()
19948        .chain([(text.len(), '\0')])
19949        .filter_map(move |(index, codepoint)| {
19950            let prev_codepoint = prev_codepoint.replace(codepoint)?;
19951            let is_boundary = index == text.len()
19952                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19953                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19954            if is_boundary {
19955                let chunk = &text[prev_index..index];
19956                prev_index = index;
19957                Some(chunk)
19958            } else {
19959                None
19960            }
19961        })
19962}
19963
19964pub trait RangeToAnchorExt: Sized {
19965    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19966
19967    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19968        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19969        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19970    }
19971}
19972
19973impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19974    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19975        let start_offset = self.start.to_offset(snapshot);
19976        let end_offset = self.end.to_offset(snapshot);
19977        if start_offset == end_offset {
19978            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19979        } else {
19980            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19981        }
19982    }
19983}
19984
19985pub trait RowExt {
19986    fn as_f32(&self) -> f32;
19987
19988    fn next_row(&self) -> Self;
19989
19990    fn previous_row(&self) -> Self;
19991
19992    fn minus(&self, other: Self) -> u32;
19993}
19994
19995impl RowExt for DisplayRow {
19996    fn as_f32(&self) -> f32 {
19997        self.0 as f32
19998    }
19999
20000    fn next_row(&self) -> Self {
20001        Self(self.0 + 1)
20002    }
20003
20004    fn previous_row(&self) -> Self {
20005        Self(self.0.saturating_sub(1))
20006    }
20007
20008    fn minus(&self, other: Self) -> u32 {
20009        self.0 - other.0
20010    }
20011}
20012
20013impl RowExt for MultiBufferRow {
20014    fn as_f32(&self) -> f32 {
20015        self.0 as f32
20016    }
20017
20018    fn next_row(&self) -> Self {
20019        Self(self.0 + 1)
20020    }
20021
20022    fn previous_row(&self) -> Self {
20023        Self(self.0.saturating_sub(1))
20024    }
20025
20026    fn minus(&self, other: Self) -> u32 {
20027        self.0 - other.0
20028    }
20029}
20030
20031trait RowRangeExt {
20032    type Row;
20033
20034    fn len(&self) -> usize;
20035
20036    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20037}
20038
20039impl RowRangeExt for Range<MultiBufferRow> {
20040    type Row = MultiBufferRow;
20041
20042    fn len(&self) -> usize {
20043        (self.end.0 - self.start.0) as usize
20044    }
20045
20046    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20047        (self.start.0..self.end.0).map(MultiBufferRow)
20048    }
20049}
20050
20051impl RowRangeExt for Range<DisplayRow> {
20052    type Row = DisplayRow;
20053
20054    fn len(&self) -> usize {
20055        (self.end.0 - self.start.0) as usize
20056    }
20057
20058    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20059        (self.start.0..self.end.0).map(DisplayRow)
20060    }
20061}
20062
20063/// If select range has more than one line, we
20064/// just point the cursor to range.start.
20065fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20066    if range.start.row == range.end.row {
20067        range
20068    } else {
20069        range.start..range.start
20070    }
20071}
20072pub struct KillRing(ClipboardItem);
20073impl Global for KillRing {}
20074
20075const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20076
20077enum BreakpointPromptEditAction {
20078    Log,
20079    Condition,
20080    HitCondition,
20081}
20082
20083struct BreakpointPromptEditor {
20084    pub(crate) prompt: Entity<Editor>,
20085    editor: WeakEntity<Editor>,
20086    breakpoint_anchor: Anchor,
20087    breakpoint: Breakpoint,
20088    edit_action: BreakpointPromptEditAction,
20089    block_ids: HashSet<CustomBlockId>,
20090    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20091    _subscriptions: Vec<Subscription>,
20092}
20093
20094impl BreakpointPromptEditor {
20095    const MAX_LINES: u8 = 4;
20096
20097    fn new(
20098        editor: WeakEntity<Editor>,
20099        breakpoint_anchor: Anchor,
20100        breakpoint: Breakpoint,
20101        edit_action: BreakpointPromptEditAction,
20102        window: &mut Window,
20103        cx: &mut Context<Self>,
20104    ) -> Self {
20105        let base_text = match edit_action {
20106            BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20107            BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20108            BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20109        }
20110        .map(|msg| msg.to_string())
20111        .unwrap_or_default();
20112
20113        let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20114        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20115
20116        let prompt = cx.new(|cx| {
20117            let mut prompt = Editor::new(
20118                EditorMode::AutoHeight {
20119                    max_lines: Self::MAX_LINES as usize,
20120                },
20121                buffer,
20122                None,
20123                window,
20124                cx,
20125            );
20126            prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20127            prompt.set_show_cursor_when_unfocused(false, cx);
20128            prompt.set_placeholder_text(
20129                match edit_action {
20130                    BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20131                    BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20132                    BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20133                },
20134                cx,
20135            );
20136
20137            prompt
20138        });
20139
20140        Self {
20141            prompt,
20142            editor,
20143            breakpoint_anchor,
20144            breakpoint,
20145            edit_action,
20146            gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20147            block_ids: Default::default(),
20148            _subscriptions: vec![],
20149        }
20150    }
20151
20152    pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20153        self.block_ids.extend(block_ids)
20154    }
20155
20156    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20157        if let Some(editor) = self.editor.upgrade() {
20158            let message = self
20159                .prompt
20160                .read(cx)
20161                .buffer
20162                .read(cx)
20163                .as_singleton()
20164                .expect("A multi buffer in breakpoint prompt isn't possible")
20165                .read(cx)
20166                .as_rope()
20167                .to_string();
20168
20169            editor.update(cx, |editor, cx| {
20170                editor.edit_breakpoint_at_anchor(
20171                    self.breakpoint_anchor,
20172                    self.breakpoint.clone(),
20173                    match self.edit_action {
20174                        BreakpointPromptEditAction::Log => {
20175                            BreakpointEditAction::EditLogMessage(message.into())
20176                        }
20177                        BreakpointPromptEditAction::Condition => {
20178                            BreakpointEditAction::EditCondition(message.into())
20179                        }
20180                        BreakpointPromptEditAction::HitCondition => {
20181                            BreakpointEditAction::EditHitCondition(message.into())
20182                        }
20183                    },
20184                    cx,
20185                );
20186
20187                editor.remove_blocks(self.block_ids.clone(), None, cx);
20188                cx.focus_self(window);
20189            });
20190        }
20191    }
20192
20193    fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20194        self.editor
20195            .update(cx, |editor, cx| {
20196                editor.remove_blocks(self.block_ids.clone(), None, cx);
20197                window.focus(&editor.focus_handle);
20198            })
20199            .log_err();
20200    }
20201
20202    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20203        let settings = ThemeSettings::get_global(cx);
20204        let text_style = TextStyle {
20205            color: if self.prompt.read(cx).read_only(cx) {
20206                cx.theme().colors().text_disabled
20207            } else {
20208                cx.theme().colors().text
20209            },
20210            font_family: settings.buffer_font.family.clone(),
20211            font_fallbacks: settings.buffer_font.fallbacks.clone(),
20212            font_size: settings.buffer_font_size(cx).into(),
20213            font_weight: settings.buffer_font.weight,
20214            line_height: relative(settings.buffer_line_height.value()),
20215            ..Default::default()
20216        };
20217        EditorElement::new(
20218            &self.prompt,
20219            EditorStyle {
20220                background: cx.theme().colors().editor_background,
20221                local_player: cx.theme().players().local(),
20222                text: text_style,
20223                ..Default::default()
20224            },
20225        )
20226    }
20227}
20228
20229impl Render for BreakpointPromptEditor {
20230    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20231        let gutter_dimensions = *self.gutter_dimensions.lock();
20232        h_flex()
20233            .key_context("Editor")
20234            .bg(cx.theme().colors().editor_background)
20235            .border_y_1()
20236            .border_color(cx.theme().status().info_border)
20237            .size_full()
20238            .py(window.line_height() / 2.5)
20239            .on_action(cx.listener(Self::confirm))
20240            .on_action(cx.listener(Self::cancel))
20241            .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20242            .child(div().flex_1().child(self.render_prompt_editor(cx)))
20243    }
20244}
20245
20246impl Focusable for BreakpointPromptEditor {
20247    fn focus_handle(&self, cx: &App) -> FocusHandle {
20248        self.prompt.focus_handle(cx)
20249    }
20250}
20251
20252fn all_edits_insertions_or_deletions(
20253    edits: &Vec<(Range<Anchor>, String)>,
20254    snapshot: &MultiBufferSnapshot,
20255) -> bool {
20256    let mut all_insertions = true;
20257    let mut all_deletions = true;
20258
20259    for (range, new_text) in edits.iter() {
20260        let range_is_empty = range.to_offset(&snapshot).is_empty();
20261        let text_is_empty = new_text.is_empty();
20262
20263        if range_is_empty != text_is_empty {
20264            if range_is_empty {
20265                all_deletions = false;
20266            } else {
20267                all_insertions = false;
20268            }
20269        } else {
20270            return false;
20271        }
20272
20273        if !all_insertions && !all_deletions {
20274            return false;
20275        }
20276    }
20277    all_insertions || all_deletions
20278}
20279
20280struct MissingEditPredictionKeybindingTooltip;
20281
20282impl Render for MissingEditPredictionKeybindingTooltip {
20283    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20284        ui::tooltip_container(window, cx, |container, _, cx| {
20285            container
20286                .flex_shrink_0()
20287                .max_w_80()
20288                .min_h(rems_from_px(124.))
20289                .justify_between()
20290                .child(
20291                    v_flex()
20292                        .flex_1()
20293                        .text_ui_sm(cx)
20294                        .child(Label::new("Conflict with Accept Keybinding"))
20295                        .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20296                )
20297                .child(
20298                    h_flex()
20299                        .pb_1()
20300                        .gap_1()
20301                        .items_end()
20302                        .w_full()
20303                        .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20304                            window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20305                        }))
20306                        .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20307                            cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20308                        })),
20309                )
20310        })
20311    }
20312}
20313
20314#[derive(Debug, Clone, Copy, PartialEq)]
20315pub struct LineHighlight {
20316    pub background: Background,
20317    pub border: Option<gpui::Hsla>,
20318}
20319
20320impl From<Hsla> for LineHighlight {
20321    fn from(hsla: Hsla) -> Self {
20322        Self {
20323            background: hsla.into(),
20324            border: None,
20325        }
20326    }
20327}
20328
20329impl From<Background> for LineHighlight {
20330    fn from(background: Background) -> Self {
20331        Self {
20332            background,
20333            border: None,
20334        }
20335    }
20336}
20337
20338fn render_diff_hunk_controls(
20339    row: u32,
20340    status: &DiffHunkStatus,
20341    hunk_range: Range<Anchor>,
20342    is_created_file: bool,
20343    line_height: Pixels,
20344    editor: &Entity<Editor>,
20345    _window: &mut Window,
20346    cx: &mut App,
20347) -> AnyElement {
20348    h_flex()
20349        .h(line_height)
20350        .mr_1()
20351        .gap_1()
20352        .px_0p5()
20353        .pb_1()
20354        .border_x_1()
20355        .border_b_1()
20356        .border_color(cx.theme().colors().border_variant)
20357        .rounded_b_lg()
20358        .bg(cx.theme().colors().editor_background)
20359        .gap_1()
20360        .occlude()
20361        .shadow_md()
20362        .child(if status.has_secondary_hunk() {
20363            Button::new(("stage", row as u64), "Stage")
20364                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20365                .tooltip({
20366                    let focus_handle = editor.focus_handle(cx);
20367                    move |window, cx| {
20368                        Tooltip::for_action_in(
20369                            "Stage Hunk",
20370                            &::git::ToggleStaged,
20371                            &focus_handle,
20372                            window,
20373                            cx,
20374                        )
20375                    }
20376                })
20377                .on_click({
20378                    let editor = editor.clone();
20379                    move |_event, _window, cx| {
20380                        editor.update(cx, |editor, cx| {
20381                            editor.stage_or_unstage_diff_hunks(
20382                                true,
20383                                vec![hunk_range.start..hunk_range.start],
20384                                cx,
20385                            );
20386                        });
20387                    }
20388                })
20389        } else {
20390            Button::new(("unstage", row as u64), "Unstage")
20391                .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20392                .tooltip({
20393                    let focus_handle = editor.focus_handle(cx);
20394                    move |window, cx| {
20395                        Tooltip::for_action_in(
20396                            "Unstage Hunk",
20397                            &::git::ToggleStaged,
20398                            &focus_handle,
20399                            window,
20400                            cx,
20401                        )
20402                    }
20403                })
20404                .on_click({
20405                    let editor = editor.clone();
20406                    move |_event, _window, cx| {
20407                        editor.update(cx, |editor, cx| {
20408                            editor.stage_or_unstage_diff_hunks(
20409                                false,
20410                                vec![hunk_range.start..hunk_range.start],
20411                                cx,
20412                            );
20413                        });
20414                    }
20415                })
20416        })
20417        .child(
20418            Button::new(("restore", row as u64), "Restore")
20419                .tooltip({
20420                    let focus_handle = editor.focus_handle(cx);
20421                    move |window, cx| {
20422                        Tooltip::for_action_in(
20423                            "Restore Hunk",
20424                            &::git::Restore,
20425                            &focus_handle,
20426                            window,
20427                            cx,
20428                        )
20429                    }
20430                })
20431                .on_click({
20432                    let editor = editor.clone();
20433                    move |_event, window, cx| {
20434                        editor.update(cx, |editor, cx| {
20435                            let snapshot = editor.snapshot(window, cx);
20436                            let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20437                            editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20438                        });
20439                    }
20440                })
20441                .disabled(is_created_file),
20442        )
20443        .when(
20444            !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20445            |el| {
20446                el.child(
20447                    IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20448                        .shape(IconButtonShape::Square)
20449                        .icon_size(IconSize::Small)
20450                        // .disabled(!has_multiple_hunks)
20451                        .tooltip({
20452                            let focus_handle = editor.focus_handle(cx);
20453                            move |window, cx| {
20454                                Tooltip::for_action_in(
20455                                    "Next Hunk",
20456                                    &GoToHunk,
20457                                    &focus_handle,
20458                                    window,
20459                                    cx,
20460                                )
20461                            }
20462                        })
20463                        .on_click({
20464                            let editor = editor.clone();
20465                            move |_event, window, cx| {
20466                                editor.update(cx, |editor, cx| {
20467                                    let snapshot = editor.snapshot(window, cx);
20468                                    let position =
20469                                        hunk_range.end.to_point(&snapshot.buffer_snapshot);
20470                                    editor.go_to_hunk_before_or_after_position(
20471                                        &snapshot,
20472                                        position,
20473                                        Direction::Next,
20474                                        window,
20475                                        cx,
20476                                    );
20477                                    editor.expand_selected_diff_hunks(cx);
20478                                });
20479                            }
20480                        }),
20481                )
20482                .child(
20483                    IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20484                        .shape(IconButtonShape::Square)
20485                        .icon_size(IconSize::Small)
20486                        // .disabled(!has_multiple_hunks)
20487                        .tooltip({
20488                            let focus_handle = editor.focus_handle(cx);
20489                            move |window, cx| {
20490                                Tooltip::for_action_in(
20491                                    "Previous Hunk",
20492                                    &GoToPreviousHunk,
20493                                    &focus_handle,
20494                                    window,
20495                                    cx,
20496                                )
20497                            }
20498                        })
20499                        .on_click({
20500                            let editor = editor.clone();
20501                            move |_event, window, cx| {
20502                                editor.update(cx, |editor, cx| {
20503                                    let snapshot = editor.snapshot(window, cx);
20504                                    let point =
20505                                        hunk_range.start.to_point(&snapshot.buffer_snapshot);
20506                                    editor.go_to_hunk_before_or_after_position(
20507                                        &snapshot,
20508                                        point,
20509                                        Direction::Prev,
20510                                        window,
20511                                        cx,
20512                                    );
20513                                    editor.expand_selected_diff_hunks(cx);
20514                                });
20515                            }
20516                        }),
20517                )
20518            },
20519        )
20520        .into_any_element()
20521}