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 commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   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::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkSecondaryStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use ::git::{status::FileStatus, Restore};
   77use code_context_menus::{
   78    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   79    CompletionsMenu, ContextMenuOrigin,
   80};
   81use git::blame::GitBlame;
   82use gpui::{
   83    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   84    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   85    ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
   86    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   87    HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   88    ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
   89    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   90    WeakEntity, WeakFocusHandle, Window,
   91};
   92use highlight_matching_bracket::refresh_matching_bracket_highlights;
   93use hover_popover::{hide_hover, HoverState};
   94use indent_guides::ActiveIndentGuidesState;
   95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   96pub use inline_completion::Direction;
   97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   98pub use items::MAX_TAB_TITLE_LEN;
   99use itertools::Itertools;
  100use language::{
  101    language_settings::{
  102        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  103    },
  104    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  105    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, DiskState,
  106    EditPredictionsMode, EditPreview, HighlightedText, IndentKind, IndentSize, Language,
  107    OffsetRangeExt, Point, Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  108};
  109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  110use linked_editing_ranges::refresh_linked_ranges;
  111use mouse_context_menu::MouseContextMenu;
  112use persistence::DB;
  113pub use proposed_changes_editor::{
  114    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  115};
  116use smallvec::smallvec;
  117use std::iter::Peekable;
  118use task::{ResolvedTask, TaskTemplate, TaskVariables};
  119
  120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  121pub use lsp::CompletionContext;
  122use lsp::{
  123    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  124    LanguageServerId, LanguageServerName,
  125};
  126
  127use language::BufferSnapshot;
  128use movement::TextLayoutDetails;
  129pub use multi_buffer::{
  130    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  131    ToOffset, ToPoint,
  132};
  133use multi_buffer::{
  134    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  135    ToOffsetUtf16,
  136};
  137use project::{
  138    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  139    project_settings::{GitGutterSetting, ProjectSettings},
  140    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  141    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  142};
  143use rand::prelude::*;
  144use rpc::{proto::*, ErrorExt};
  145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  146use selections_collection::{
  147    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  148};
  149use serde::{Deserialize, Serialize};
  150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  151use smallvec::SmallVec;
  152use snippet::Snippet;
  153use std::{
  154    any::TypeId,
  155    borrow::Cow,
  156    cell::RefCell,
  157    cmp::{self, Ordering, Reverse},
  158    mem,
  159    num::NonZeroU32,
  160    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  161    path::{Path, PathBuf},
  162    rc::Rc,
  163    sync::Arc,
  164    time::{Duration, Instant},
  165};
  166pub use sum_tree::Bias;
  167use sum_tree::TreeMap;
  168use text::{BufferId, OffsetUtf16, Rope};
  169use theme::{
  170    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  171    ThemeColors, ThemeSettings,
  172};
  173use ui::{
  174    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  175    Tooltip,
  176};
  177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  178use workspace::{
  179    item::{ItemHandle, PreviewTabsSettings},
  180    ItemId, RestoreOnStartupBehavior,
  181};
  182use workspace::{
  183    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  184    WorkspaceSettings,
  185};
  186use workspace::{
  187    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  188};
  189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  190
  191use crate::hover_links::{find_url, find_url_from_range};
  192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  193
  194pub const FILE_HEADER_HEIGHT: u32 = 2;
  195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  199const MAX_LINE_LEN: usize = 1024;
  200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  203#[doc(hidden)]
  204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  205
  206pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  207pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  208
  209pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  210pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  211
  212const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  213    alt: true,
  214    shift: true,
  215    control: false,
  216    platform: false,
  217    function: false,
  218};
  219
  220#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  221pub enum InlayId {
  222    InlineCompletion(usize),
  223    Hint(usize),
  224}
  225
  226impl InlayId {
  227    fn id(&self) -> usize {
  228        match self {
  229            Self::InlineCompletion(id) => *id,
  230            Self::Hint(id) => *id,
  231        }
  232    }
  233}
  234
  235enum DocumentHighlightRead {}
  236enum DocumentHighlightWrite {}
  237enum InputComposition {}
  238enum SelectedTextHighlight {}
  239
  240#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  241pub enum Navigated {
  242    Yes,
  243    No,
  244}
  245
  246impl Navigated {
  247    pub fn from_bool(yes: bool) -> Navigated {
  248        if yes {
  249            Navigated::Yes
  250        } else {
  251            Navigated::No
  252        }
  253    }
  254}
  255
  256pub fn init_settings(cx: &mut App) {
  257    EditorSettings::register(cx);
  258}
  259
  260pub fn init(cx: &mut App) {
  261    init_settings(cx);
  262
  263    workspace::register_project_item::<Editor>(cx);
  264    workspace::FollowableViewRegistry::register::<Editor>(cx);
  265    workspace::register_serializable_item::<Editor>(cx);
  266
  267    cx.observe_new(
  268        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  269            workspace.register_action(Editor::new_file);
  270            workspace.register_action(Editor::new_file_vertical);
  271            workspace.register_action(Editor::new_file_horizontal);
  272            workspace.register_action(Editor::cancel_language_server_work);
  273        },
  274    )
  275    .detach();
  276
  277    cx.on_action(move |_: &workspace::NewFile, cx| {
  278        let app_state = workspace::AppState::global(cx);
  279        if let Some(app_state) = app_state.upgrade() {
  280            workspace::open_new(
  281                Default::default(),
  282                app_state,
  283                cx,
  284                |workspace, window, cx| {
  285                    Editor::new_file(workspace, &Default::default(), window, cx)
  286                },
  287            )
  288            .detach();
  289        }
  290    });
  291    cx.on_action(move |_: &workspace::NewWindow, cx| {
  292        let app_state = workspace::AppState::global(cx);
  293        if let Some(app_state) = app_state.upgrade() {
  294            workspace::open_new(
  295                Default::default(),
  296                app_state,
  297                cx,
  298                |workspace, window, cx| {
  299                    cx.activate(true);
  300                    Editor::new_file(workspace, &Default::default(), window, cx)
  301                },
  302            )
  303            .detach();
  304        }
  305    });
  306}
  307
  308pub struct SearchWithinRange;
  309
  310trait InvalidationRegion {
  311    fn ranges(&self) -> &[Range<Anchor>];
  312}
  313
  314#[derive(Clone, Debug, PartialEq)]
  315pub enum SelectPhase {
  316    Begin {
  317        position: DisplayPoint,
  318        add: bool,
  319        click_count: usize,
  320    },
  321    BeginColumnar {
  322        position: DisplayPoint,
  323        reset: bool,
  324        goal_column: u32,
  325    },
  326    Extend {
  327        position: DisplayPoint,
  328        click_count: usize,
  329    },
  330    Update {
  331        position: DisplayPoint,
  332        goal_column: u32,
  333        scroll_delta: gpui::Point<f32>,
  334    },
  335    End,
  336}
  337
  338#[derive(Clone, Debug)]
  339pub enum SelectMode {
  340    Character,
  341    Word(Range<Anchor>),
  342    Line(Range<Anchor>),
  343    All,
  344}
  345
  346#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  347pub enum EditorMode {
  348    SingleLine { auto_width: bool },
  349    AutoHeight { max_lines: usize },
  350    Full,
  351}
  352
  353#[derive(Copy, Clone, Debug)]
  354pub enum SoftWrap {
  355    /// Prefer not to wrap at all.
  356    ///
  357    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  358    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  359    GitDiff,
  360    /// Prefer a single line generally, unless an overly long line is encountered.
  361    None,
  362    /// Soft wrap lines that exceed the editor width.
  363    EditorWidth,
  364    /// Soft wrap lines at the preferred line length.
  365    Column(u32),
  366    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  367    Bounded(u32),
  368}
  369
  370#[derive(Clone)]
  371pub struct EditorStyle {
  372    pub background: Hsla,
  373    pub local_player: PlayerColor,
  374    pub text: TextStyle,
  375    pub scrollbar_width: Pixels,
  376    pub syntax: Arc<SyntaxTheme>,
  377    pub status: StatusColors,
  378    pub inlay_hints_style: HighlightStyle,
  379    pub inline_completion_styles: InlineCompletionStyles,
  380    pub unnecessary_code_fade: f32,
  381}
  382
  383impl Default for EditorStyle {
  384    fn default() -> Self {
  385        Self {
  386            background: Hsla::default(),
  387            local_player: PlayerColor::default(),
  388            text: TextStyle::default(),
  389            scrollbar_width: Pixels::default(),
  390            syntax: Default::default(),
  391            // HACK: Status colors don't have a real default.
  392            // We should look into removing the status colors from the editor
  393            // style and retrieve them directly from the theme.
  394            status: StatusColors::dark(),
  395            inlay_hints_style: HighlightStyle::default(),
  396            inline_completion_styles: InlineCompletionStyles {
  397                insertion: HighlightStyle::default(),
  398                whitespace: HighlightStyle::default(),
  399            },
  400            unnecessary_code_fade: Default::default(),
  401        }
  402    }
  403}
  404
  405pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  406    let show_background = language_settings::language_settings(None, None, cx)
  407        .inlay_hints
  408        .show_background;
  409
  410    HighlightStyle {
  411        color: Some(cx.theme().status().hint),
  412        background_color: show_background.then(|| cx.theme().status().hint_background),
  413        ..HighlightStyle::default()
  414    }
  415}
  416
  417pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  418    InlineCompletionStyles {
  419        insertion: HighlightStyle {
  420            color: Some(cx.theme().status().predictive),
  421            ..HighlightStyle::default()
  422        },
  423        whitespace: HighlightStyle {
  424            background_color: Some(cx.theme().status().created_background),
  425            ..HighlightStyle::default()
  426        },
  427    }
  428}
  429
  430type CompletionId = usize;
  431
  432pub(crate) enum EditDisplayMode {
  433    TabAccept,
  434    DiffPopover,
  435    Inline,
  436}
  437
  438enum InlineCompletion {
  439    Edit {
  440        edits: Vec<(Range<Anchor>, String)>,
  441        edit_preview: Option<EditPreview>,
  442        display_mode: EditDisplayMode,
  443        snapshot: BufferSnapshot,
  444    },
  445    Move {
  446        target: Anchor,
  447        snapshot: BufferSnapshot,
  448    },
  449}
  450
  451struct InlineCompletionState {
  452    inlay_ids: Vec<InlayId>,
  453    completion: InlineCompletion,
  454    completion_id: Option<SharedString>,
  455    invalidation_range: Range<Anchor>,
  456}
  457
  458enum EditPredictionSettings {
  459    Disabled,
  460    Enabled {
  461        show_in_menu: bool,
  462        preview_requires_modifier: bool,
  463    },
  464}
  465
  466enum InlineCompletionHighlight {}
  467
  468#[derive(Debug, Clone)]
  469struct InlineDiagnostic {
  470    message: SharedString,
  471    group_id: usize,
  472    is_primary: bool,
  473    start: Point,
  474    severity: DiagnosticSeverity,
  475}
  476
  477pub enum MenuInlineCompletionsPolicy {
  478    Never,
  479    ByProvider,
  480}
  481
  482pub enum EditPredictionPreview {
  483    /// Modifier is not pressed
  484    Inactive,
  485    /// Modifier pressed
  486    Active {
  487        previous_scroll_position: Option<ScrollAnchor>,
  488    },
  489}
  490
  491#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  492struct EditorActionId(usize);
  493
  494impl EditorActionId {
  495    pub fn post_inc(&mut self) -> Self {
  496        let answer = self.0;
  497
  498        *self = Self(answer + 1);
  499
  500        Self(answer)
  501    }
  502}
  503
  504// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  505// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  506
  507type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  508type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  509
  510#[derive(Default)]
  511struct ScrollbarMarkerState {
  512    scrollbar_size: Size<Pixels>,
  513    dirty: bool,
  514    markers: Arc<[PaintQuad]>,
  515    pending_refresh: Option<Task<Result<()>>>,
  516}
  517
  518impl ScrollbarMarkerState {
  519    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  520        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  521    }
  522}
  523
  524#[derive(Clone, Debug)]
  525struct RunnableTasks {
  526    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  527    offset: MultiBufferOffset,
  528    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  529    column: u32,
  530    // Values of all named captures, including those starting with '_'
  531    extra_variables: HashMap<String, String>,
  532    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  533    context_range: Range<BufferOffset>,
  534}
  535
  536impl RunnableTasks {
  537    fn resolve<'a>(
  538        &'a self,
  539        cx: &'a task::TaskContext,
  540    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  541        self.templates.iter().filter_map(|(kind, template)| {
  542            template
  543                .resolve_task(&kind.to_id_base(), cx)
  544                .map(|task| (kind.clone(), task))
  545        })
  546    }
  547}
  548
  549#[derive(Clone)]
  550struct ResolvedTasks {
  551    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  552    position: Anchor,
  553}
  554#[derive(Copy, Clone, Debug)]
  555struct MultiBufferOffset(usize);
  556#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  557struct BufferOffset(usize);
  558
  559// Addons allow storing per-editor state in other crates (e.g. Vim)
  560pub trait Addon: 'static {
  561    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  562
  563    fn render_buffer_header_controls(
  564        &self,
  565        _: &ExcerptInfo,
  566        _: &Window,
  567        _: &App,
  568    ) -> Option<AnyElement> {
  569        None
  570    }
  571
  572    fn to_any(&self) -> &dyn std::any::Any;
  573}
  574
  575#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  576pub enum IsVimMode {
  577    Yes,
  578    No,
  579}
  580
  581/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  582///
  583/// See the [module level documentation](self) for more information.
  584pub struct Editor {
  585    focus_handle: FocusHandle,
  586    last_focused_descendant: Option<WeakFocusHandle>,
  587    /// The text buffer being edited
  588    buffer: Entity<MultiBuffer>,
  589    /// Map of how text in the buffer should be displayed.
  590    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  591    pub display_map: Entity<DisplayMap>,
  592    pub selections: SelectionsCollection,
  593    pub scroll_manager: ScrollManager,
  594    /// When inline assist editors are linked, they all render cursors because
  595    /// typing enters text into each of them, even the ones that aren't focused.
  596    pub(crate) show_cursor_when_unfocused: bool,
  597    columnar_selection_tail: Option<Anchor>,
  598    add_selections_state: Option<AddSelectionsState>,
  599    select_next_state: Option<SelectNextState>,
  600    select_prev_state: Option<SelectNextState>,
  601    selection_history: SelectionHistory,
  602    autoclose_regions: Vec<AutocloseRegion>,
  603    snippet_stack: InvalidationStack<SnippetState>,
  604    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  605    ime_transaction: Option<TransactionId>,
  606    active_diagnostics: Option<ActiveDiagnosticGroup>,
  607    show_inline_diagnostics: bool,
  608    inline_diagnostics_update: Task<()>,
  609    inline_diagnostics_enabled: bool,
  610    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  611    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  612
  613    // TODO: make this a access method
  614    pub project: Option<Entity<Project>>,
  615    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  616    completion_provider: Option<Box<dyn CompletionProvider>>,
  617    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  618    blink_manager: Entity<BlinkManager>,
  619    show_cursor_names: bool,
  620    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  621    pub show_local_selections: bool,
  622    mode: EditorMode,
  623    show_breadcrumbs: bool,
  624    show_gutter: bool,
  625    show_scrollbars: bool,
  626    show_line_numbers: Option<bool>,
  627    use_relative_line_numbers: Option<bool>,
  628    show_git_diff_gutter: Option<bool>,
  629    show_code_actions: Option<bool>,
  630    show_runnables: Option<bool>,
  631    show_wrap_guides: Option<bool>,
  632    show_indent_guides: Option<bool>,
  633    placeholder_text: Option<Arc<str>>,
  634    highlight_order: usize,
  635    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  636    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  637    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  638    scrollbar_marker_state: ScrollbarMarkerState,
  639    active_indent_guides_state: ActiveIndentGuidesState,
  640    nav_history: Option<ItemNavHistory>,
  641    context_menu: RefCell<Option<CodeContextMenu>>,
  642    mouse_context_menu: Option<MouseContextMenu>,
  643    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  644    signature_help_state: SignatureHelpState,
  645    auto_signature_help: Option<bool>,
  646    find_all_references_task_sources: Vec<Anchor>,
  647    next_completion_id: CompletionId,
  648    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  649    code_actions_task: Option<Task<Result<()>>>,
  650    selection_highlight_task: Option<Task<()>>,
  651    document_highlights_task: Option<Task<()>>,
  652    linked_editing_range_task: Option<Task<Option<()>>>,
  653    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  654    pending_rename: Option<RenameState>,
  655    searchable: bool,
  656    cursor_shape: CursorShape,
  657    current_line_highlight: Option<CurrentLineHighlight>,
  658    collapse_matches: bool,
  659    autoindent_mode: Option<AutoindentMode>,
  660    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  661    input_enabled: bool,
  662    use_modal_editing: bool,
  663    read_only: bool,
  664    leader_peer_id: Option<PeerId>,
  665    remote_id: Option<ViewId>,
  666    hover_state: HoverState,
  667    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  668    gutter_hovered: bool,
  669    hovered_link_state: Option<HoveredLinkState>,
  670    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  671    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  672    active_inline_completion: Option<InlineCompletionState>,
  673    /// Used to prevent flickering as the user types while the menu is open
  674    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  675    edit_prediction_settings: EditPredictionSettings,
  676    inline_completions_hidden_for_vim_mode: bool,
  677    show_inline_completions_override: Option<bool>,
  678    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  679    edit_prediction_preview: EditPredictionPreview,
  680    edit_prediction_cursor_on_leading_whitespace: bool,
  681    edit_prediction_requires_modifier_in_leading_space: bool,
  682    inlay_hint_cache: InlayHintCache,
  683    next_inlay_id: usize,
  684    _subscriptions: Vec<Subscription>,
  685    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  686    gutter_dimensions: GutterDimensions,
  687    style: Option<EditorStyle>,
  688    text_style_refinement: Option<TextStyleRefinement>,
  689    next_editor_action_id: EditorActionId,
  690    editor_actions:
  691        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  692    use_autoclose: bool,
  693    use_auto_surround: bool,
  694    auto_replace_emoji_shortcode: bool,
  695    show_git_blame_gutter: bool,
  696    show_git_blame_inline: bool,
  697    show_git_blame_inline_delay_task: Option<Task<()>>,
  698    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  699    git_blame_inline_enabled: bool,
  700    serialize_dirty_buffers: bool,
  701    show_selection_menu: Option<bool>,
  702    blame: Option<Entity<GitBlame>>,
  703    blame_subscription: Option<Subscription>,
  704    custom_context_menu: Option<
  705        Box<
  706            dyn 'static
  707                + Fn(
  708                    &mut Self,
  709                    DisplayPoint,
  710                    &mut Window,
  711                    &mut Context<Self>,
  712                ) -> Option<Entity<ui::ContextMenu>>,
  713        >,
  714    >,
  715    last_bounds: Option<Bounds<Pixels>>,
  716    last_position_map: Option<Rc<PositionMap>>,
  717    expect_bounds_change: Option<Bounds<Pixels>>,
  718    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  719    tasks_update_task: Option<Task<()>>,
  720    in_project_search: bool,
  721    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  722    breadcrumb_header: Option<String>,
  723    focused_block: Option<FocusedBlock>,
  724    next_scroll_position: NextScrollCursorCenterTopBottom,
  725    addons: HashMap<TypeId, Box<dyn Addon>>,
  726    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  727    load_diff_task: Option<Shared<Task<()>>>,
  728    selection_mark_mode: bool,
  729    toggle_fold_multiple_buffers: Task<()>,
  730    _scroll_cursor_center_top_bottom_task: Task<()>,
  731    serialize_selections: Task<()>,
  732}
  733
  734#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  735enum NextScrollCursorCenterTopBottom {
  736    #[default]
  737    Center,
  738    Top,
  739    Bottom,
  740}
  741
  742impl NextScrollCursorCenterTopBottom {
  743    fn next(&self) -> Self {
  744        match self {
  745            Self::Center => Self::Top,
  746            Self::Top => Self::Bottom,
  747            Self::Bottom => Self::Center,
  748        }
  749    }
  750}
  751
  752#[derive(Clone)]
  753pub struct EditorSnapshot {
  754    pub mode: EditorMode,
  755    show_gutter: bool,
  756    show_line_numbers: Option<bool>,
  757    show_git_diff_gutter: Option<bool>,
  758    show_code_actions: Option<bool>,
  759    show_runnables: Option<bool>,
  760    git_blame_gutter_max_author_length: Option<usize>,
  761    pub display_snapshot: DisplaySnapshot,
  762    pub placeholder_text: Option<Arc<str>>,
  763    is_focused: bool,
  764    scroll_anchor: ScrollAnchor,
  765    ongoing_scroll: OngoingScroll,
  766    current_line_highlight: CurrentLineHighlight,
  767    gutter_hovered: bool,
  768}
  769
  770const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  771
  772#[derive(Default, Debug, Clone, Copy)]
  773pub struct GutterDimensions {
  774    pub left_padding: Pixels,
  775    pub right_padding: Pixels,
  776    pub width: Pixels,
  777    pub margin: Pixels,
  778    pub git_blame_entries_width: Option<Pixels>,
  779}
  780
  781impl GutterDimensions {
  782    /// The full width of the space taken up by the gutter.
  783    pub fn full_width(&self) -> Pixels {
  784        self.margin + self.width
  785    }
  786
  787    /// The width of the space reserved for the fold indicators,
  788    /// use alongside 'justify_end' and `gutter_width` to
  789    /// right align content with the line numbers
  790    pub fn fold_area_width(&self) -> Pixels {
  791        self.margin + self.right_padding
  792    }
  793}
  794
  795#[derive(Debug)]
  796pub struct RemoteSelection {
  797    pub replica_id: ReplicaId,
  798    pub selection: Selection<Anchor>,
  799    pub cursor_shape: CursorShape,
  800    pub peer_id: PeerId,
  801    pub line_mode: bool,
  802    pub participant_index: Option<ParticipantIndex>,
  803    pub user_name: Option<SharedString>,
  804}
  805
  806#[derive(Clone, Debug)]
  807struct SelectionHistoryEntry {
  808    selections: Arc<[Selection<Anchor>]>,
  809    select_next_state: Option<SelectNextState>,
  810    select_prev_state: Option<SelectNextState>,
  811    add_selections_state: Option<AddSelectionsState>,
  812}
  813
  814enum SelectionHistoryMode {
  815    Normal,
  816    Undoing,
  817    Redoing,
  818}
  819
  820#[derive(Clone, PartialEq, Eq, Hash)]
  821struct HoveredCursor {
  822    replica_id: u16,
  823    selection_id: usize,
  824}
  825
  826impl Default for SelectionHistoryMode {
  827    fn default() -> Self {
  828        Self::Normal
  829    }
  830}
  831
  832#[derive(Default)]
  833struct SelectionHistory {
  834    #[allow(clippy::type_complexity)]
  835    selections_by_transaction:
  836        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  837    mode: SelectionHistoryMode,
  838    undo_stack: VecDeque<SelectionHistoryEntry>,
  839    redo_stack: VecDeque<SelectionHistoryEntry>,
  840}
  841
  842impl SelectionHistory {
  843    fn insert_transaction(
  844        &mut self,
  845        transaction_id: TransactionId,
  846        selections: Arc<[Selection<Anchor>]>,
  847    ) {
  848        self.selections_by_transaction
  849            .insert(transaction_id, (selections, None));
  850    }
  851
  852    #[allow(clippy::type_complexity)]
  853    fn transaction(
  854        &self,
  855        transaction_id: TransactionId,
  856    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  857        self.selections_by_transaction.get(&transaction_id)
  858    }
  859
  860    #[allow(clippy::type_complexity)]
  861    fn transaction_mut(
  862        &mut self,
  863        transaction_id: TransactionId,
  864    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  865        self.selections_by_transaction.get_mut(&transaction_id)
  866    }
  867
  868    fn push(&mut self, entry: SelectionHistoryEntry) {
  869        if !entry.selections.is_empty() {
  870            match self.mode {
  871                SelectionHistoryMode::Normal => {
  872                    self.push_undo(entry);
  873                    self.redo_stack.clear();
  874                }
  875                SelectionHistoryMode::Undoing => self.push_redo(entry),
  876                SelectionHistoryMode::Redoing => self.push_undo(entry),
  877            }
  878        }
  879    }
  880
  881    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  882        if self
  883            .undo_stack
  884            .back()
  885            .map_or(true, |e| e.selections != entry.selections)
  886        {
  887            self.undo_stack.push_back(entry);
  888            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  889                self.undo_stack.pop_front();
  890            }
  891        }
  892    }
  893
  894    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  895        if self
  896            .redo_stack
  897            .back()
  898            .map_or(true, |e| e.selections != entry.selections)
  899        {
  900            self.redo_stack.push_back(entry);
  901            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  902                self.redo_stack.pop_front();
  903            }
  904        }
  905    }
  906}
  907
  908struct RowHighlight {
  909    index: usize,
  910    range: Range<Anchor>,
  911    color: Hsla,
  912    should_autoscroll: bool,
  913}
  914
  915#[derive(Clone, Debug)]
  916struct AddSelectionsState {
  917    above: bool,
  918    stack: Vec<usize>,
  919}
  920
  921#[derive(Clone)]
  922struct SelectNextState {
  923    query: AhoCorasick,
  924    wordwise: bool,
  925    done: bool,
  926}
  927
  928impl std::fmt::Debug for SelectNextState {
  929    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  930        f.debug_struct(std::any::type_name::<Self>())
  931            .field("wordwise", &self.wordwise)
  932            .field("done", &self.done)
  933            .finish()
  934    }
  935}
  936
  937#[derive(Debug)]
  938struct AutocloseRegion {
  939    selection_id: usize,
  940    range: Range<Anchor>,
  941    pair: BracketPair,
  942}
  943
  944#[derive(Debug)]
  945struct SnippetState {
  946    ranges: Vec<Vec<Range<Anchor>>>,
  947    active_index: usize,
  948    choices: Vec<Option<Vec<String>>>,
  949}
  950
  951#[doc(hidden)]
  952pub struct RenameState {
  953    pub range: Range<Anchor>,
  954    pub old_name: Arc<str>,
  955    pub editor: Entity<Editor>,
  956    block_id: CustomBlockId,
  957}
  958
  959struct InvalidationStack<T>(Vec<T>);
  960
  961struct RegisteredInlineCompletionProvider {
  962    provider: Arc<dyn InlineCompletionProviderHandle>,
  963    _subscription: Subscription,
  964}
  965
  966#[derive(Debug)]
  967struct ActiveDiagnosticGroup {
  968    primary_range: Range<Anchor>,
  969    primary_message: String,
  970    group_id: usize,
  971    blocks: HashMap<CustomBlockId, Diagnostic>,
  972    is_valid: bool,
  973}
  974
  975#[derive(Serialize, Deserialize, Clone, Debug)]
  976pub struct ClipboardSelection {
  977    /// The number of bytes in this selection.
  978    pub len: usize,
  979    /// Whether this was a full-line selection.
  980    pub is_entire_line: bool,
  981    /// The column where this selection originally started.
  982    pub start_column: u32,
  983}
  984
  985#[derive(Debug)]
  986pub(crate) struct NavigationData {
  987    cursor_anchor: Anchor,
  988    cursor_position: Point,
  989    scroll_anchor: ScrollAnchor,
  990    scroll_top_row: u32,
  991}
  992
  993#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  994pub enum GotoDefinitionKind {
  995    Symbol,
  996    Declaration,
  997    Type,
  998    Implementation,
  999}
 1000
 1001#[derive(Debug, Clone)]
 1002enum InlayHintRefreshReason {
 1003    Toggle(bool),
 1004    SettingsChange(InlayHintSettings),
 1005    NewLinesShown,
 1006    BufferEdited(HashSet<Arc<Language>>),
 1007    RefreshRequested,
 1008    ExcerptsRemoved(Vec<ExcerptId>),
 1009}
 1010
 1011impl InlayHintRefreshReason {
 1012    fn description(&self) -> &'static str {
 1013        match self {
 1014            Self::Toggle(_) => "toggle",
 1015            Self::SettingsChange(_) => "settings change",
 1016            Self::NewLinesShown => "new lines shown",
 1017            Self::BufferEdited(_) => "buffer edited",
 1018            Self::RefreshRequested => "refresh requested",
 1019            Self::ExcerptsRemoved(_) => "excerpts removed",
 1020        }
 1021    }
 1022}
 1023
 1024pub enum FormatTarget {
 1025    Buffers,
 1026    Ranges(Vec<Range<MultiBufferPoint>>),
 1027}
 1028
 1029pub(crate) struct FocusedBlock {
 1030    id: BlockId,
 1031    focus_handle: WeakFocusHandle,
 1032}
 1033
 1034#[derive(Clone)]
 1035enum JumpData {
 1036    MultiBufferRow {
 1037        row: MultiBufferRow,
 1038        line_offset_from_top: u32,
 1039    },
 1040    MultiBufferPoint {
 1041        excerpt_id: ExcerptId,
 1042        position: Point,
 1043        anchor: text::Anchor,
 1044        line_offset_from_top: u32,
 1045    },
 1046}
 1047
 1048pub enum MultibufferSelectionMode {
 1049    First,
 1050    All,
 1051}
 1052
 1053impl Editor {
 1054    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1055        let buffer = cx.new(|cx| Buffer::local("", cx));
 1056        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1057        Self::new(
 1058            EditorMode::SingleLine { auto_width: false },
 1059            buffer,
 1060            None,
 1061            false,
 1062            window,
 1063            cx,
 1064        )
 1065    }
 1066
 1067    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1068        let buffer = cx.new(|cx| Buffer::local("", cx));
 1069        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1070        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1071    }
 1072
 1073    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1074        let buffer = cx.new(|cx| Buffer::local("", cx));
 1075        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1076        Self::new(
 1077            EditorMode::SingleLine { auto_width: true },
 1078            buffer,
 1079            None,
 1080            false,
 1081            window,
 1082            cx,
 1083        )
 1084    }
 1085
 1086    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1087        let buffer = cx.new(|cx| Buffer::local("", cx));
 1088        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1089        Self::new(
 1090            EditorMode::AutoHeight { max_lines },
 1091            buffer,
 1092            None,
 1093            false,
 1094            window,
 1095            cx,
 1096        )
 1097    }
 1098
 1099    pub fn for_buffer(
 1100        buffer: Entity<Buffer>,
 1101        project: Option<Entity<Project>>,
 1102        window: &mut Window,
 1103        cx: &mut Context<Self>,
 1104    ) -> Self {
 1105        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1106        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1107    }
 1108
 1109    pub fn for_multibuffer(
 1110        buffer: Entity<MultiBuffer>,
 1111        project: Option<Entity<Project>>,
 1112        show_excerpt_controls: bool,
 1113        window: &mut Window,
 1114        cx: &mut Context<Self>,
 1115    ) -> Self {
 1116        Self::new(
 1117            EditorMode::Full,
 1118            buffer,
 1119            project,
 1120            show_excerpt_controls,
 1121            window,
 1122            cx,
 1123        )
 1124    }
 1125
 1126    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1127        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1128        let mut clone = Self::new(
 1129            self.mode,
 1130            self.buffer.clone(),
 1131            self.project.clone(),
 1132            show_excerpt_controls,
 1133            window,
 1134            cx,
 1135        );
 1136        self.display_map.update(cx, |display_map, cx| {
 1137            let snapshot = display_map.snapshot(cx);
 1138            clone.display_map.update(cx, |display_map, cx| {
 1139                display_map.set_state(&snapshot, cx);
 1140            });
 1141        });
 1142        clone.selections.clone_state(&self.selections);
 1143        clone.scroll_manager.clone_state(&self.scroll_manager);
 1144        clone.searchable = self.searchable;
 1145        clone
 1146    }
 1147
 1148    pub fn new(
 1149        mode: EditorMode,
 1150        buffer: Entity<MultiBuffer>,
 1151        project: Option<Entity<Project>>,
 1152        show_excerpt_controls: bool,
 1153        window: &mut Window,
 1154        cx: &mut Context<Self>,
 1155    ) -> Self {
 1156        let style = window.text_style();
 1157        let font_size = style.font_size.to_pixels(window.rem_size());
 1158        let editor = cx.entity().downgrade();
 1159        let fold_placeholder = FoldPlaceholder {
 1160            constrain_width: true,
 1161            render: Arc::new(move |fold_id, fold_range, cx| {
 1162                let editor = editor.clone();
 1163                div()
 1164                    .id(fold_id)
 1165                    .bg(cx.theme().colors().ghost_element_background)
 1166                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1167                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1168                    .rounded_sm()
 1169                    .size_full()
 1170                    .cursor_pointer()
 1171                    .child("")
 1172                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1173                    .on_click(move |_, _window, cx| {
 1174                        editor
 1175                            .update(cx, |editor, cx| {
 1176                                editor.unfold_ranges(
 1177                                    &[fold_range.start..fold_range.end],
 1178                                    true,
 1179                                    false,
 1180                                    cx,
 1181                                );
 1182                                cx.stop_propagation();
 1183                            })
 1184                            .ok();
 1185                    })
 1186                    .into_any()
 1187            }),
 1188            merge_adjacent: true,
 1189            ..Default::default()
 1190        };
 1191        let display_map = cx.new(|cx| {
 1192            DisplayMap::new(
 1193                buffer.clone(),
 1194                style.font(),
 1195                font_size,
 1196                None,
 1197                show_excerpt_controls,
 1198                FILE_HEADER_HEIGHT,
 1199                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1200                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1201                fold_placeholder,
 1202                cx,
 1203            )
 1204        });
 1205
 1206        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1207
 1208        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1209
 1210        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1211            .then(|| language_settings::SoftWrap::None);
 1212
 1213        let mut project_subscriptions = Vec::new();
 1214        if mode == EditorMode::Full {
 1215            if let Some(project) = project.as_ref() {
 1216                if buffer.read(cx).is_singleton() {
 1217                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1218                        cx.emit(EditorEvent::TitleChanged);
 1219                    }));
 1220                }
 1221                project_subscriptions.push(cx.subscribe_in(
 1222                    project,
 1223                    window,
 1224                    |editor, _, event, window, cx| {
 1225                        if let project::Event::RefreshInlayHints = event {
 1226                            editor
 1227                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1228                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1229                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1230                                let focus_handle = editor.focus_handle(cx);
 1231                                if focus_handle.is_focused(window) {
 1232                                    let snapshot = buffer.read(cx).snapshot();
 1233                                    for (range, snippet) in snippet_edits {
 1234                                        let editor_range =
 1235                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1236                                        editor
 1237                                            .insert_snippet(
 1238                                                &[editor_range],
 1239                                                snippet.clone(),
 1240                                                window,
 1241                                                cx,
 1242                                            )
 1243                                            .ok();
 1244                                    }
 1245                                }
 1246                            }
 1247                        }
 1248                    },
 1249                ));
 1250                if let Some(task_inventory) = project
 1251                    .read(cx)
 1252                    .task_store()
 1253                    .read(cx)
 1254                    .task_inventory()
 1255                    .cloned()
 1256                {
 1257                    project_subscriptions.push(cx.observe_in(
 1258                        &task_inventory,
 1259                        window,
 1260                        |editor, _, window, cx| {
 1261                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1262                        },
 1263                    ));
 1264                }
 1265            }
 1266        }
 1267
 1268        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1269
 1270        let inlay_hint_settings =
 1271            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1272        let focus_handle = cx.focus_handle();
 1273        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1274            .detach();
 1275        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1276            .detach();
 1277        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1278            .detach();
 1279        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1280            .detach();
 1281
 1282        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1283            Some(false)
 1284        } else {
 1285            None
 1286        };
 1287
 1288        let mut code_action_providers = Vec::new();
 1289        let mut load_uncommitted_diff = None;
 1290        if let Some(project) = project.clone() {
 1291            load_uncommitted_diff = Some(
 1292                get_uncommitted_diff_for_buffer(
 1293                    &project,
 1294                    buffer.read(cx).all_buffers(),
 1295                    buffer.clone(),
 1296                    cx,
 1297                )
 1298                .shared(),
 1299            );
 1300            code_action_providers.push(Rc::new(project) as Rc<_>);
 1301        }
 1302
 1303        let mut this = Self {
 1304            focus_handle,
 1305            show_cursor_when_unfocused: false,
 1306            last_focused_descendant: None,
 1307            buffer: buffer.clone(),
 1308            display_map: display_map.clone(),
 1309            selections,
 1310            scroll_manager: ScrollManager::new(cx),
 1311            columnar_selection_tail: None,
 1312            add_selections_state: None,
 1313            select_next_state: None,
 1314            select_prev_state: None,
 1315            selection_history: Default::default(),
 1316            autoclose_regions: Default::default(),
 1317            snippet_stack: Default::default(),
 1318            select_larger_syntax_node_stack: Vec::new(),
 1319            ime_transaction: Default::default(),
 1320            active_diagnostics: None,
 1321            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1322            inline_diagnostics_update: Task::ready(()),
 1323            inline_diagnostics: Vec::new(),
 1324            soft_wrap_mode_override,
 1325            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1326            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1327            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1328            project,
 1329            blink_manager: blink_manager.clone(),
 1330            show_local_selections: true,
 1331            show_scrollbars: true,
 1332            mode,
 1333            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1334            show_gutter: mode == EditorMode::Full,
 1335            show_line_numbers: None,
 1336            use_relative_line_numbers: None,
 1337            show_git_diff_gutter: None,
 1338            show_code_actions: None,
 1339            show_runnables: None,
 1340            show_wrap_guides: None,
 1341            show_indent_guides,
 1342            placeholder_text: None,
 1343            highlight_order: 0,
 1344            highlighted_rows: HashMap::default(),
 1345            background_highlights: Default::default(),
 1346            gutter_highlights: TreeMap::default(),
 1347            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1348            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1349            nav_history: None,
 1350            context_menu: RefCell::new(None),
 1351            mouse_context_menu: None,
 1352            completion_tasks: Default::default(),
 1353            signature_help_state: SignatureHelpState::default(),
 1354            auto_signature_help: None,
 1355            find_all_references_task_sources: Vec::new(),
 1356            next_completion_id: 0,
 1357            next_inlay_id: 0,
 1358            code_action_providers,
 1359            available_code_actions: Default::default(),
 1360            code_actions_task: Default::default(),
 1361            selection_highlight_task: Default::default(),
 1362            document_highlights_task: Default::default(),
 1363            linked_editing_range_task: Default::default(),
 1364            pending_rename: Default::default(),
 1365            searchable: true,
 1366            cursor_shape: EditorSettings::get_global(cx)
 1367                .cursor_shape
 1368                .unwrap_or_default(),
 1369            current_line_highlight: None,
 1370            autoindent_mode: Some(AutoindentMode::EachLine),
 1371            collapse_matches: false,
 1372            workspace: None,
 1373            input_enabled: true,
 1374            use_modal_editing: mode == EditorMode::Full,
 1375            read_only: false,
 1376            use_autoclose: true,
 1377            use_auto_surround: true,
 1378            auto_replace_emoji_shortcode: false,
 1379            leader_peer_id: None,
 1380            remote_id: None,
 1381            hover_state: Default::default(),
 1382            pending_mouse_down: None,
 1383            hovered_link_state: Default::default(),
 1384            edit_prediction_provider: None,
 1385            active_inline_completion: None,
 1386            stale_inline_completion_in_menu: None,
 1387            edit_prediction_preview: EditPredictionPreview::Inactive,
 1388            inline_diagnostics_enabled: mode == EditorMode::Full,
 1389            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1390
 1391            gutter_hovered: false,
 1392            pixel_position_of_newest_cursor: None,
 1393            last_bounds: None,
 1394            last_position_map: None,
 1395            expect_bounds_change: None,
 1396            gutter_dimensions: GutterDimensions::default(),
 1397            style: None,
 1398            show_cursor_names: false,
 1399            hovered_cursors: Default::default(),
 1400            next_editor_action_id: EditorActionId::default(),
 1401            editor_actions: Rc::default(),
 1402            inline_completions_hidden_for_vim_mode: false,
 1403            show_inline_completions_override: None,
 1404            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1405            edit_prediction_settings: EditPredictionSettings::Disabled,
 1406            edit_prediction_cursor_on_leading_whitespace: false,
 1407            edit_prediction_requires_modifier_in_leading_space: true,
 1408            custom_context_menu: None,
 1409            show_git_blame_gutter: false,
 1410            show_git_blame_inline: false,
 1411            show_selection_menu: None,
 1412            show_git_blame_inline_delay_task: None,
 1413            git_blame_inline_tooltip: None,
 1414            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1415            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1416                .session
 1417                .restore_unsaved_buffers,
 1418            blame: None,
 1419            blame_subscription: None,
 1420            tasks: Default::default(),
 1421            _subscriptions: vec![
 1422                cx.observe(&buffer, Self::on_buffer_changed),
 1423                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1424                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1425                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1426                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1427                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1428                cx.observe_window_activation(window, |editor, window, cx| {
 1429                    let active = window.is_window_active();
 1430                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1431                        if active {
 1432                            blink_manager.enable(cx);
 1433                        } else {
 1434                            blink_manager.disable(cx);
 1435                        }
 1436                    });
 1437                }),
 1438            ],
 1439            tasks_update_task: None,
 1440            linked_edit_ranges: Default::default(),
 1441            in_project_search: false,
 1442            previous_search_ranges: None,
 1443            breadcrumb_header: None,
 1444            focused_block: None,
 1445            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1446            addons: HashMap::default(),
 1447            registered_buffers: HashMap::default(),
 1448            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1449            selection_mark_mode: false,
 1450            toggle_fold_multiple_buffers: Task::ready(()),
 1451            serialize_selections: Task::ready(()),
 1452            text_style_refinement: None,
 1453            load_diff_task: load_uncommitted_diff,
 1454        };
 1455        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1456        this._subscriptions.extend(project_subscriptions);
 1457
 1458        this.end_selection(window, cx);
 1459        this.scroll_manager.show_scrollbar(window, cx);
 1460
 1461        if mode == EditorMode::Full {
 1462            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1463            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1464
 1465            if this.git_blame_inline_enabled {
 1466                this.git_blame_inline_enabled = true;
 1467                this.start_git_blame_inline(false, window, cx);
 1468            }
 1469
 1470            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1471                if let Some(project) = this.project.as_ref() {
 1472                    let handle = project.update(cx, |project, cx| {
 1473                        project.register_buffer_with_language_servers(&buffer, cx)
 1474                    });
 1475                    this.registered_buffers
 1476                        .insert(buffer.read(cx).remote_id(), handle);
 1477                }
 1478            }
 1479        }
 1480
 1481        this.report_editor_event("Editor Opened", None, cx);
 1482        this
 1483    }
 1484
 1485    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1486        self.mouse_context_menu
 1487            .as_ref()
 1488            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1489    }
 1490
 1491    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1492        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1493    }
 1494
 1495    fn key_context_internal(
 1496        &self,
 1497        has_active_edit_prediction: bool,
 1498        window: &Window,
 1499        cx: &App,
 1500    ) -> KeyContext {
 1501        let mut key_context = KeyContext::new_with_defaults();
 1502        key_context.add("Editor");
 1503        let mode = match self.mode {
 1504            EditorMode::SingleLine { .. } => "single_line",
 1505            EditorMode::AutoHeight { .. } => "auto_height",
 1506            EditorMode::Full => "full",
 1507        };
 1508
 1509        if EditorSettings::jupyter_enabled(cx) {
 1510            key_context.add("jupyter");
 1511        }
 1512
 1513        key_context.set("mode", mode);
 1514        if self.pending_rename.is_some() {
 1515            key_context.add("renaming");
 1516        }
 1517
 1518        match self.context_menu.borrow().as_ref() {
 1519            Some(CodeContextMenu::Completions(_)) => {
 1520                key_context.add("menu");
 1521                key_context.add("showing_completions");
 1522            }
 1523            Some(CodeContextMenu::CodeActions(_)) => {
 1524                key_context.add("menu");
 1525                key_context.add("showing_code_actions")
 1526            }
 1527            None => {}
 1528        }
 1529
 1530        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1531        if !self.focus_handle(cx).contains_focused(window, cx)
 1532            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1533        {
 1534            for addon in self.addons.values() {
 1535                addon.extend_key_context(&mut key_context, cx)
 1536            }
 1537        }
 1538
 1539        if let Some(extension) = self
 1540            .buffer
 1541            .read(cx)
 1542            .as_singleton()
 1543            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1544        {
 1545            key_context.set("extension", extension.to_string());
 1546        }
 1547
 1548        if has_active_edit_prediction {
 1549            if self.edit_prediction_in_conflict() {
 1550                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1551            } else {
 1552                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1553                key_context.add("copilot_suggestion");
 1554            }
 1555        }
 1556
 1557        if self.selection_mark_mode {
 1558            key_context.add("selection_mode");
 1559        }
 1560
 1561        key_context
 1562    }
 1563
 1564    pub fn edit_prediction_in_conflict(&self) -> bool {
 1565        if !self.show_edit_predictions_in_menu() {
 1566            return false;
 1567        }
 1568
 1569        let showing_completions = self
 1570            .context_menu
 1571            .borrow()
 1572            .as_ref()
 1573            .map_or(false, |context| {
 1574                matches!(context, CodeContextMenu::Completions(_))
 1575            });
 1576
 1577        showing_completions
 1578            || self.edit_prediction_requires_modifier()
 1579            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1580            // bindings to insert tab characters.
 1581            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1582    }
 1583
 1584    pub fn accept_edit_prediction_keybind(
 1585        &self,
 1586        window: &Window,
 1587        cx: &App,
 1588    ) -> AcceptEditPredictionBinding {
 1589        let key_context = self.key_context_internal(true, window, cx);
 1590        let in_conflict = self.edit_prediction_in_conflict();
 1591
 1592        AcceptEditPredictionBinding(
 1593            window
 1594                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1595                .into_iter()
 1596                .filter(|binding| {
 1597                    !in_conflict
 1598                        || binding
 1599                            .keystrokes()
 1600                            .first()
 1601                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1602                })
 1603                .rev()
 1604                .min_by_key(|binding| {
 1605                    binding
 1606                        .keystrokes()
 1607                        .first()
 1608                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1609                }),
 1610        )
 1611    }
 1612
 1613    pub fn new_file(
 1614        workspace: &mut Workspace,
 1615        _: &workspace::NewFile,
 1616        window: &mut Window,
 1617        cx: &mut Context<Workspace>,
 1618    ) {
 1619        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1620            "Failed to create buffer",
 1621            window,
 1622            cx,
 1623            |e, _, _| match e.error_code() {
 1624                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1625                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1626                e.error_tag("required").unwrap_or("the latest version")
 1627            )),
 1628                _ => None,
 1629            },
 1630        );
 1631    }
 1632
 1633    pub fn new_in_workspace(
 1634        workspace: &mut Workspace,
 1635        window: &mut Window,
 1636        cx: &mut Context<Workspace>,
 1637    ) -> Task<Result<Entity<Editor>>> {
 1638        let project = workspace.project().clone();
 1639        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1640
 1641        cx.spawn_in(window, |workspace, mut cx| async move {
 1642            let buffer = create.await?;
 1643            workspace.update_in(&mut cx, |workspace, window, cx| {
 1644                let editor =
 1645                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1646                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1647                editor
 1648            })
 1649        })
 1650    }
 1651
 1652    fn new_file_vertical(
 1653        workspace: &mut Workspace,
 1654        _: &workspace::NewFileSplitVertical,
 1655        window: &mut Window,
 1656        cx: &mut Context<Workspace>,
 1657    ) {
 1658        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1659    }
 1660
 1661    fn new_file_horizontal(
 1662        workspace: &mut Workspace,
 1663        _: &workspace::NewFileSplitHorizontal,
 1664        window: &mut Window,
 1665        cx: &mut Context<Workspace>,
 1666    ) {
 1667        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1668    }
 1669
 1670    fn new_file_in_direction(
 1671        workspace: &mut Workspace,
 1672        direction: SplitDirection,
 1673        window: &mut Window,
 1674        cx: &mut Context<Workspace>,
 1675    ) {
 1676        let project = workspace.project().clone();
 1677        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1678
 1679        cx.spawn_in(window, |workspace, mut cx| async move {
 1680            let buffer = create.await?;
 1681            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1682                workspace.split_item(
 1683                    direction,
 1684                    Box::new(
 1685                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1686                    ),
 1687                    window,
 1688                    cx,
 1689                )
 1690            })?;
 1691            anyhow::Ok(())
 1692        })
 1693        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1694            match e.error_code() {
 1695                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1696                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1697                e.error_tag("required").unwrap_or("the latest version")
 1698            )),
 1699                _ => None,
 1700            }
 1701        });
 1702    }
 1703
 1704    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1705        self.leader_peer_id
 1706    }
 1707
 1708    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1709        &self.buffer
 1710    }
 1711
 1712    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1713        self.workspace.as_ref()?.0.upgrade()
 1714    }
 1715
 1716    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1717        self.buffer().read(cx).title(cx)
 1718    }
 1719
 1720    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1721        let git_blame_gutter_max_author_length = self
 1722            .render_git_blame_gutter(cx)
 1723            .then(|| {
 1724                if let Some(blame) = self.blame.as_ref() {
 1725                    let max_author_length =
 1726                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1727                    Some(max_author_length)
 1728                } else {
 1729                    None
 1730                }
 1731            })
 1732            .flatten();
 1733
 1734        EditorSnapshot {
 1735            mode: self.mode,
 1736            show_gutter: self.show_gutter,
 1737            show_line_numbers: self.show_line_numbers,
 1738            show_git_diff_gutter: self.show_git_diff_gutter,
 1739            show_code_actions: self.show_code_actions,
 1740            show_runnables: self.show_runnables,
 1741            git_blame_gutter_max_author_length,
 1742            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1743            scroll_anchor: self.scroll_manager.anchor(),
 1744            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1745            placeholder_text: self.placeholder_text.clone(),
 1746            is_focused: self.focus_handle.is_focused(window),
 1747            current_line_highlight: self
 1748                .current_line_highlight
 1749                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1750            gutter_hovered: self.gutter_hovered,
 1751        }
 1752    }
 1753
 1754    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1755        self.buffer.read(cx).language_at(point, cx)
 1756    }
 1757
 1758    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1759        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1760    }
 1761
 1762    pub fn active_excerpt(
 1763        &self,
 1764        cx: &App,
 1765    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1766        self.buffer
 1767            .read(cx)
 1768            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1769    }
 1770
 1771    pub fn mode(&self) -> EditorMode {
 1772        self.mode
 1773    }
 1774
 1775    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1776        self.collaboration_hub.as_deref()
 1777    }
 1778
 1779    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1780        self.collaboration_hub = Some(hub);
 1781    }
 1782
 1783    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1784        self.in_project_search = in_project_search;
 1785    }
 1786
 1787    pub fn set_custom_context_menu(
 1788        &mut self,
 1789        f: impl 'static
 1790            + Fn(
 1791                &mut Self,
 1792                DisplayPoint,
 1793                &mut Window,
 1794                &mut Context<Self>,
 1795            ) -> Option<Entity<ui::ContextMenu>>,
 1796    ) {
 1797        self.custom_context_menu = Some(Box::new(f))
 1798    }
 1799
 1800    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1801        self.completion_provider = provider;
 1802    }
 1803
 1804    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1805        self.semantics_provider.clone()
 1806    }
 1807
 1808    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1809        self.semantics_provider = provider;
 1810    }
 1811
 1812    pub fn set_edit_prediction_provider<T>(
 1813        &mut self,
 1814        provider: Option<Entity<T>>,
 1815        window: &mut Window,
 1816        cx: &mut Context<Self>,
 1817    ) where
 1818        T: EditPredictionProvider,
 1819    {
 1820        self.edit_prediction_provider =
 1821            provider.map(|provider| RegisteredInlineCompletionProvider {
 1822                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1823                    if this.focus_handle.is_focused(window) {
 1824                        this.update_visible_inline_completion(window, cx);
 1825                    }
 1826                }),
 1827                provider: Arc::new(provider),
 1828            });
 1829        self.refresh_inline_completion(false, false, window, cx);
 1830    }
 1831
 1832    pub fn placeholder_text(&self) -> Option<&str> {
 1833        self.placeholder_text.as_deref()
 1834    }
 1835
 1836    pub fn set_placeholder_text(
 1837        &mut self,
 1838        placeholder_text: impl Into<Arc<str>>,
 1839        cx: &mut Context<Self>,
 1840    ) {
 1841        let placeholder_text = Some(placeholder_text.into());
 1842        if self.placeholder_text != placeholder_text {
 1843            self.placeholder_text = placeholder_text;
 1844            cx.notify();
 1845        }
 1846    }
 1847
 1848    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1849        self.cursor_shape = cursor_shape;
 1850
 1851        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1852        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1853
 1854        cx.notify();
 1855    }
 1856
 1857    pub fn set_current_line_highlight(
 1858        &mut self,
 1859        current_line_highlight: Option<CurrentLineHighlight>,
 1860    ) {
 1861        self.current_line_highlight = current_line_highlight;
 1862    }
 1863
 1864    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1865        self.collapse_matches = collapse_matches;
 1866    }
 1867
 1868    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1869        let buffers = self.buffer.read(cx).all_buffers();
 1870        let Some(project) = self.project.as_ref() else {
 1871            return;
 1872        };
 1873        project.update(cx, |project, cx| {
 1874            for buffer in buffers {
 1875                self.registered_buffers
 1876                    .entry(buffer.read(cx).remote_id())
 1877                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1878            }
 1879        })
 1880    }
 1881
 1882    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1883        if self.collapse_matches {
 1884            return range.start..range.start;
 1885        }
 1886        range.clone()
 1887    }
 1888
 1889    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1890        if self.display_map.read(cx).clip_at_line_ends != clip {
 1891            self.display_map
 1892                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1893        }
 1894    }
 1895
 1896    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1897        self.input_enabled = input_enabled;
 1898    }
 1899
 1900    pub fn set_inline_completions_hidden_for_vim_mode(
 1901        &mut self,
 1902        hidden: bool,
 1903        window: &mut Window,
 1904        cx: &mut Context<Self>,
 1905    ) {
 1906        if hidden != self.inline_completions_hidden_for_vim_mode {
 1907            self.inline_completions_hidden_for_vim_mode = hidden;
 1908            if hidden {
 1909                self.update_visible_inline_completion(window, cx);
 1910            } else {
 1911                self.refresh_inline_completion(true, false, window, cx);
 1912            }
 1913        }
 1914    }
 1915
 1916    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1917        self.menu_inline_completions_policy = value;
 1918    }
 1919
 1920    pub fn set_autoindent(&mut self, autoindent: bool) {
 1921        if autoindent {
 1922            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1923        } else {
 1924            self.autoindent_mode = None;
 1925        }
 1926    }
 1927
 1928    pub fn read_only(&self, cx: &App) -> bool {
 1929        self.read_only || self.buffer.read(cx).read_only()
 1930    }
 1931
 1932    pub fn set_read_only(&mut self, read_only: bool) {
 1933        self.read_only = read_only;
 1934    }
 1935
 1936    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1937        self.use_autoclose = autoclose;
 1938    }
 1939
 1940    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1941        self.use_auto_surround = auto_surround;
 1942    }
 1943
 1944    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1945        self.auto_replace_emoji_shortcode = auto_replace;
 1946    }
 1947
 1948    pub fn toggle_inline_completions(
 1949        &mut self,
 1950        _: &ToggleEditPrediction,
 1951        window: &mut Window,
 1952        cx: &mut Context<Self>,
 1953    ) {
 1954        if self.show_inline_completions_override.is_some() {
 1955            self.set_show_edit_predictions(None, window, cx);
 1956        } else {
 1957            let show_edit_predictions = !self.edit_predictions_enabled();
 1958            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1959        }
 1960    }
 1961
 1962    pub fn set_show_edit_predictions(
 1963        &mut self,
 1964        show_edit_predictions: Option<bool>,
 1965        window: &mut Window,
 1966        cx: &mut Context<Self>,
 1967    ) {
 1968        self.show_inline_completions_override = show_edit_predictions;
 1969
 1970        if let Some(false) = show_edit_predictions {
 1971            self.discard_inline_completion(false, cx);
 1972        } else {
 1973            self.refresh_inline_completion(false, true, window, cx);
 1974        }
 1975    }
 1976
 1977    fn inline_completions_disabled_in_scope(
 1978        &self,
 1979        buffer: &Entity<Buffer>,
 1980        buffer_position: language::Anchor,
 1981        cx: &App,
 1982    ) -> bool {
 1983        let snapshot = buffer.read(cx).snapshot();
 1984        let settings = snapshot.settings_at(buffer_position, cx);
 1985
 1986        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1987            return false;
 1988        };
 1989
 1990        scope.override_name().map_or(false, |scope_name| {
 1991            settings
 1992                .edit_predictions_disabled_in
 1993                .iter()
 1994                .any(|s| s == scope_name)
 1995        })
 1996    }
 1997
 1998    pub fn set_use_modal_editing(&mut self, to: bool) {
 1999        self.use_modal_editing = to;
 2000    }
 2001
 2002    pub fn use_modal_editing(&self) -> bool {
 2003        self.use_modal_editing
 2004    }
 2005
 2006    fn selections_did_change(
 2007        &mut self,
 2008        local: bool,
 2009        old_cursor_position: &Anchor,
 2010        show_completions: bool,
 2011        window: &mut Window,
 2012        cx: &mut Context<Self>,
 2013    ) {
 2014        window.invalidate_character_coordinates();
 2015
 2016        // Copy selections to primary selection buffer
 2017        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2018        if local {
 2019            let selections = self.selections.all::<usize>(cx);
 2020            let buffer_handle = self.buffer.read(cx).read(cx);
 2021
 2022            let mut text = String::new();
 2023            for (index, selection) in selections.iter().enumerate() {
 2024                let text_for_selection = buffer_handle
 2025                    .text_for_range(selection.start..selection.end)
 2026                    .collect::<String>();
 2027
 2028                text.push_str(&text_for_selection);
 2029                if index != selections.len() - 1 {
 2030                    text.push('\n');
 2031                }
 2032            }
 2033
 2034            if !text.is_empty() {
 2035                cx.write_to_primary(ClipboardItem::new_string(text));
 2036            }
 2037        }
 2038
 2039        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2040            self.buffer.update(cx, |buffer, cx| {
 2041                buffer.set_active_selections(
 2042                    &self.selections.disjoint_anchors(),
 2043                    self.selections.line_mode,
 2044                    self.cursor_shape,
 2045                    cx,
 2046                )
 2047            });
 2048        }
 2049        let display_map = self
 2050            .display_map
 2051            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2052        let buffer = &display_map.buffer_snapshot;
 2053        self.add_selections_state = None;
 2054        self.select_next_state = None;
 2055        self.select_prev_state = None;
 2056        self.select_larger_syntax_node_stack.clear();
 2057        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2058        self.snippet_stack
 2059            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2060        self.take_rename(false, window, cx);
 2061
 2062        let new_cursor_position = self.selections.newest_anchor().head();
 2063
 2064        self.push_to_nav_history(
 2065            *old_cursor_position,
 2066            Some(new_cursor_position.to_point(buffer)),
 2067            cx,
 2068        );
 2069
 2070        if local {
 2071            let new_cursor_position = self.selections.newest_anchor().head();
 2072            let mut context_menu = self.context_menu.borrow_mut();
 2073            let completion_menu = match context_menu.as_ref() {
 2074                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2075                _ => {
 2076                    *context_menu = None;
 2077                    None
 2078                }
 2079            };
 2080            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2081                if !self.registered_buffers.contains_key(&buffer_id) {
 2082                    if let Some(project) = self.project.as_ref() {
 2083                        project.update(cx, |project, cx| {
 2084                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2085                                return;
 2086                            };
 2087                            self.registered_buffers.insert(
 2088                                buffer_id,
 2089                                project.register_buffer_with_language_servers(&buffer, cx),
 2090                            );
 2091                        })
 2092                    }
 2093                }
 2094            }
 2095
 2096            if let Some(completion_menu) = completion_menu {
 2097                let cursor_position = new_cursor_position.to_offset(buffer);
 2098                let (word_range, kind) =
 2099                    buffer.surrounding_word(completion_menu.initial_position, true);
 2100                if kind == Some(CharKind::Word)
 2101                    && word_range.to_inclusive().contains(&cursor_position)
 2102                {
 2103                    let mut completion_menu = completion_menu.clone();
 2104                    drop(context_menu);
 2105
 2106                    let query = Self::completion_query(buffer, cursor_position);
 2107                    cx.spawn(move |this, mut cx| async move {
 2108                        completion_menu
 2109                            .filter(query.as_deref(), cx.background_executor().clone())
 2110                            .await;
 2111
 2112                        this.update(&mut cx, |this, cx| {
 2113                            let mut context_menu = this.context_menu.borrow_mut();
 2114                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2115                            else {
 2116                                return;
 2117                            };
 2118
 2119                            if menu.id > completion_menu.id {
 2120                                return;
 2121                            }
 2122
 2123                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2124                            drop(context_menu);
 2125                            cx.notify();
 2126                        })
 2127                    })
 2128                    .detach();
 2129
 2130                    if show_completions {
 2131                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2132                    }
 2133                } else {
 2134                    drop(context_menu);
 2135                    self.hide_context_menu(window, cx);
 2136                }
 2137            } else {
 2138                drop(context_menu);
 2139            }
 2140
 2141            hide_hover(self, cx);
 2142
 2143            if old_cursor_position.to_display_point(&display_map).row()
 2144                != new_cursor_position.to_display_point(&display_map).row()
 2145            {
 2146                self.available_code_actions.take();
 2147            }
 2148            self.refresh_code_actions(window, cx);
 2149            self.refresh_document_highlights(cx);
 2150            self.refresh_selected_text_highlights(window, cx);
 2151            refresh_matching_bracket_highlights(self, window, cx);
 2152            self.update_visible_inline_completion(window, cx);
 2153            self.edit_prediction_requires_modifier_in_leading_space = true;
 2154            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2155            if self.git_blame_inline_enabled {
 2156                self.start_inline_blame_timer(window, cx);
 2157            }
 2158        }
 2159
 2160        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2161        cx.emit(EditorEvent::SelectionsChanged { local });
 2162
 2163        let selections = &self.selections.disjoint;
 2164        if selections.len() == 1 {
 2165            cx.emit(SearchEvent::ActiveMatchChanged)
 2166        }
 2167        if local
 2168            && self.is_singleton(cx)
 2169            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2170        {
 2171            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2172                let background_executor = cx.background_executor().clone();
 2173                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2174                let snapshot = self.buffer().read(cx).snapshot(cx);
 2175                let selections = selections.clone();
 2176                self.serialize_selections = cx.background_spawn(async move {
 2177                    background_executor.timer(Duration::from_millis(100)).await;
 2178                    let selections = selections
 2179                        .iter()
 2180                        .map(|selection| {
 2181                            (
 2182                                selection.start.to_offset(&snapshot),
 2183                                selection.end.to_offset(&snapshot),
 2184                            )
 2185                        })
 2186                        .collect();
 2187                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2188                        .await
 2189                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2190                        .log_err();
 2191                });
 2192            }
 2193        }
 2194
 2195        cx.notify();
 2196    }
 2197
 2198    pub fn change_selections<R>(
 2199        &mut self,
 2200        autoscroll: Option<Autoscroll>,
 2201        window: &mut Window,
 2202        cx: &mut Context<Self>,
 2203        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2204    ) -> R {
 2205        self.change_selections_inner(autoscroll, true, window, cx, change)
 2206    }
 2207
 2208    fn change_selections_inner<R>(
 2209        &mut self,
 2210        autoscroll: Option<Autoscroll>,
 2211        request_completions: bool,
 2212        window: &mut Window,
 2213        cx: &mut Context<Self>,
 2214        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2215    ) -> R {
 2216        let old_cursor_position = self.selections.newest_anchor().head();
 2217        self.push_to_selection_history();
 2218
 2219        let (changed, result) = self.selections.change_with(cx, change);
 2220
 2221        if changed {
 2222            if let Some(autoscroll) = autoscroll {
 2223                self.request_autoscroll(autoscroll, cx);
 2224            }
 2225            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2226
 2227            if self.should_open_signature_help_automatically(
 2228                &old_cursor_position,
 2229                self.signature_help_state.backspace_pressed(),
 2230                cx,
 2231            ) {
 2232                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2233            }
 2234            self.signature_help_state.set_backspace_pressed(false);
 2235        }
 2236
 2237        result
 2238    }
 2239
 2240    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2241    where
 2242        I: IntoIterator<Item = (Range<S>, T)>,
 2243        S: ToOffset,
 2244        T: Into<Arc<str>>,
 2245    {
 2246        if self.read_only(cx) {
 2247            return;
 2248        }
 2249
 2250        self.buffer
 2251            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2252    }
 2253
 2254    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2255    where
 2256        I: IntoIterator<Item = (Range<S>, T)>,
 2257        S: ToOffset,
 2258        T: Into<Arc<str>>,
 2259    {
 2260        if self.read_only(cx) {
 2261            return;
 2262        }
 2263
 2264        self.buffer.update(cx, |buffer, cx| {
 2265            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2266        });
 2267    }
 2268
 2269    pub fn edit_with_block_indent<I, S, T>(
 2270        &mut self,
 2271        edits: I,
 2272        original_start_columns: Vec<u32>,
 2273        cx: &mut Context<Self>,
 2274    ) where
 2275        I: IntoIterator<Item = (Range<S>, T)>,
 2276        S: ToOffset,
 2277        T: Into<Arc<str>>,
 2278    {
 2279        if self.read_only(cx) {
 2280            return;
 2281        }
 2282
 2283        self.buffer.update(cx, |buffer, cx| {
 2284            buffer.edit(
 2285                edits,
 2286                Some(AutoindentMode::Block {
 2287                    original_start_columns,
 2288                }),
 2289                cx,
 2290            )
 2291        });
 2292    }
 2293
 2294    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2295        self.hide_context_menu(window, cx);
 2296
 2297        match phase {
 2298            SelectPhase::Begin {
 2299                position,
 2300                add,
 2301                click_count,
 2302            } => self.begin_selection(position, add, click_count, window, cx),
 2303            SelectPhase::BeginColumnar {
 2304                position,
 2305                goal_column,
 2306                reset,
 2307            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2308            SelectPhase::Extend {
 2309                position,
 2310                click_count,
 2311            } => self.extend_selection(position, click_count, window, cx),
 2312            SelectPhase::Update {
 2313                position,
 2314                goal_column,
 2315                scroll_delta,
 2316            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2317            SelectPhase::End => self.end_selection(window, cx),
 2318        }
 2319    }
 2320
 2321    fn extend_selection(
 2322        &mut self,
 2323        position: DisplayPoint,
 2324        click_count: usize,
 2325        window: &mut Window,
 2326        cx: &mut Context<Self>,
 2327    ) {
 2328        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2329        let tail = self.selections.newest::<usize>(cx).tail();
 2330        self.begin_selection(position, false, click_count, window, cx);
 2331
 2332        let position = position.to_offset(&display_map, Bias::Left);
 2333        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2334
 2335        let mut pending_selection = self
 2336            .selections
 2337            .pending_anchor()
 2338            .expect("extend_selection not called with pending selection");
 2339        if position >= tail {
 2340            pending_selection.start = tail_anchor;
 2341        } else {
 2342            pending_selection.end = tail_anchor;
 2343            pending_selection.reversed = true;
 2344        }
 2345
 2346        let mut pending_mode = self.selections.pending_mode().unwrap();
 2347        match &mut pending_mode {
 2348            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2349            _ => {}
 2350        }
 2351
 2352        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2353            s.set_pending(pending_selection, pending_mode)
 2354        });
 2355    }
 2356
 2357    fn begin_selection(
 2358        &mut self,
 2359        position: DisplayPoint,
 2360        add: bool,
 2361        click_count: usize,
 2362        window: &mut Window,
 2363        cx: &mut Context<Self>,
 2364    ) {
 2365        if !self.focus_handle.is_focused(window) {
 2366            self.last_focused_descendant = None;
 2367            window.focus(&self.focus_handle);
 2368        }
 2369
 2370        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2371        let buffer = &display_map.buffer_snapshot;
 2372        let newest_selection = self.selections.newest_anchor().clone();
 2373        let position = display_map.clip_point(position, Bias::Left);
 2374
 2375        let start;
 2376        let end;
 2377        let mode;
 2378        let mut auto_scroll;
 2379        match click_count {
 2380            1 => {
 2381                start = buffer.anchor_before(position.to_point(&display_map));
 2382                end = start;
 2383                mode = SelectMode::Character;
 2384                auto_scroll = true;
 2385            }
 2386            2 => {
 2387                let range = movement::surrounding_word(&display_map, position);
 2388                start = buffer.anchor_before(range.start.to_point(&display_map));
 2389                end = buffer.anchor_before(range.end.to_point(&display_map));
 2390                mode = SelectMode::Word(start..end);
 2391                auto_scroll = true;
 2392            }
 2393            3 => {
 2394                let position = display_map
 2395                    .clip_point(position, Bias::Left)
 2396                    .to_point(&display_map);
 2397                let line_start = display_map.prev_line_boundary(position).0;
 2398                let next_line_start = buffer.clip_point(
 2399                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2400                    Bias::Left,
 2401                );
 2402                start = buffer.anchor_before(line_start);
 2403                end = buffer.anchor_before(next_line_start);
 2404                mode = SelectMode::Line(start..end);
 2405                auto_scroll = true;
 2406            }
 2407            _ => {
 2408                start = buffer.anchor_before(0);
 2409                end = buffer.anchor_before(buffer.len());
 2410                mode = SelectMode::All;
 2411                auto_scroll = false;
 2412            }
 2413        }
 2414        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2415
 2416        let point_to_delete: Option<usize> = {
 2417            let selected_points: Vec<Selection<Point>> =
 2418                self.selections.disjoint_in_range(start..end, cx);
 2419
 2420            if !add || click_count > 1 {
 2421                None
 2422            } else if !selected_points.is_empty() {
 2423                Some(selected_points[0].id)
 2424            } else {
 2425                let clicked_point_already_selected =
 2426                    self.selections.disjoint.iter().find(|selection| {
 2427                        selection.start.to_point(buffer) == start.to_point(buffer)
 2428                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2429                    });
 2430
 2431                clicked_point_already_selected.map(|selection| selection.id)
 2432            }
 2433        };
 2434
 2435        let selections_count = self.selections.count();
 2436
 2437        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2438            if let Some(point_to_delete) = point_to_delete {
 2439                s.delete(point_to_delete);
 2440
 2441                if selections_count == 1 {
 2442                    s.set_pending_anchor_range(start..end, mode);
 2443                }
 2444            } else {
 2445                if !add {
 2446                    s.clear_disjoint();
 2447                } else if click_count > 1 {
 2448                    s.delete(newest_selection.id)
 2449                }
 2450
 2451                s.set_pending_anchor_range(start..end, mode);
 2452            }
 2453        });
 2454    }
 2455
 2456    fn begin_columnar_selection(
 2457        &mut self,
 2458        position: DisplayPoint,
 2459        goal_column: u32,
 2460        reset: bool,
 2461        window: &mut Window,
 2462        cx: &mut Context<Self>,
 2463    ) {
 2464        if !self.focus_handle.is_focused(window) {
 2465            self.last_focused_descendant = None;
 2466            window.focus(&self.focus_handle);
 2467        }
 2468
 2469        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2470
 2471        if reset {
 2472            let pointer_position = display_map
 2473                .buffer_snapshot
 2474                .anchor_before(position.to_point(&display_map));
 2475
 2476            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2477                s.clear_disjoint();
 2478                s.set_pending_anchor_range(
 2479                    pointer_position..pointer_position,
 2480                    SelectMode::Character,
 2481                );
 2482            });
 2483        }
 2484
 2485        let tail = self.selections.newest::<Point>(cx).tail();
 2486        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2487
 2488        if !reset {
 2489            self.select_columns(
 2490                tail.to_display_point(&display_map),
 2491                position,
 2492                goal_column,
 2493                &display_map,
 2494                window,
 2495                cx,
 2496            );
 2497        }
 2498    }
 2499
 2500    fn update_selection(
 2501        &mut self,
 2502        position: DisplayPoint,
 2503        goal_column: u32,
 2504        scroll_delta: gpui::Point<f32>,
 2505        window: &mut Window,
 2506        cx: &mut Context<Self>,
 2507    ) {
 2508        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2509
 2510        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2511            let tail = tail.to_display_point(&display_map);
 2512            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2513        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2514            let buffer = self.buffer.read(cx).snapshot(cx);
 2515            let head;
 2516            let tail;
 2517            let mode = self.selections.pending_mode().unwrap();
 2518            match &mode {
 2519                SelectMode::Character => {
 2520                    head = position.to_point(&display_map);
 2521                    tail = pending.tail().to_point(&buffer);
 2522                }
 2523                SelectMode::Word(original_range) => {
 2524                    let original_display_range = original_range.start.to_display_point(&display_map)
 2525                        ..original_range.end.to_display_point(&display_map);
 2526                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2527                        ..original_display_range.end.to_point(&display_map);
 2528                    if movement::is_inside_word(&display_map, position)
 2529                        || original_display_range.contains(&position)
 2530                    {
 2531                        let word_range = movement::surrounding_word(&display_map, position);
 2532                        if word_range.start < original_display_range.start {
 2533                            head = word_range.start.to_point(&display_map);
 2534                        } else {
 2535                            head = word_range.end.to_point(&display_map);
 2536                        }
 2537                    } else {
 2538                        head = position.to_point(&display_map);
 2539                    }
 2540
 2541                    if head <= original_buffer_range.start {
 2542                        tail = original_buffer_range.end;
 2543                    } else {
 2544                        tail = original_buffer_range.start;
 2545                    }
 2546                }
 2547                SelectMode::Line(original_range) => {
 2548                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2549
 2550                    let position = display_map
 2551                        .clip_point(position, Bias::Left)
 2552                        .to_point(&display_map);
 2553                    let line_start = display_map.prev_line_boundary(position).0;
 2554                    let next_line_start = buffer.clip_point(
 2555                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2556                        Bias::Left,
 2557                    );
 2558
 2559                    if line_start < original_range.start {
 2560                        head = line_start
 2561                    } else {
 2562                        head = next_line_start
 2563                    }
 2564
 2565                    if head <= original_range.start {
 2566                        tail = original_range.end;
 2567                    } else {
 2568                        tail = original_range.start;
 2569                    }
 2570                }
 2571                SelectMode::All => {
 2572                    return;
 2573                }
 2574            };
 2575
 2576            if head < tail {
 2577                pending.start = buffer.anchor_before(head);
 2578                pending.end = buffer.anchor_before(tail);
 2579                pending.reversed = true;
 2580            } else {
 2581                pending.start = buffer.anchor_before(tail);
 2582                pending.end = buffer.anchor_before(head);
 2583                pending.reversed = false;
 2584            }
 2585
 2586            self.change_selections(None, window, cx, |s| {
 2587                s.set_pending(pending, mode);
 2588            });
 2589        } else {
 2590            log::error!("update_selection dispatched with no pending selection");
 2591            return;
 2592        }
 2593
 2594        self.apply_scroll_delta(scroll_delta, window, cx);
 2595        cx.notify();
 2596    }
 2597
 2598    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2599        self.columnar_selection_tail.take();
 2600        if self.selections.pending_anchor().is_some() {
 2601            let selections = self.selections.all::<usize>(cx);
 2602            self.change_selections(None, window, cx, |s| {
 2603                s.select(selections);
 2604                s.clear_pending();
 2605            });
 2606        }
 2607    }
 2608
 2609    fn select_columns(
 2610        &mut self,
 2611        tail: DisplayPoint,
 2612        head: DisplayPoint,
 2613        goal_column: u32,
 2614        display_map: &DisplaySnapshot,
 2615        window: &mut Window,
 2616        cx: &mut Context<Self>,
 2617    ) {
 2618        let start_row = cmp::min(tail.row(), head.row());
 2619        let end_row = cmp::max(tail.row(), head.row());
 2620        let start_column = cmp::min(tail.column(), goal_column);
 2621        let end_column = cmp::max(tail.column(), goal_column);
 2622        let reversed = start_column < tail.column();
 2623
 2624        let selection_ranges = (start_row.0..=end_row.0)
 2625            .map(DisplayRow)
 2626            .filter_map(|row| {
 2627                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2628                    let start = display_map
 2629                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2630                        .to_point(display_map);
 2631                    let end = display_map
 2632                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2633                        .to_point(display_map);
 2634                    if reversed {
 2635                        Some(end..start)
 2636                    } else {
 2637                        Some(start..end)
 2638                    }
 2639                } else {
 2640                    None
 2641                }
 2642            })
 2643            .collect::<Vec<_>>();
 2644
 2645        self.change_selections(None, window, cx, |s| {
 2646            s.select_ranges(selection_ranges);
 2647        });
 2648        cx.notify();
 2649    }
 2650
 2651    pub fn has_pending_nonempty_selection(&self) -> bool {
 2652        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2653            Some(Selection { start, end, .. }) => start != end,
 2654            None => false,
 2655        };
 2656
 2657        pending_nonempty_selection
 2658            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2659    }
 2660
 2661    pub fn has_pending_selection(&self) -> bool {
 2662        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2663    }
 2664
 2665    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2666        self.selection_mark_mode = false;
 2667
 2668        if self.clear_expanded_diff_hunks(cx) {
 2669            cx.notify();
 2670            return;
 2671        }
 2672        if self.dismiss_menus_and_popups(true, window, cx) {
 2673            return;
 2674        }
 2675
 2676        if self.mode == EditorMode::Full
 2677            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2678        {
 2679            return;
 2680        }
 2681
 2682        cx.propagate();
 2683    }
 2684
 2685    pub fn dismiss_menus_and_popups(
 2686        &mut self,
 2687        is_user_requested: bool,
 2688        window: &mut Window,
 2689        cx: &mut Context<Self>,
 2690    ) -> bool {
 2691        if self.take_rename(false, window, cx).is_some() {
 2692            return true;
 2693        }
 2694
 2695        if hide_hover(self, cx) {
 2696            return true;
 2697        }
 2698
 2699        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2700            return true;
 2701        }
 2702
 2703        if self.hide_context_menu(window, cx).is_some() {
 2704            return true;
 2705        }
 2706
 2707        if self.mouse_context_menu.take().is_some() {
 2708            return true;
 2709        }
 2710
 2711        if is_user_requested && self.discard_inline_completion(true, cx) {
 2712            return true;
 2713        }
 2714
 2715        if self.snippet_stack.pop().is_some() {
 2716            return true;
 2717        }
 2718
 2719        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2720            self.dismiss_diagnostics(cx);
 2721            return true;
 2722        }
 2723
 2724        false
 2725    }
 2726
 2727    fn linked_editing_ranges_for(
 2728        &self,
 2729        selection: Range<text::Anchor>,
 2730        cx: &App,
 2731    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2732        if self.linked_edit_ranges.is_empty() {
 2733            return None;
 2734        }
 2735        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2736            selection.end.buffer_id.and_then(|end_buffer_id| {
 2737                if selection.start.buffer_id != Some(end_buffer_id) {
 2738                    return None;
 2739                }
 2740                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2741                let snapshot = buffer.read(cx).snapshot();
 2742                self.linked_edit_ranges
 2743                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2744                    .map(|ranges| (ranges, snapshot, buffer))
 2745            })?;
 2746        use text::ToOffset as TO;
 2747        // find offset from the start of current range to current cursor position
 2748        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2749
 2750        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2751        let start_difference = start_offset - start_byte_offset;
 2752        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2753        let end_difference = end_offset - start_byte_offset;
 2754        // Current range has associated linked ranges.
 2755        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2756        for range in linked_ranges.iter() {
 2757            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2758            let end_offset = start_offset + end_difference;
 2759            let start_offset = start_offset + start_difference;
 2760            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2761                continue;
 2762            }
 2763            if self.selections.disjoint_anchor_ranges().any(|s| {
 2764                if s.start.buffer_id != selection.start.buffer_id
 2765                    || s.end.buffer_id != selection.end.buffer_id
 2766                {
 2767                    return false;
 2768                }
 2769                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2770                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2771            }) {
 2772                continue;
 2773            }
 2774            let start = buffer_snapshot.anchor_after(start_offset);
 2775            let end = buffer_snapshot.anchor_after(end_offset);
 2776            linked_edits
 2777                .entry(buffer.clone())
 2778                .or_default()
 2779                .push(start..end);
 2780        }
 2781        Some(linked_edits)
 2782    }
 2783
 2784    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2785        let text: Arc<str> = text.into();
 2786
 2787        if self.read_only(cx) {
 2788            return;
 2789        }
 2790
 2791        let selections = self.selections.all_adjusted(cx);
 2792        let mut bracket_inserted = false;
 2793        let mut edits = Vec::new();
 2794        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2795        let mut new_selections = Vec::with_capacity(selections.len());
 2796        let mut new_autoclose_regions = Vec::new();
 2797        let snapshot = self.buffer.read(cx).read(cx);
 2798
 2799        for (selection, autoclose_region) in
 2800            self.selections_with_autoclose_regions(selections, &snapshot)
 2801        {
 2802            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2803                // Determine if the inserted text matches the opening or closing
 2804                // bracket of any of this language's bracket pairs.
 2805                let mut bracket_pair = None;
 2806                let mut is_bracket_pair_start = false;
 2807                let mut is_bracket_pair_end = false;
 2808                if !text.is_empty() {
 2809                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2810                    //  and they are removing the character that triggered IME popup.
 2811                    for (pair, enabled) in scope.brackets() {
 2812                        if !pair.close && !pair.surround {
 2813                            continue;
 2814                        }
 2815
 2816                        if enabled && pair.start.ends_with(text.as_ref()) {
 2817                            let prefix_len = pair.start.len() - text.len();
 2818                            let preceding_text_matches_prefix = prefix_len == 0
 2819                                || (selection.start.column >= (prefix_len as u32)
 2820                                    && snapshot.contains_str_at(
 2821                                        Point::new(
 2822                                            selection.start.row,
 2823                                            selection.start.column - (prefix_len as u32),
 2824                                        ),
 2825                                        &pair.start[..prefix_len],
 2826                                    ));
 2827                            if preceding_text_matches_prefix {
 2828                                bracket_pair = Some(pair.clone());
 2829                                is_bracket_pair_start = true;
 2830                                break;
 2831                            }
 2832                        }
 2833                        if pair.end.as_str() == text.as_ref() {
 2834                            bracket_pair = Some(pair.clone());
 2835                            is_bracket_pair_end = true;
 2836                            break;
 2837                        }
 2838                    }
 2839                }
 2840
 2841                if let Some(bracket_pair) = bracket_pair {
 2842                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2843                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2844                    let auto_surround =
 2845                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2846                    if selection.is_empty() {
 2847                        if is_bracket_pair_start {
 2848                            // If the inserted text is a suffix of an opening bracket and the
 2849                            // selection is preceded by the rest of the opening bracket, then
 2850                            // insert the closing bracket.
 2851                            let following_text_allows_autoclose = snapshot
 2852                                .chars_at(selection.start)
 2853                                .next()
 2854                                .map_or(true, |c| scope.should_autoclose_before(c));
 2855
 2856                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2857                                && bracket_pair.start.len() == 1
 2858                            {
 2859                                let target = bracket_pair.start.chars().next().unwrap();
 2860                                let current_line_count = snapshot
 2861                                    .reversed_chars_at(selection.start)
 2862                                    .take_while(|&c| c != '\n')
 2863                                    .filter(|&c| c == target)
 2864                                    .count();
 2865                                current_line_count % 2 == 1
 2866                            } else {
 2867                                false
 2868                            };
 2869
 2870                            if autoclose
 2871                                && bracket_pair.close
 2872                                && following_text_allows_autoclose
 2873                                && !is_closing_quote
 2874                            {
 2875                                let anchor = snapshot.anchor_before(selection.end);
 2876                                new_selections.push((selection.map(|_| anchor), text.len()));
 2877                                new_autoclose_regions.push((
 2878                                    anchor,
 2879                                    text.len(),
 2880                                    selection.id,
 2881                                    bracket_pair.clone(),
 2882                                ));
 2883                                edits.push((
 2884                                    selection.range(),
 2885                                    format!("{}{}", text, bracket_pair.end).into(),
 2886                                ));
 2887                                bracket_inserted = true;
 2888                                continue;
 2889                            }
 2890                        }
 2891
 2892                        if let Some(region) = autoclose_region {
 2893                            // If the selection is followed by an auto-inserted closing bracket,
 2894                            // then don't insert that closing bracket again; just move the selection
 2895                            // past the closing bracket.
 2896                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2897                                && text.as_ref() == region.pair.end.as_str();
 2898                            if should_skip {
 2899                                let anchor = snapshot.anchor_after(selection.end);
 2900                                new_selections
 2901                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2902                                continue;
 2903                            }
 2904                        }
 2905
 2906                        let always_treat_brackets_as_autoclosed = snapshot
 2907                            .settings_at(selection.start, cx)
 2908                            .always_treat_brackets_as_autoclosed;
 2909                        if always_treat_brackets_as_autoclosed
 2910                            && is_bracket_pair_end
 2911                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2912                        {
 2913                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2914                            // and the inserted text is a closing bracket and the selection is followed
 2915                            // by the closing bracket then move the selection past the closing bracket.
 2916                            let anchor = snapshot.anchor_after(selection.end);
 2917                            new_selections.push((selection.map(|_| anchor), text.len()));
 2918                            continue;
 2919                        }
 2920                    }
 2921                    // If an opening bracket is 1 character long and is typed while
 2922                    // text is selected, then surround that text with the bracket pair.
 2923                    else if auto_surround
 2924                        && bracket_pair.surround
 2925                        && is_bracket_pair_start
 2926                        && bracket_pair.start.chars().count() == 1
 2927                    {
 2928                        edits.push((selection.start..selection.start, text.clone()));
 2929                        edits.push((
 2930                            selection.end..selection.end,
 2931                            bracket_pair.end.as_str().into(),
 2932                        ));
 2933                        bracket_inserted = true;
 2934                        new_selections.push((
 2935                            Selection {
 2936                                id: selection.id,
 2937                                start: snapshot.anchor_after(selection.start),
 2938                                end: snapshot.anchor_before(selection.end),
 2939                                reversed: selection.reversed,
 2940                                goal: selection.goal,
 2941                            },
 2942                            0,
 2943                        ));
 2944                        continue;
 2945                    }
 2946                }
 2947            }
 2948
 2949            if self.auto_replace_emoji_shortcode
 2950                && selection.is_empty()
 2951                && text.as_ref().ends_with(':')
 2952            {
 2953                if let Some(possible_emoji_short_code) =
 2954                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2955                {
 2956                    if !possible_emoji_short_code.is_empty() {
 2957                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2958                            let emoji_shortcode_start = Point::new(
 2959                                selection.start.row,
 2960                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2961                            );
 2962
 2963                            // Remove shortcode from buffer
 2964                            edits.push((
 2965                                emoji_shortcode_start..selection.start,
 2966                                "".to_string().into(),
 2967                            ));
 2968                            new_selections.push((
 2969                                Selection {
 2970                                    id: selection.id,
 2971                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2972                                    end: snapshot.anchor_before(selection.start),
 2973                                    reversed: selection.reversed,
 2974                                    goal: selection.goal,
 2975                                },
 2976                                0,
 2977                            ));
 2978
 2979                            // Insert emoji
 2980                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2981                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2982                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2983
 2984                            continue;
 2985                        }
 2986                    }
 2987                }
 2988            }
 2989
 2990            // If not handling any auto-close operation, then just replace the selected
 2991            // text with the given input and move the selection to the end of the
 2992            // newly inserted text.
 2993            let anchor = snapshot.anchor_after(selection.end);
 2994            if !self.linked_edit_ranges.is_empty() {
 2995                let start_anchor = snapshot.anchor_before(selection.start);
 2996
 2997                let is_word_char = text.chars().next().map_or(true, |char| {
 2998                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2999                    classifier.is_word(char)
 3000                });
 3001
 3002                if is_word_char {
 3003                    if let Some(ranges) = self
 3004                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3005                    {
 3006                        for (buffer, edits) in ranges {
 3007                            linked_edits
 3008                                .entry(buffer.clone())
 3009                                .or_default()
 3010                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3011                        }
 3012                    }
 3013                }
 3014            }
 3015
 3016            new_selections.push((selection.map(|_| anchor), 0));
 3017            edits.push((selection.start..selection.end, text.clone()));
 3018        }
 3019
 3020        drop(snapshot);
 3021
 3022        self.transact(window, cx, |this, window, cx| {
 3023            this.buffer.update(cx, |buffer, cx| {
 3024                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3025            });
 3026            for (buffer, edits) in linked_edits {
 3027                buffer.update(cx, |buffer, cx| {
 3028                    let snapshot = buffer.snapshot();
 3029                    let edits = edits
 3030                        .into_iter()
 3031                        .map(|(range, text)| {
 3032                            use text::ToPoint as TP;
 3033                            let end_point = TP::to_point(&range.end, &snapshot);
 3034                            let start_point = TP::to_point(&range.start, &snapshot);
 3035                            (start_point..end_point, text)
 3036                        })
 3037                        .sorted_by_key(|(range, _)| range.start)
 3038                        .collect::<Vec<_>>();
 3039                    buffer.edit(edits, None, cx);
 3040                })
 3041            }
 3042            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3043            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3044            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3045            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3046                .zip(new_selection_deltas)
 3047                .map(|(selection, delta)| Selection {
 3048                    id: selection.id,
 3049                    start: selection.start + delta,
 3050                    end: selection.end + delta,
 3051                    reversed: selection.reversed,
 3052                    goal: SelectionGoal::None,
 3053                })
 3054                .collect::<Vec<_>>();
 3055
 3056            let mut i = 0;
 3057            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3058                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3059                let start = map.buffer_snapshot.anchor_before(position);
 3060                let end = map.buffer_snapshot.anchor_after(position);
 3061                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3062                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3063                        Ordering::Less => i += 1,
 3064                        Ordering::Greater => break,
 3065                        Ordering::Equal => {
 3066                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3067                                Ordering::Less => i += 1,
 3068                                Ordering::Equal => break,
 3069                                Ordering::Greater => break,
 3070                            }
 3071                        }
 3072                    }
 3073                }
 3074                this.autoclose_regions.insert(
 3075                    i,
 3076                    AutocloseRegion {
 3077                        selection_id,
 3078                        range: start..end,
 3079                        pair,
 3080                    },
 3081                );
 3082            }
 3083
 3084            let had_active_inline_completion = this.has_active_inline_completion();
 3085            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3086                s.select(new_selections)
 3087            });
 3088
 3089            if !bracket_inserted {
 3090                if let Some(on_type_format_task) =
 3091                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3092                {
 3093                    on_type_format_task.detach_and_log_err(cx);
 3094                }
 3095            }
 3096
 3097            let editor_settings = EditorSettings::get_global(cx);
 3098            if bracket_inserted
 3099                && (editor_settings.auto_signature_help
 3100                    || editor_settings.show_signature_help_after_edits)
 3101            {
 3102                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3103            }
 3104
 3105            let trigger_in_words =
 3106                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3107            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3108            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3109            this.refresh_inline_completion(true, false, window, cx);
 3110        });
 3111    }
 3112
 3113    fn find_possible_emoji_shortcode_at_position(
 3114        snapshot: &MultiBufferSnapshot,
 3115        position: Point,
 3116    ) -> Option<String> {
 3117        let mut chars = Vec::new();
 3118        let mut found_colon = false;
 3119        for char in snapshot.reversed_chars_at(position).take(100) {
 3120            // Found a possible emoji shortcode in the middle of the buffer
 3121            if found_colon {
 3122                if char.is_whitespace() {
 3123                    chars.reverse();
 3124                    return Some(chars.iter().collect());
 3125                }
 3126                // If the previous character is not a whitespace, we are in the middle of a word
 3127                // and we only want to complete the shortcode if the word is made up of other emojis
 3128                let mut containing_word = String::new();
 3129                for ch in snapshot
 3130                    .reversed_chars_at(position)
 3131                    .skip(chars.len() + 1)
 3132                    .take(100)
 3133                {
 3134                    if ch.is_whitespace() {
 3135                        break;
 3136                    }
 3137                    containing_word.push(ch);
 3138                }
 3139                let containing_word = containing_word.chars().rev().collect::<String>();
 3140                if util::word_consists_of_emojis(containing_word.as_str()) {
 3141                    chars.reverse();
 3142                    return Some(chars.iter().collect());
 3143                }
 3144            }
 3145
 3146            if char.is_whitespace() || !char.is_ascii() {
 3147                return None;
 3148            }
 3149            if char == ':' {
 3150                found_colon = true;
 3151            } else {
 3152                chars.push(char);
 3153            }
 3154        }
 3155        // Found a possible emoji shortcode at the beginning of the buffer
 3156        chars.reverse();
 3157        Some(chars.iter().collect())
 3158    }
 3159
 3160    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3161        self.transact(window, cx, |this, window, cx| {
 3162            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3163                let selections = this.selections.all::<usize>(cx);
 3164                let multi_buffer = this.buffer.read(cx);
 3165                let buffer = multi_buffer.snapshot(cx);
 3166                selections
 3167                    .iter()
 3168                    .map(|selection| {
 3169                        let start_point = selection.start.to_point(&buffer);
 3170                        let mut indent =
 3171                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3172                        indent.len = cmp::min(indent.len, start_point.column);
 3173                        let start = selection.start;
 3174                        let end = selection.end;
 3175                        let selection_is_empty = start == end;
 3176                        let language_scope = buffer.language_scope_at(start);
 3177                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3178                            &language_scope
 3179                        {
 3180                            let insert_extra_newline =
 3181                                insert_extra_newline_brackets(&buffer, start..end, language)
 3182                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3183
 3184                            // Comment extension on newline is allowed only for cursor selections
 3185                            let comment_delimiter = maybe!({
 3186                                if !selection_is_empty {
 3187                                    return None;
 3188                                }
 3189
 3190                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3191                                    return None;
 3192                                }
 3193
 3194                                let delimiters = language.line_comment_prefixes();
 3195                                let max_len_of_delimiter =
 3196                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3197                                let (snapshot, range) =
 3198                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3199
 3200                                let mut index_of_first_non_whitespace = 0;
 3201                                let comment_candidate = snapshot
 3202                                    .chars_for_range(range)
 3203                                    .skip_while(|c| {
 3204                                        let should_skip = c.is_whitespace();
 3205                                        if should_skip {
 3206                                            index_of_first_non_whitespace += 1;
 3207                                        }
 3208                                        should_skip
 3209                                    })
 3210                                    .take(max_len_of_delimiter)
 3211                                    .collect::<String>();
 3212                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3213                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3214                                })?;
 3215                                let cursor_is_placed_after_comment_marker =
 3216                                    index_of_first_non_whitespace + comment_prefix.len()
 3217                                        <= start_point.column as usize;
 3218                                if cursor_is_placed_after_comment_marker {
 3219                                    Some(comment_prefix.clone())
 3220                                } else {
 3221                                    None
 3222                                }
 3223                            });
 3224                            (comment_delimiter, insert_extra_newline)
 3225                        } else {
 3226                            (None, false)
 3227                        };
 3228
 3229                        let capacity_for_delimiter = comment_delimiter
 3230                            .as_deref()
 3231                            .map(str::len)
 3232                            .unwrap_or_default();
 3233                        let mut new_text =
 3234                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3235                        new_text.push('\n');
 3236                        new_text.extend(indent.chars());
 3237                        if let Some(delimiter) = &comment_delimiter {
 3238                            new_text.push_str(delimiter);
 3239                        }
 3240                        if insert_extra_newline {
 3241                            new_text = new_text.repeat(2);
 3242                        }
 3243
 3244                        let anchor = buffer.anchor_after(end);
 3245                        let new_selection = selection.map(|_| anchor);
 3246                        (
 3247                            (start..end, new_text),
 3248                            (insert_extra_newline, new_selection),
 3249                        )
 3250                    })
 3251                    .unzip()
 3252            };
 3253
 3254            this.edit_with_autoindent(edits, cx);
 3255            let buffer = this.buffer.read(cx).snapshot(cx);
 3256            let new_selections = selection_fixup_info
 3257                .into_iter()
 3258                .map(|(extra_newline_inserted, new_selection)| {
 3259                    let mut cursor = new_selection.end.to_point(&buffer);
 3260                    if extra_newline_inserted {
 3261                        cursor.row -= 1;
 3262                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3263                    }
 3264                    new_selection.map(|_| cursor)
 3265                })
 3266                .collect();
 3267
 3268            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3269                s.select(new_selections)
 3270            });
 3271            this.refresh_inline_completion(true, false, window, cx);
 3272        });
 3273    }
 3274
 3275    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3276        let buffer = self.buffer.read(cx);
 3277        let snapshot = buffer.snapshot(cx);
 3278
 3279        let mut edits = Vec::new();
 3280        let mut rows = Vec::new();
 3281
 3282        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3283            let cursor = selection.head();
 3284            let row = cursor.row;
 3285
 3286            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3287
 3288            let newline = "\n".to_string();
 3289            edits.push((start_of_line..start_of_line, newline));
 3290
 3291            rows.push(row + rows_inserted as u32);
 3292        }
 3293
 3294        self.transact(window, cx, |editor, window, cx| {
 3295            editor.edit(edits, cx);
 3296
 3297            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3298                let mut index = 0;
 3299                s.move_cursors_with(|map, _, _| {
 3300                    let row = rows[index];
 3301                    index += 1;
 3302
 3303                    let point = Point::new(row, 0);
 3304                    let boundary = map.next_line_boundary(point).1;
 3305                    let clipped = map.clip_point(boundary, Bias::Left);
 3306
 3307                    (clipped, SelectionGoal::None)
 3308                });
 3309            });
 3310
 3311            let mut indent_edits = Vec::new();
 3312            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3313            for row in rows {
 3314                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3315                for (row, indent) in indents {
 3316                    if indent.len == 0 {
 3317                        continue;
 3318                    }
 3319
 3320                    let text = match indent.kind {
 3321                        IndentKind::Space => " ".repeat(indent.len as usize),
 3322                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3323                    };
 3324                    let point = Point::new(row.0, 0);
 3325                    indent_edits.push((point..point, text));
 3326                }
 3327            }
 3328            editor.edit(indent_edits, cx);
 3329        });
 3330    }
 3331
 3332    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3333        let buffer = self.buffer.read(cx);
 3334        let snapshot = buffer.snapshot(cx);
 3335
 3336        let mut edits = Vec::new();
 3337        let mut rows = Vec::new();
 3338        let mut rows_inserted = 0;
 3339
 3340        for selection in self.selections.all_adjusted(cx) {
 3341            let cursor = selection.head();
 3342            let row = cursor.row;
 3343
 3344            let point = Point::new(row + 1, 0);
 3345            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3346
 3347            let newline = "\n".to_string();
 3348            edits.push((start_of_line..start_of_line, newline));
 3349
 3350            rows_inserted += 1;
 3351            rows.push(row + rows_inserted);
 3352        }
 3353
 3354        self.transact(window, cx, |editor, window, cx| {
 3355            editor.edit(edits, cx);
 3356
 3357            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3358                let mut index = 0;
 3359                s.move_cursors_with(|map, _, _| {
 3360                    let row = rows[index];
 3361                    index += 1;
 3362
 3363                    let point = Point::new(row, 0);
 3364                    let boundary = map.next_line_boundary(point).1;
 3365                    let clipped = map.clip_point(boundary, Bias::Left);
 3366
 3367                    (clipped, SelectionGoal::None)
 3368                });
 3369            });
 3370
 3371            let mut indent_edits = Vec::new();
 3372            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3373            for row in rows {
 3374                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3375                for (row, indent) in indents {
 3376                    if indent.len == 0 {
 3377                        continue;
 3378                    }
 3379
 3380                    let text = match indent.kind {
 3381                        IndentKind::Space => " ".repeat(indent.len as usize),
 3382                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3383                    };
 3384                    let point = Point::new(row.0, 0);
 3385                    indent_edits.push((point..point, text));
 3386                }
 3387            }
 3388            editor.edit(indent_edits, cx);
 3389        });
 3390    }
 3391
 3392    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3393        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3394            original_start_columns: Vec::new(),
 3395        });
 3396        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3397    }
 3398
 3399    fn insert_with_autoindent_mode(
 3400        &mut self,
 3401        text: &str,
 3402        autoindent_mode: Option<AutoindentMode>,
 3403        window: &mut Window,
 3404        cx: &mut Context<Self>,
 3405    ) {
 3406        if self.read_only(cx) {
 3407            return;
 3408        }
 3409
 3410        let text: Arc<str> = text.into();
 3411        self.transact(window, cx, |this, window, cx| {
 3412            let old_selections = this.selections.all_adjusted(cx);
 3413            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3414                let anchors = {
 3415                    let snapshot = buffer.read(cx);
 3416                    old_selections
 3417                        .iter()
 3418                        .map(|s| {
 3419                            let anchor = snapshot.anchor_after(s.head());
 3420                            s.map(|_| anchor)
 3421                        })
 3422                        .collect::<Vec<_>>()
 3423                };
 3424                buffer.edit(
 3425                    old_selections
 3426                        .iter()
 3427                        .map(|s| (s.start..s.end, text.clone())),
 3428                    autoindent_mode,
 3429                    cx,
 3430                );
 3431                anchors
 3432            });
 3433
 3434            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3435                s.select_anchors(selection_anchors);
 3436            });
 3437
 3438            cx.notify();
 3439        });
 3440    }
 3441
 3442    fn trigger_completion_on_input(
 3443        &mut self,
 3444        text: &str,
 3445        trigger_in_words: bool,
 3446        window: &mut Window,
 3447        cx: &mut Context<Self>,
 3448    ) {
 3449        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3450            self.show_completions(
 3451                &ShowCompletions {
 3452                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3453                },
 3454                window,
 3455                cx,
 3456            );
 3457        } else {
 3458            self.hide_context_menu(window, cx);
 3459        }
 3460    }
 3461
 3462    fn is_completion_trigger(
 3463        &self,
 3464        text: &str,
 3465        trigger_in_words: bool,
 3466        cx: &mut Context<Self>,
 3467    ) -> bool {
 3468        let position = self.selections.newest_anchor().head();
 3469        let multibuffer = self.buffer.read(cx);
 3470        let Some(buffer) = position
 3471            .buffer_id
 3472            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3473        else {
 3474            return false;
 3475        };
 3476
 3477        if let Some(completion_provider) = &self.completion_provider {
 3478            completion_provider.is_completion_trigger(
 3479                &buffer,
 3480                position.text_anchor,
 3481                text,
 3482                trigger_in_words,
 3483                cx,
 3484            )
 3485        } else {
 3486            false
 3487        }
 3488    }
 3489
 3490    /// If any empty selections is touching the start of its innermost containing autoclose
 3491    /// region, expand it to select the brackets.
 3492    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3493        let selections = self.selections.all::<usize>(cx);
 3494        let buffer = self.buffer.read(cx).read(cx);
 3495        let new_selections = self
 3496            .selections_with_autoclose_regions(selections, &buffer)
 3497            .map(|(mut selection, region)| {
 3498                if !selection.is_empty() {
 3499                    return selection;
 3500                }
 3501
 3502                if let Some(region) = region {
 3503                    let mut range = region.range.to_offset(&buffer);
 3504                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3505                        range.start -= region.pair.start.len();
 3506                        if buffer.contains_str_at(range.start, &region.pair.start)
 3507                            && buffer.contains_str_at(range.end, &region.pair.end)
 3508                        {
 3509                            range.end += region.pair.end.len();
 3510                            selection.start = range.start;
 3511                            selection.end = range.end;
 3512
 3513                            return selection;
 3514                        }
 3515                    }
 3516                }
 3517
 3518                let always_treat_brackets_as_autoclosed = buffer
 3519                    .settings_at(selection.start, cx)
 3520                    .always_treat_brackets_as_autoclosed;
 3521
 3522                if !always_treat_brackets_as_autoclosed {
 3523                    return selection;
 3524                }
 3525
 3526                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3527                    for (pair, enabled) in scope.brackets() {
 3528                        if !enabled || !pair.close {
 3529                            continue;
 3530                        }
 3531
 3532                        if buffer.contains_str_at(selection.start, &pair.end) {
 3533                            let pair_start_len = pair.start.len();
 3534                            if buffer.contains_str_at(
 3535                                selection.start.saturating_sub(pair_start_len),
 3536                                &pair.start,
 3537                            ) {
 3538                                selection.start -= pair_start_len;
 3539                                selection.end += pair.end.len();
 3540
 3541                                return selection;
 3542                            }
 3543                        }
 3544                    }
 3545                }
 3546
 3547                selection
 3548            })
 3549            .collect();
 3550
 3551        drop(buffer);
 3552        self.change_selections(None, window, cx, |selections| {
 3553            selections.select(new_selections)
 3554        });
 3555    }
 3556
 3557    /// Iterate the given selections, and for each one, find the smallest surrounding
 3558    /// autoclose region. This uses the ordering of the selections and the autoclose
 3559    /// regions to avoid repeated comparisons.
 3560    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3561        &'a self,
 3562        selections: impl IntoIterator<Item = Selection<D>>,
 3563        buffer: &'a MultiBufferSnapshot,
 3564    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3565        let mut i = 0;
 3566        let mut regions = self.autoclose_regions.as_slice();
 3567        selections.into_iter().map(move |selection| {
 3568            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3569
 3570            let mut enclosing = None;
 3571            while let Some(pair_state) = regions.get(i) {
 3572                if pair_state.range.end.to_offset(buffer) < range.start {
 3573                    regions = &regions[i + 1..];
 3574                    i = 0;
 3575                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3576                    break;
 3577                } else {
 3578                    if pair_state.selection_id == selection.id {
 3579                        enclosing = Some(pair_state);
 3580                    }
 3581                    i += 1;
 3582                }
 3583            }
 3584
 3585            (selection, enclosing)
 3586        })
 3587    }
 3588
 3589    /// Remove any autoclose regions that no longer contain their selection.
 3590    fn invalidate_autoclose_regions(
 3591        &mut self,
 3592        mut selections: &[Selection<Anchor>],
 3593        buffer: &MultiBufferSnapshot,
 3594    ) {
 3595        self.autoclose_regions.retain(|state| {
 3596            let mut i = 0;
 3597            while let Some(selection) = selections.get(i) {
 3598                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3599                    selections = &selections[1..];
 3600                    continue;
 3601                }
 3602                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3603                    break;
 3604                }
 3605                if selection.id == state.selection_id {
 3606                    return true;
 3607                } else {
 3608                    i += 1;
 3609                }
 3610            }
 3611            false
 3612        });
 3613    }
 3614
 3615    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3616        let offset = position.to_offset(buffer);
 3617        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3618        if offset > word_range.start && kind == Some(CharKind::Word) {
 3619            Some(
 3620                buffer
 3621                    .text_for_range(word_range.start..offset)
 3622                    .collect::<String>(),
 3623            )
 3624        } else {
 3625            None
 3626        }
 3627    }
 3628
 3629    pub fn toggle_inlay_hints(
 3630        &mut self,
 3631        _: &ToggleInlayHints,
 3632        _: &mut Window,
 3633        cx: &mut Context<Self>,
 3634    ) {
 3635        self.refresh_inlay_hints(
 3636            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3637            cx,
 3638        );
 3639    }
 3640
 3641    pub fn inlay_hints_enabled(&self) -> bool {
 3642        self.inlay_hint_cache.enabled
 3643    }
 3644
 3645    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3646        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3647            return;
 3648        }
 3649
 3650        let reason_description = reason.description();
 3651        let ignore_debounce = matches!(
 3652            reason,
 3653            InlayHintRefreshReason::SettingsChange(_)
 3654                | InlayHintRefreshReason::Toggle(_)
 3655                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3656        );
 3657        let (invalidate_cache, required_languages) = match reason {
 3658            InlayHintRefreshReason::Toggle(enabled) => {
 3659                self.inlay_hint_cache.enabled = enabled;
 3660                if enabled {
 3661                    (InvalidationStrategy::RefreshRequested, None)
 3662                } else {
 3663                    self.inlay_hint_cache.clear();
 3664                    self.splice_inlays(
 3665                        &self
 3666                            .visible_inlay_hints(cx)
 3667                            .iter()
 3668                            .map(|inlay| inlay.id)
 3669                            .collect::<Vec<InlayId>>(),
 3670                        Vec::new(),
 3671                        cx,
 3672                    );
 3673                    return;
 3674                }
 3675            }
 3676            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3677                match self.inlay_hint_cache.update_settings(
 3678                    &self.buffer,
 3679                    new_settings,
 3680                    self.visible_inlay_hints(cx),
 3681                    cx,
 3682                ) {
 3683                    ControlFlow::Break(Some(InlaySplice {
 3684                        to_remove,
 3685                        to_insert,
 3686                    })) => {
 3687                        self.splice_inlays(&to_remove, to_insert, cx);
 3688                        return;
 3689                    }
 3690                    ControlFlow::Break(None) => return,
 3691                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3692                }
 3693            }
 3694            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3695                if let Some(InlaySplice {
 3696                    to_remove,
 3697                    to_insert,
 3698                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3699                {
 3700                    self.splice_inlays(&to_remove, to_insert, cx);
 3701                }
 3702                return;
 3703            }
 3704            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3705            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3706                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3707            }
 3708            InlayHintRefreshReason::RefreshRequested => {
 3709                (InvalidationStrategy::RefreshRequested, None)
 3710            }
 3711        };
 3712
 3713        if let Some(InlaySplice {
 3714            to_remove,
 3715            to_insert,
 3716        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3717            reason_description,
 3718            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3719            invalidate_cache,
 3720            ignore_debounce,
 3721            cx,
 3722        ) {
 3723            self.splice_inlays(&to_remove, to_insert, cx);
 3724        }
 3725    }
 3726
 3727    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3728        self.display_map
 3729            .read(cx)
 3730            .current_inlays()
 3731            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3732            .cloned()
 3733            .collect()
 3734    }
 3735
 3736    pub fn excerpts_for_inlay_hints_query(
 3737        &self,
 3738        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3739        cx: &mut Context<Editor>,
 3740    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3741        let Some(project) = self.project.as_ref() else {
 3742            return HashMap::default();
 3743        };
 3744        let project = project.read(cx);
 3745        let multi_buffer = self.buffer().read(cx);
 3746        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3747        let multi_buffer_visible_start = self
 3748            .scroll_manager
 3749            .anchor()
 3750            .anchor
 3751            .to_point(&multi_buffer_snapshot);
 3752        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3753            multi_buffer_visible_start
 3754                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3755            Bias::Left,
 3756        );
 3757        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3758        multi_buffer_snapshot
 3759            .range_to_buffer_ranges(multi_buffer_visible_range)
 3760            .into_iter()
 3761            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3762            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3763                let buffer_file = project::File::from_dyn(buffer.file())?;
 3764                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3765                let worktree_entry = buffer_worktree
 3766                    .read(cx)
 3767                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3768                if worktree_entry.is_ignored {
 3769                    return None;
 3770                }
 3771
 3772                let language = buffer.language()?;
 3773                if let Some(restrict_to_languages) = restrict_to_languages {
 3774                    if !restrict_to_languages.contains(language) {
 3775                        return None;
 3776                    }
 3777                }
 3778                Some((
 3779                    excerpt_id,
 3780                    (
 3781                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3782                        buffer.version().clone(),
 3783                        excerpt_visible_range,
 3784                    ),
 3785                ))
 3786            })
 3787            .collect()
 3788    }
 3789
 3790    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3791        TextLayoutDetails {
 3792            text_system: window.text_system().clone(),
 3793            editor_style: self.style.clone().unwrap(),
 3794            rem_size: window.rem_size(),
 3795            scroll_anchor: self.scroll_manager.anchor(),
 3796            visible_rows: self.visible_line_count(),
 3797            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3798        }
 3799    }
 3800
 3801    pub fn splice_inlays(
 3802        &self,
 3803        to_remove: &[InlayId],
 3804        to_insert: Vec<Inlay>,
 3805        cx: &mut Context<Self>,
 3806    ) {
 3807        self.display_map.update(cx, |display_map, cx| {
 3808            display_map.splice_inlays(to_remove, to_insert, cx)
 3809        });
 3810        cx.notify();
 3811    }
 3812
 3813    fn trigger_on_type_formatting(
 3814        &self,
 3815        input: String,
 3816        window: &mut Window,
 3817        cx: &mut Context<Self>,
 3818    ) -> Option<Task<Result<()>>> {
 3819        if input.len() != 1 {
 3820            return None;
 3821        }
 3822
 3823        let project = self.project.as_ref()?;
 3824        let position = self.selections.newest_anchor().head();
 3825        let (buffer, buffer_position) = self
 3826            .buffer
 3827            .read(cx)
 3828            .text_anchor_for_position(position, cx)?;
 3829
 3830        let settings = language_settings::language_settings(
 3831            buffer
 3832                .read(cx)
 3833                .language_at(buffer_position)
 3834                .map(|l| l.name()),
 3835            buffer.read(cx).file(),
 3836            cx,
 3837        );
 3838        if !settings.use_on_type_format {
 3839            return None;
 3840        }
 3841
 3842        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3843        // hence we do LSP request & edit on host side only — add formats to host's history.
 3844        let push_to_lsp_host_history = true;
 3845        // If this is not the host, append its history with new edits.
 3846        let push_to_client_history = project.read(cx).is_via_collab();
 3847
 3848        let on_type_formatting = project.update(cx, |project, cx| {
 3849            project.on_type_format(
 3850                buffer.clone(),
 3851                buffer_position,
 3852                input,
 3853                push_to_lsp_host_history,
 3854                cx,
 3855            )
 3856        });
 3857        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3858            if let Some(transaction) = on_type_formatting.await? {
 3859                if push_to_client_history {
 3860                    buffer
 3861                        .update(&mut cx, |buffer, _| {
 3862                            buffer.push_transaction(transaction, Instant::now());
 3863                        })
 3864                        .ok();
 3865                }
 3866                editor.update(&mut cx, |editor, cx| {
 3867                    editor.refresh_document_highlights(cx);
 3868                })?;
 3869            }
 3870            Ok(())
 3871        }))
 3872    }
 3873
 3874    pub fn show_completions(
 3875        &mut self,
 3876        options: &ShowCompletions,
 3877        window: &mut Window,
 3878        cx: &mut Context<Self>,
 3879    ) {
 3880        if self.pending_rename.is_some() {
 3881            return;
 3882        }
 3883
 3884        let Some(provider) = self.completion_provider.as_ref() else {
 3885            return;
 3886        };
 3887
 3888        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3889            return;
 3890        }
 3891
 3892        let position = self.selections.newest_anchor().head();
 3893        if position.diff_base_anchor.is_some() {
 3894            return;
 3895        }
 3896        let (buffer, buffer_position) =
 3897            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3898                output
 3899            } else {
 3900                return;
 3901            };
 3902        let show_completion_documentation = buffer
 3903            .read(cx)
 3904            .snapshot()
 3905            .settings_at(buffer_position, cx)
 3906            .show_completion_documentation;
 3907
 3908        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3909
 3910        let trigger_kind = match &options.trigger {
 3911            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3912                CompletionTriggerKind::TRIGGER_CHARACTER
 3913            }
 3914            _ => CompletionTriggerKind::INVOKED,
 3915        };
 3916        let completion_context = CompletionContext {
 3917            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3918                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3919                    Some(String::from(trigger))
 3920                } else {
 3921                    None
 3922                }
 3923            }),
 3924            trigger_kind,
 3925        };
 3926        let completions =
 3927            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3928        let sort_completions = provider.sort_completions();
 3929
 3930        let id = post_inc(&mut self.next_completion_id);
 3931        let task = cx.spawn_in(window, |editor, mut cx| {
 3932            async move {
 3933                editor.update(&mut cx, |this, _| {
 3934                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3935                })?;
 3936                let completions = completions.await.log_err();
 3937                let menu = if let Some(completions) = completions {
 3938                    let mut menu = CompletionsMenu::new(
 3939                        id,
 3940                        sort_completions,
 3941                        show_completion_documentation,
 3942                        position,
 3943                        buffer.clone(),
 3944                        completions.into(),
 3945                    );
 3946
 3947                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3948                        .await;
 3949
 3950                    menu.visible().then_some(menu)
 3951                } else {
 3952                    None
 3953                };
 3954
 3955                editor.update_in(&mut cx, |editor, window, cx| {
 3956                    match editor.context_menu.borrow().as_ref() {
 3957                        None => {}
 3958                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3959                            if prev_menu.id > id {
 3960                                return;
 3961                            }
 3962                        }
 3963                        _ => return,
 3964                    }
 3965
 3966                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3967                        let mut menu = menu.unwrap();
 3968                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3969
 3970                        *editor.context_menu.borrow_mut() =
 3971                            Some(CodeContextMenu::Completions(menu));
 3972
 3973                        if editor.show_edit_predictions_in_menu() {
 3974                            editor.update_visible_inline_completion(window, cx);
 3975                        } else {
 3976                            editor.discard_inline_completion(false, cx);
 3977                        }
 3978
 3979                        cx.notify();
 3980                    } else if editor.completion_tasks.len() <= 1 {
 3981                        // If there are no more completion tasks and the last menu was
 3982                        // empty, we should hide it.
 3983                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3984                        // If it was already hidden and we don't show inline
 3985                        // completions in the menu, we should also show the
 3986                        // inline-completion when available.
 3987                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3988                            editor.update_visible_inline_completion(window, cx);
 3989                        }
 3990                    }
 3991                })?;
 3992
 3993                Ok::<_, anyhow::Error>(())
 3994            }
 3995            .log_err()
 3996        });
 3997
 3998        self.completion_tasks.push((id, task));
 3999    }
 4000
 4001    pub fn confirm_completion(
 4002        &mut self,
 4003        action: &ConfirmCompletion,
 4004        window: &mut Window,
 4005        cx: &mut Context<Self>,
 4006    ) -> Option<Task<Result<()>>> {
 4007        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4008    }
 4009
 4010    pub fn compose_completion(
 4011        &mut self,
 4012        action: &ComposeCompletion,
 4013        window: &mut Window,
 4014        cx: &mut Context<Self>,
 4015    ) -> Option<Task<Result<()>>> {
 4016        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4017    }
 4018
 4019    fn do_completion(
 4020        &mut self,
 4021        item_ix: Option<usize>,
 4022        intent: CompletionIntent,
 4023        window: &mut Window,
 4024        cx: &mut Context<Editor>,
 4025    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4026        use language::ToOffset as _;
 4027
 4028        let completions_menu =
 4029            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4030                menu
 4031            } else {
 4032                return None;
 4033            };
 4034
 4035        let entries = completions_menu.entries.borrow();
 4036        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4037        if self.show_edit_predictions_in_menu() {
 4038            self.discard_inline_completion(true, cx);
 4039        }
 4040        let candidate_id = mat.candidate_id;
 4041        drop(entries);
 4042
 4043        let buffer_handle = completions_menu.buffer;
 4044        let completion = completions_menu
 4045            .completions
 4046            .borrow()
 4047            .get(candidate_id)?
 4048            .clone();
 4049        cx.stop_propagation();
 4050
 4051        let snippet;
 4052        let text;
 4053
 4054        if completion.is_snippet() {
 4055            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4056            text = snippet.as_ref().unwrap().text.clone();
 4057        } else {
 4058            snippet = None;
 4059            text = completion.new_text.clone();
 4060        };
 4061        let selections = self.selections.all::<usize>(cx);
 4062        let buffer = buffer_handle.read(cx);
 4063        let old_range = completion.old_range.to_offset(buffer);
 4064        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4065
 4066        let newest_selection = self.selections.newest_anchor();
 4067        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4068            return None;
 4069        }
 4070
 4071        let lookbehind = newest_selection
 4072            .start
 4073            .text_anchor
 4074            .to_offset(buffer)
 4075            .saturating_sub(old_range.start);
 4076        let lookahead = old_range
 4077            .end
 4078            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4079        let mut common_prefix_len = old_text
 4080            .bytes()
 4081            .zip(text.bytes())
 4082            .take_while(|(a, b)| a == b)
 4083            .count();
 4084
 4085        let snapshot = self.buffer.read(cx).snapshot(cx);
 4086        let mut range_to_replace: Option<Range<isize>> = None;
 4087        let mut ranges = Vec::new();
 4088        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4089        for selection in &selections {
 4090            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4091                let start = selection.start.saturating_sub(lookbehind);
 4092                let end = selection.end + lookahead;
 4093                if selection.id == newest_selection.id {
 4094                    range_to_replace = Some(
 4095                        ((start + common_prefix_len) as isize - selection.start as isize)
 4096                            ..(end as isize - selection.start as isize),
 4097                    );
 4098                }
 4099                ranges.push(start + common_prefix_len..end);
 4100            } else {
 4101                common_prefix_len = 0;
 4102                ranges.clear();
 4103                ranges.extend(selections.iter().map(|s| {
 4104                    if s.id == newest_selection.id {
 4105                        range_to_replace = Some(
 4106                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4107                                - selection.start as isize
 4108                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4109                                    - selection.start as isize,
 4110                        );
 4111                        old_range.clone()
 4112                    } else {
 4113                        s.start..s.end
 4114                    }
 4115                }));
 4116                break;
 4117            }
 4118            if !self.linked_edit_ranges.is_empty() {
 4119                let start_anchor = snapshot.anchor_before(selection.head());
 4120                let end_anchor = snapshot.anchor_after(selection.tail());
 4121                if let Some(ranges) = self
 4122                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4123                {
 4124                    for (buffer, edits) in ranges {
 4125                        linked_edits.entry(buffer.clone()).or_default().extend(
 4126                            edits
 4127                                .into_iter()
 4128                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4129                        );
 4130                    }
 4131                }
 4132            }
 4133        }
 4134        let text = &text[common_prefix_len..];
 4135
 4136        cx.emit(EditorEvent::InputHandled {
 4137            utf16_range_to_replace: range_to_replace,
 4138            text: text.into(),
 4139        });
 4140
 4141        self.transact(window, cx, |this, window, cx| {
 4142            if let Some(mut snippet) = snippet {
 4143                snippet.text = text.to_string();
 4144                for tabstop in snippet
 4145                    .tabstops
 4146                    .iter_mut()
 4147                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4148                {
 4149                    tabstop.start -= common_prefix_len as isize;
 4150                    tabstop.end -= common_prefix_len as isize;
 4151                }
 4152
 4153                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4154            } else {
 4155                this.buffer.update(cx, |buffer, cx| {
 4156                    buffer.edit(
 4157                        ranges.iter().map(|range| (range.clone(), text)),
 4158                        this.autoindent_mode.clone(),
 4159                        cx,
 4160                    );
 4161                });
 4162            }
 4163            for (buffer, edits) in linked_edits {
 4164                buffer.update(cx, |buffer, cx| {
 4165                    let snapshot = buffer.snapshot();
 4166                    let edits = edits
 4167                        .into_iter()
 4168                        .map(|(range, text)| {
 4169                            use text::ToPoint as TP;
 4170                            let end_point = TP::to_point(&range.end, &snapshot);
 4171                            let start_point = TP::to_point(&range.start, &snapshot);
 4172                            (start_point..end_point, text)
 4173                        })
 4174                        .sorted_by_key(|(range, _)| range.start)
 4175                        .collect::<Vec<_>>();
 4176                    buffer.edit(edits, None, cx);
 4177                })
 4178            }
 4179
 4180            this.refresh_inline_completion(true, false, window, cx);
 4181        });
 4182
 4183        let show_new_completions_on_confirm = completion
 4184            .confirm
 4185            .as_ref()
 4186            .map_or(false, |confirm| confirm(intent, window, cx));
 4187        if show_new_completions_on_confirm {
 4188            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4189        }
 4190
 4191        let provider = self.completion_provider.as_ref()?;
 4192        drop(completion);
 4193        let apply_edits = provider.apply_additional_edits_for_completion(
 4194            buffer_handle,
 4195            completions_menu.completions.clone(),
 4196            candidate_id,
 4197            true,
 4198            cx,
 4199        );
 4200
 4201        let editor_settings = EditorSettings::get_global(cx);
 4202        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4203            // After the code completion is finished, users often want to know what signatures are needed.
 4204            // so we should automatically call signature_help
 4205            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4206        }
 4207
 4208        Some(cx.foreground_executor().spawn(async move {
 4209            apply_edits.await?;
 4210            Ok(())
 4211        }))
 4212    }
 4213
 4214    pub fn toggle_code_actions(
 4215        &mut self,
 4216        action: &ToggleCodeActions,
 4217        window: &mut Window,
 4218        cx: &mut Context<Self>,
 4219    ) {
 4220        let mut context_menu = self.context_menu.borrow_mut();
 4221        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4222            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4223                // Toggle if we're selecting the same one
 4224                *context_menu = None;
 4225                cx.notify();
 4226                return;
 4227            } else {
 4228                // Otherwise, clear it and start a new one
 4229                *context_menu = None;
 4230                cx.notify();
 4231            }
 4232        }
 4233        drop(context_menu);
 4234        let snapshot = self.snapshot(window, cx);
 4235        let deployed_from_indicator = action.deployed_from_indicator;
 4236        let mut task = self.code_actions_task.take();
 4237        let action = action.clone();
 4238        cx.spawn_in(window, |editor, mut cx| async move {
 4239            while let Some(prev_task) = task {
 4240                prev_task.await.log_err();
 4241                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4242            }
 4243
 4244            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4245                if editor.focus_handle.is_focused(window) {
 4246                    let multibuffer_point = action
 4247                        .deployed_from_indicator
 4248                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4249                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4250                    let (buffer, buffer_row) = snapshot
 4251                        .buffer_snapshot
 4252                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4253                        .and_then(|(buffer_snapshot, range)| {
 4254                            editor
 4255                                .buffer
 4256                                .read(cx)
 4257                                .buffer(buffer_snapshot.remote_id())
 4258                                .map(|buffer| (buffer, range.start.row))
 4259                        })?;
 4260                    let (_, code_actions) = editor
 4261                        .available_code_actions
 4262                        .clone()
 4263                        .and_then(|(location, code_actions)| {
 4264                            let snapshot = location.buffer.read(cx).snapshot();
 4265                            let point_range = location.range.to_point(&snapshot);
 4266                            let point_range = point_range.start.row..=point_range.end.row;
 4267                            if point_range.contains(&buffer_row) {
 4268                                Some((location, code_actions))
 4269                            } else {
 4270                                None
 4271                            }
 4272                        })
 4273                        .unzip();
 4274                    let buffer_id = buffer.read(cx).remote_id();
 4275                    let tasks = editor
 4276                        .tasks
 4277                        .get(&(buffer_id, buffer_row))
 4278                        .map(|t| Arc::new(t.to_owned()));
 4279                    if tasks.is_none() && code_actions.is_none() {
 4280                        return None;
 4281                    }
 4282
 4283                    editor.completion_tasks.clear();
 4284                    editor.discard_inline_completion(false, cx);
 4285                    let task_context =
 4286                        tasks
 4287                            .as_ref()
 4288                            .zip(editor.project.clone())
 4289                            .map(|(tasks, project)| {
 4290                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4291                            });
 4292
 4293                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4294                        let task_context = match task_context {
 4295                            Some(task_context) => task_context.await,
 4296                            None => None,
 4297                        };
 4298                        let resolved_tasks =
 4299                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4300                                Rc::new(ResolvedTasks {
 4301                                    templates: tasks.resolve(&task_context).collect(),
 4302                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4303                                        multibuffer_point.row,
 4304                                        tasks.column,
 4305                                    )),
 4306                                })
 4307                            });
 4308                        let spawn_straight_away = resolved_tasks
 4309                            .as_ref()
 4310                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4311                            && code_actions
 4312                                .as_ref()
 4313                                .map_or(true, |actions| actions.is_empty());
 4314                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4315                            *editor.context_menu.borrow_mut() =
 4316                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4317                                    buffer,
 4318                                    actions: CodeActionContents {
 4319                                        tasks: resolved_tasks,
 4320                                        actions: code_actions,
 4321                                    },
 4322                                    selected_item: Default::default(),
 4323                                    scroll_handle: UniformListScrollHandle::default(),
 4324                                    deployed_from_indicator,
 4325                                }));
 4326                            if spawn_straight_away {
 4327                                if let Some(task) = editor.confirm_code_action(
 4328                                    &ConfirmCodeAction { item_ix: Some(0) },
 4329                                    window,
 4330                                    cx,
 4331                                ) {
 4332                                    cx.notify();
 4333                                    return task;
 4334                                }
 4335                            }
 4336                            cx.notify();
 4337                            Task::ready(Ok(()))
 4338                        }) {
 4339                            task.await
 4340                        } else {
 4341                            Ok(())
 4342                        }
 4343                    }))
 4344                } else {
 4345                    Some(Task::ready(Ok(())))
 4346                }
 4347            })?;
 4348            if let Some(task) = spawned_test_task {
 4349                task.await?;
 4350            }
 4351
 4352            Ok::<_, anyhow::Error>(())
 4353        })
 4354        .detach_and_log_err(cx);
 4355    }
 4356
 4357    pub fn confirm_code_action(
 4358        &mut self,
 4359        action: &ConfirmCodeAction,
 4360        window: &mut Window,
 4361        cx: &mut Context<Self>,
 4362    ) -> Option<Task<Result<()>>> {
 4363        let actions_menu =
 4364            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4365                menu
 4366            } else {
 4367                return None;
 4368            };
 4369        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4370        let action = actions_menu.actions.get(action_ix)?;
 4371        let title = action.label();
 4372        let buffer = actions_menu.buffer;
 4373        let workspace = self.workspace()?;
 4374
 4375        match action {
 4376            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4377                workspace.update(cx, |workspace, cx| {
 4378                    workspace::tasks::schedule_resolved_task(
 4379                        workspace,
 4380                        task_source_kind,
 4381                        resolved_task,
 4382                        false,
 4383                        cx,
 4384                    );
 4385
 4386                    Some(Task::ready(Ok(())))
 4387                })
 4388            }
 4389            CodeActionsItem::CodeAction {
 4390                excerpt_id,
 4391                action,
 4392                provider,
 4393            } => {
 4394                let apply_code_action =
 4395                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4396                let workspace = workspace.downgrade();
 4397                Some(cx.spawn_in(window, |editor, cx| async move {
 4398                    let project_transaction = apply_code_action.await?;
 4399                    Self::open_project_transaction(
 4400                        &editor,
 4401                        workspace,
 4402                        project_transaction,
 4403                        title,
 4404                        cx,
 4405                    )
 4406                    .await
 4407                }))
 4408            }
 4409        }
 4410    }
 4411
 4412    pub async fn open_project_transaction(
 4413        this: &WeakEntity<Editor>,
 4414        workspace: WeakEntity<Workspace>,
 4415        transaction: ProjectTransaction,
 4416        title: String,
 4417        mut cx: AsyncWindowContext,
 4418    ) -> Result<()> {
 4419        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4420        cx.update(|_, cx| {
 4421            entries.sort_unstable_by_key(|(buffer, _)| {
 4422                buffer.read(cx).file().map(|f| f.path().clone())
 4423            });
 4424        })?;
 4425
 4426        // If the project transaction's edits are all contained within this editor, then
 4427        // avoid opening a new editor to display them.
 4428
 4429        if let Some((buffer, transaction)) = entries.first() {
 4430            if entries.len() == 1 {
 4431                let excerpt = this.update(&mut cx, |editor, cx| {
 4432                    editor
 4433                        .buffer()
 4434                        .read(cx)
 4435                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4436                })?;
 4437                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4438                    if excerpted_buffer == *buffer {
 4439                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4440                            let excerpt_range = excerpt_range.to_offset(buffer);
 4441                            buffer
 4442                                .edited_ranges_for_transaction::<usize>(transaction)
 4443                                .all(|range| {
 4444                                    excerpt_range.start <= range.start
 4445                                        && excerpt_range.end >= range.end
 4446                                })
 4447                        })?;
 4448
 4449                        if all_edits_within_excerpt {
 4450                            return Ok(());
 4451                        }
 4452                    }
 4453                }
 4454            }
 4455        } else {
 4456            return Ok(());
 4457        }
 4458
 4459        let mut ranges_to_highlight = Vec::new();
 4460        let excerpt_buffer = cx.new(|cx| {
 4461            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4462            for (buffer_handle, transaction) in &entries {
 4463                let buffer = buffer_handle.read(cx);
 4464                ranges_to_highlight.extend(
 4465                    multibuffer.push_excerpts_with_context_lines(
 4466                        buffer_handle.clone(),
 4467                        buffer
 4468                            .edited_ranges_for_transaction::<usize>(transaction)
 4469                            .collect(),
 4470                        DEFAULT_MULTIBUFFER_CONTEXT,
 4471                        cx,
 4472                    ),
 4473                );
 4474            }
 4475            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4476            multibuffer
 4477        })?;
 4478
 4479        workspace.update_in(&mut cx, |workspace, window, cx| {
 4480            let project = workspace.project().clone();
 4481            let editor = cx
 4482                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4483            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4484            editor.update(cx, |editor, cx| {
 4485                editor.highlight_background::<Self>(
 4486                    &ranges_to_highlight,
 4487                    |theme| theme.editor_highlighted_line_background,
 4488                    cx,
 4489                );
 4490            });
 4491        })?;
 4492
 4493        Ok(())
 4494    }
 4495
 4496    pub fn clear_code_action_providers(&mut self) {
 4497        self.code_action_providers.clear();
 4498        self.available_code_actions.take();
 4499    }
 4500
 4501    pub fn add_code_action_provider(
 4502        &mut self,
 4503        provider: Rc<dyn CodeActionProvider>,
 4504        window: &mut Window,
 4505        cx: &mut Context<Self>,
 4506    ) {
 4507        if self
 4508            .code_action_providers
 4509            .iter()
 4510            .any(|existing_provider| existing_provider.id() == provider.id())
 4511        {
 4512            return;
 4513        }
 4514
 4515        self.code_action_providers.push(provider);
 4516        self.refresh_code_actions(window, cx);
 4517    }
 4518
 4519    pub fn remove_code_action_provider(
 4520        &mut self,
 4521        id: Arc<str>,
 4522        window: &mut Window,
 4523        cx: &mut Context<Self>,
 4524    ) {
 4525        self.code_action_providers
 4526            .retain(|provider| provider.id() != id);
 4527        self.refresh_code_actions(window, cx);
 4528    }
 4529
 4530    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4531        let buffer = self.buffer.read(cx);
 4532        let newest_selection = self.selections.newest_anchor().clone();
 4533        if newest_selection.head().diff_base_anchor.is_some() {
 4534            return None;
 4535        }
 4536        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4537        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4538        if start_buffer != end_buffer {
 4539            return None;
 4540        }
 4541
 4542        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4543            cx.background_executor()
 4544                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4545                .await;
 4546
 4547            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4548                let providers = this.code_action_providers.clone();
 4549                let tasks = this
 4550                    .code_action_providers
 4551                    .iter()
 4552                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4553                    .collect::<Vec<_>>();
 4554                (providers, tasks)
 4555            })?;
 4556
 4557            let mut actions = Vec::new();
 4558            for (provider, provider_actions) in
 4559                providers.into_iter().zip(future::join_all(tasks).await)
 4560            {
 4561                if let Some(provider_actions) = provider_actions.log_err() {
 4562                    actions.extend(provider_actions.into_iter().map(|action| {
 4563                        AvailableCodeAction {
 4564                            excerpt_id: newest_selection.start.excerpt_id,
 4565                            action,
 4566                            provider: provider.clone(),
 4567                        }
 4568                    }));
 4569                }
 4570            }
 4571
 4572            this.update(&mut cx, |this, cx| {
 4573                this.available_code_actions = if actions.is_empty() {
 4574                    None
 4575                } else {
 4576                    Some((
 4577                        Location {
 4578                            buffer: start_buffer,
 4579                            range: start..end,
 4580                        },
 4581                        actions.into(),
 4582                    ))
 4583                };
 4584                cx.notify();
 4585            })
 4586        }));
 4587        None
 4588    }
 4589
 4590    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4591        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4592            self.show_git_blame_inline = false;
 4593
 4594            self.show_git_blame_inline_delay_task =
 4595                Some(cx.spawn_in(window, |this, mut cx| async move {
 4596                    cx.background_executor().timer(delay).await;
 4597
 4598                    this.update(&mut cx, |this, cx| {
 4599                        this.show_git_blame_inline = true;
 4600                        cx.notify();
 4601                    })
 4602                    .log_err();
 4603                }));
 4604        }
 4605    }
 4606
 4607    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4608        if self.pending_rename.is_some() {
 4609            return None;
 4610        }
 4611
 4612        let provider = self.semantics_provider.clone()?;
 4613        let buffer = self.buffer.read(cx);
 4614        let newest_selection = self.selections.newest_anchor().clone();
 4615        let cursor_position = newest_selection.head();
 4616        let (cursor_buffer, cursor_buffer_position) =
 4617            buffer.text_anchor_for_position(cursor_position, cx)?;
 4618        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4619        if cursor_buffer != tail_buffer {
 4620            return None;
 4621        }
 4622        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4623        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4624            cx.background_executor()
 4625                .timer(Duration::from_millis(debounce))
 4626                .await;
 4627
 4628            let highlights = if let Some(highlights) = cx
 4629                .update(|cx| {
 4630                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4631                })
 4632                .ok()
 4633                .flatten()
 4634            {
 4635                highlights.await.log_err()
 4636            } else {
 4637                None
 4638            };
 4639
 4640            if let Some(highlights) = highlights {
 4641                this.update(&mut cx, |this, cx| {
 4642                    if this.pending_rename.is_some() {
 4643                        return;
 4644                    }
 4645
 4646                    let buffer_id = cursor_position.buffer_id;
 4647                    let buffer = this.buffer.read(cx);
 4648                    if !buffer
 4649                        .text_anchor_for_position(cursor_position, cx)
 4650                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4651                    {
 4652                        return;
 4653                    }
 4654
 4655                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4656                    let mut write_ranges = Vec::new();
 4657                    let mut read_ranges = Vec::new();
 4658                    for highlight in highlights {
 4659                        for (excerpt_id, excerpt_range) in
 4660                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4661                        {
 4662                            let start = highlight
 4663                                .range
 4664                                .start
 4665                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4666                            let end = highlight
 4667                                .range
 4668                                .end
 4669                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4670                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4671                                continue;
 4672                            }
 4673
 4674                            let range = Anchor {
 4675                                buffer_id,
 4676                                excerpt_id,
 4677                                text_anchor: start,
 4678                                diff_base_anchor: None,
 4679                            }..Anchor {
 4680                                buffer_id,
 4681                                excerpt_id,
 4682                                text_anchor: end,
 4683                                diff_base_anchor: None,
 4684                            };
 4685                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4686                                write_ranges.push(range);
 4687                            } else {
 4688                                read_ranges.push(range);
 4689                            }
 4690                        }
 4691                    }
 4692
 4693                    this.highlight_background::<DocumentHighlightRead>(
 4694                        &read_ranges,
 4695                        |theme| theme.editor_document_highlight_read_background,
 4696                        cx,
 4697                    );
 4698                    this.highlight_background::<DocumentHighlightWrite>(
 4699                        &write_ranges,
 4700                        |theme| theme.editor_document_highlight_write_background,
 4701                        cx,
 4702                    );
 4703                    cx.notify();
 4704                })
 4705                .log_err();
 4706            }
 4707        }));
 4708        None
 4709    }
 4710
 4711    pub fn refresh_selected_text_highlights(
 4712        &mut self,
 4713        window: &mut Window,
 4714        cx: &mut Context<Editor>,
 4715    ) {
 4716        self.selection_highlight_task.take();
 4717        if !EditorSettings::get_global(cx).selection_highlight {
 4718            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4719            return;
 4720        }
 4721        if self.selections.count() != 1 || self.selections.line_mode {
 4722            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4723            return;
 4724        }
 4725        let selection = self.selections.newest::<Point>(cx);
 4726        if selection.is_empty() || selection.start.row != selection.end.row {
 4727            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4728            return;
 4729        }
 4730        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4731        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4732            cx.background_executor()
 4733                .timer(Duration::from_millis(debounce))
 4734                .await;
 4735            let Some(Some(matches_task)) = editor
 4736                .update_in(&mut cx, |editor, _, cx| {
 4737                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4738                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4739                        return None;
 4740                    }
 4741                    let selection = editor.selections.newest::<Point>(cx);
 4742                    if selection.is_empty() || selection.start.row != selection.end.row {
 4743                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4744                        return None;
 4745                    }
 4746                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4747                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4748                    if query.trim().is_empty() {
 4749                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4750                        return None;
 4751                    }
 4752                    Some(cx.background_spawn(async move {
 4753                        let mut ranges = Vec::new();
 4754                        let selection_anchors = selection.range().to_anchors(&buffer);
 4755                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4756                            for (search_buffer, search_range, excerpt_id) in
 4757                                buffer.range_to_buffer_ranges(range)
 4758                            {
 4759                                ranges.extend(
 4760                                    project::search::SearchQuery::text(
 4761                                        query.clone(),
 4762                                        false,
 4763                                        false,
 4764                                        false,
 4765                                        Default::default(),
 4766                                        Default::default(),
 4767                                        None,
 4768                                    )
 4769                                    .unwrap()
 4770                                    .search(search_buffer, Some(search_range.clone()))
 4771                                    .await
 4772                                    .into_iter()
 4773                                    .filter_map(
 4774                                        |match_range| {
 4775                                            let start = search_buffer.anchor_after(
 4776                                                search_range.start + match_range.start,
 4777                                            );
 4778                                            let end = search_buffer.anchor_before(
 4779                                                search_range.start + match_range.end,
 4780                                            );
 4781                                            let range = Anchor::range_in_buffer(
 4782                                                excerpt_id,
 4783                                                search_buffer.remote_id(),
 4784                                                start..end,
 4785                                            );
 4786                                            (range != selection_anchors).then_some(range)
 4787                                        },
 4788                                    ),
 4789                                );
 4790                            }
 4791                        }
 4792                        ranges
 4793                    }))
 4794                })
 4795                .log_err()
 4796            else {
 4797                return;
 4798            };
 4799            let matches = matches_task.await;
 4800            editor
 4801                .update_in(&mut cx, |editor, _, cx| {
 4802                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4803                    if !matches.is_empty() {
 4804                        editor.highlight_background::<SelectedTextHighlight>(
 4805                            &matches,
 4806                            |theme| theme.editor_document_highlight_bracket_background,
 4807                            cx,
 4808                        )
 4809                    }
 4810                })
 4811                .log_err();
 4812        }));
 4813    }
 4814
 4815    pub fn refresh_inline_completion(
 4816        &mut self,
 4817        debounce: bool,
 4818        user_requested: bool,
 4819        window: &mut Window,
 4820        cx: &mut Context<Self>,
 4821    ) -> Option<()> {
 4822        let provider = self.edit_prediction_provider()?;
 4823        let cursor = self.selections.newest_anchor().head();
 4824        let (buffer, cursor_buffer_position) =
 4825            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4826
 4827        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4828            self.discard_inline_completion(false, cx);
 4829            return None;
 4830        }
 4831
 4832        if !user_requested
 4833            && (!self.should_show_edit_predictions()
 4834                || !self.is_focused(window)
 4835                || buffer.read(cx).is_empty())
 4836        {
 4837            self.discard_inline_completion(false, cx);
 4838            return None;
 4839        }
 4840
 4841        self.update_visible_inline_completion(window, cx);
 4842        provider.refresh(
 4843            self.project.clone(),
 4844            buffer,
 4845            cursor_buffer_position,
 4846            debounce,
 4847            cx,
 4848        );
 4849        Some(())
 4850    }
 4851
 4852    fn show_edit_predictions_in_menu(&self) -> bool {
 4853        match self.edit_prediction_settings {
 4854            EditPredictionSettings::Disabled => false,
 4855            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4856        }
 4857    }
 4858
 4859    pub fn edit_predictions_enabled(&self) -> bool {
 4860        match self.edit_prediction_settings {
 4861            EditPredictionSettings::Disabled => false,
 4862            EditPredictionSettings::Enabled { .. } => true,
 4863        }
 4864    }
 4865
 4866    fn edit_prediction_requires_modifier(&self) -> bool {
 4867        match self.edit_prediction_settings {
 4868            EditPredictionSettings::Disabled => false,
 4869            EditPredictionSettings::Enabled {
 4870                preview_requires_modifier,
 4871                ..
 4872            } => preview_requires_modifier,
 4873        }
 4874    }
 4875
 4876    fn edit_prediction_settings_at_position(
 4877        &self,
 4878        buffer: &Entity<Buffer>,
 4879        buffer_position: language::Anchor,
 4880        cx: &App,
 4881    ) -> EditPredictionSettings {
 4882        if self.mode != EditorMode::Full
 4883            || !self.show_inline_completions_override.unwrap_or(true)
 4884            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4885        {
 4886            return EditPredictionSettings::Disabled;
 4887        }
 4888
 4889        let buffer = buffer.read(cx);
 4890
 4891        let file = buffer.file();
 4892
 4893        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4894            return EditPredictionSettings::Disabled;
 4895        };
 4896
 4897        let by_provider = matches!(
 4898            self.menu_inline_completions_policy,
 4899            MenuInlineCompletionsPolicy::ByProvider
 4900        );
 4901
 4902        let show_in_menu = by_provider
 4903            && self
 4904                .edit_prediction_provider
 4905                .as_ref()
 4906                .map_or(false, |provider| {
 4907                    provider.provider.show_completions_in_menu()
 4908                });
 4909
 4910        let preview_requires_modifier =
 4911            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4912
 4913        EditPredictionSettings::Enabled {
 4914            show_in_menu,
 4915            preview_requires_modifier,
 4916        }
 4917    }
 4918
 4919    fn should_show_edit_predictions(&self) -> bool {
 4920        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4921    }
 4922
 4923    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4924        matches!(
 4925            self.edit_prediction_preview,
 4926            EditPredictionPreview::Active { .. }
 4927        )
 4928    }
 4929
 4930    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4931        let cursor = self.selections.newest_anchor().head();
 4932        if let Some((buffer, cursor_position)) =
 4933            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4934        {
 4935            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4936        } else {
 4937            false
 4938        }
 4939    }
 4940
 4941    fn inline_completions_enabled_in_buffer(
 4942        &self,
 4943        buffer: &Entity<Buffer>,
 4944        buffer_position: language::Anchor,
 4945        cx: &App,
 4946    ) -> bool {
 4947        maybe!({
 4948            let provider = self.edit_prediction_provider()?;
 4949            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4950                return Some(false);
 4951            }
 4952            let buffer = buffer.read(cx);
 4953            let Some(file) = buffer.file() else {
 4954                return Some(true);
 4955            };
 4956            let settings = all_language_settings(Some(file), cx);
 4957            Some(settings.inline_completions_enabled_for_path(file.path()))
 4958        })
 4959        .unwrap_or(false)
 4960    }
 4961
 4962    fn cycle_inline_completion(
 4963        &mut self,
 4964        direction: Direction,
 4965        window: &mut Window,
 4966        cx: &mut Context<Self>,
 4967    ) -> Option<()> {
 4968        let provider = self.edit_prediction_provider()?;
 4969        let cursor = self.selections.newest_anchor().head();
 4970        let (buffer, cursor_buffer_position) =
 4971            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4972        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4973            return None;
 4974        }
 4975
 4976        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4977        self.update_visible_inline_completion(window, cx);
 4978
 4979        Some(())
 4980    }
 4981
 4982    pub fn show_inline_completion(
 4983        &mut self,
 4984        _: &ShowEditPrediction,
 4985        window: &mut Window,
 4986        cx: &mut Context<Self>,
 4987    ) {
 4988        if !self.has_active_inline_completion() {
 4989            self.refresh_inline_completion(false, true, window, cx);
 4990            return;
 4991        }
 4992
 4993        self.update_visible_inline_completion(window, cx);
 4994    }
 4995
 4996    pub fn display_cursor_names(
 4997        &mut self,
 4998        _: &DisplayCursorNames,
 4999        window: &mut Window,
 5000        cx: &mut Context<Self>,
 5001    ) {
 5002        self.show_cursor_names(window, cx);
 5003    }
 5004
 5005    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5006        self.show_cursor_names = true;
 5007        cx.notify();
 5008        cx.spawn_in(window, |this, mut cx| async move {
 5009            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5010            this.update(&mut cx, |this, cx| {
 5011                this.show_cursor_names = false;
 5012                cx.notify()
 5013            })
 5014            .ok()
 5015        })
 5016        .detach();
 5017    }
 5018
 5019    pub fn next_edit_prediction(
 5020        &mut self,
 5021        _: &NextEditPrediction,
 5022        window: &mut Window,
 5023        cx: &mut Context<Self>,
 5024    ) {
 5025        if self.has_active_inline_completion() {
 5026            self.cycle_inline_completion(Direction::Next, window, cx);
 5027        } else {
 5028            let is_copilot_disabled = self
 5029                .refresh_inline_completion(false, true, window, cx)
 5030                .is_none();
 5031            if is_copilot_disabled {
 5032                cx.propagate();
 5033            }
 5034        }
 5035    }
 5036
 5037    pub fn previous_edit_prediction(
 5038        &mut self,
 5039        _: &PreviousEditPrediction,
 5040        window: &mut Window,
 5041        cx: &mut Context<Self>,
 5042    ) {
 5043        if self.has_active_inline_completion() {
 5044            self.cycle_inline_completion(Direction::Prev, window, cx);
 5045        } else {
 5046            let is_copilot_disabled = self
 5047                .refresh_inline_completion(false, true, window, cx)
 5048                .is_none();
 5049            if is_copilot_disabled {
 5050                cx.propagate();
 5051            }
 5052        }
 5053    }
 5054
 5055    pub fn accept_edit_prediction(
 5056        &mut self,
 5057        _: &AcceptEditPrediction,
 5058        window: &mut Window,
 5059        cx: &mut Context<Self>,
 5060    ) {
 5061        if self.show_edit_predictions_in_menu() {
 5062            self.hide_context_menu(window, cx);
 5063        }
 5064
 5065        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5066            return;
 5067        };
 5068
 5069        self.report_inline_completion_event(
 5070            active_inline_completion.completion_id.clone(),
 5071            true,
 5072            cx,
 5073        );
 5074
 5075        match &active_inline_completion.completion {
 5076            InlineCompletion::Move { target, .. } => {
 5077                let target = *target;
 5078
 5079                if let Some(position_map) = &self.last_position_map {
 5080                    if position_map
 5081                        .visible_row_range
 5082                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5083                        || !self.edit_prediction_requires_modifier()
 5084                    {
 5085                        self.unfold_ranges(&[target..target], true, false, cx);
 5086                        // Note that this is also done in vim's handler of the Tab action.
 5087                        self.change_selections(
 5088                            Some(Autoscroll::newest()),
 5089                            window,
 5090                            cx,
 5091                            |selections| {
 5092                                selections.select_anchor_ranges([target..target]);
 5093                            },
 5094                        );
 5095                        self.clear_row_highlights::<EditPredictionPreview>();
 5096
 5097                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5098                            previous_scroll_position: None,
 5099                        };
 5100                    } else {
 5101                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5102                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5103                        };
 5104                        self.highlight_rows::<EditPredictionPreview>(
 5105                            target..target,
 5106                            cx.theme().colors().editor_highlighted_line_background,
 5107                            true,
 5108                            cx,
 5109                        );
 5110                        self.request_autoscroll(Autoscroll::fit(), cx);
 5111                    }
 5112                }
 5113            }
 5114            InlineCompletion::Edit { edits, .. } => {
 5115                if let Some(provider) = self.edit_prediction_provider() {
 5116                    provider.accept(cx);
 5117                }
 5118
 5119                let snapshot = self.buffer.read(cx).snapshot(cx);
 5120                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5121
 5122                self.buffer.update(cx, |buffer, cx| {
 5123                    buffer.edit(edits.iter().cloned(), None, cx)
 5124                });
 5125
 5126                self.change_selections(None, window, cx, |s| {
 5127                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5128                });
 5129
 5130                self.update_visible_inline_completion(window, cx);
 5131                if self.active_inline_completion.is_none() {
 5132                    self.refresh_inline_completion(true, true, window, cx);
 5133                }
 5134
 5135                cx.notify();
 5136            }
 5137        }
 5138
 5139        self.edit_prediction_requires_modifier_in_leading_space = false;
 5140    }
 5141
 5142    pub fn accept_partial_inline_completion(
 5143        &mut self,
 5144        _: &AcceptPartialEditPrediction,
 5145        window: &mut Window,
 5146        cx: &mut Context<Self>,
 5147    ) {
 5148        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5149            return;
 5150        };
 5151        if self.selections.count() != 1 {
 5152            return;
 5153        }
 5154
 5155        self.report_inline_completion_event(
 5156            active_inline_completion.completion_id.clone(),
 5157            true,
 5158            cx,
 5159        );
 5160
 5161        match &active_inline_completion.completion {
 5162            InlineCompletion::Move { target, .. } => {
 5163                let target = *target;
 5164                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5165                    selections.select_anchor_ranges([target..target]);
 5166                });
 5167            }
 5168            InlineCompletion::Edit { edits, .. } => {
 5169                // Find an insertion that starts at the cursor position.
 5170                let snapshot = self.buffer.read(cx).snapshot(cx);
 5171                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5172                let insertion = edits.iter().find_map(|(range, text)| {
 5173                    let range = range.to_offset(&snapshot);
 5174                    if range.is_empty() && range.start == cursor_offset {
 5175                        Some(text)
 5176                    } else {
 5177                        None
 5178                    }
 5179                });
 5180
 5181                if let Some(text) = insertion {
 5182                    let mut partial_completion = text
 5183                        .chars()
 5184                        .by_ref()
 5185                        .take_while(|c| c.is_alphabetic())
 5186                        .collect::<String>();
 5187                    if partial_completion.is_empty() {
 5188                        partial_completion = text
 5189                            .chars()
 5190                            .by_ref()
 5191                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5192                            .collect::<String>();
 5193                    }
 5194
 5195                    cx.emit(EditorEvent::InputHandled {
 5196                        utf16_range_to_replace: None,
 5197                        text: partial_completion.clone().into(),
 5198                    });
 5199
 5200                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5201
 5202                    self.refresh_inline_completion(true, true, window, cx);
 5203                    cx.notify();
 5204                } else {
 5205                    self.accept_edit_prediction(&Default::default(), window, cx);
 5206                }
 5207            }
 5208        }
 5209    }
 5210
 5211    fn discard_inline_completion(
 5212        &mut self,
 5213        should_report_inline_completion_event: bool,
 5214        cx: &mut Context<Self>,
 5215    ) -> bool {
 5216        if should_report_inline_completion_event {
 5217            let completion_id = self
 5218                .active_inline_completion
 5219                .as_ref()
 5220                .and_then(|active_completion| active_completion.completion_id.clone());
 5221
 5222            self.report_inline_completion_event(completion_id, false, cx);
 5223        }
 5224
 5225        if let Some(provider) = self.edit_prediction_provider() {
 5226            provider.discard(cx);
 5227        }
 5228
 5229        self.take_active_inline_completion(cx)
 5230    }
 5231
 5232    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5233        let Some(provider) = self.edit_prediction_provider() else {
 5234            return;
 5235        };
 5236
 5237        let Some((_, buffer, _)) = self
 5238            .buffer
 5239            .read(cx)
 5240            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5241        else {
 5242            return;
 5243        };
 5244
 5245        let extension = buffer
 5246            .read(cx)
 5247            .file()
 5248            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5249
 5250        let event_type = match accepted {
 5251            true => "Edit Prediction Accepted",
 5252            false => "Edit Prediction Discarded",
 5253        };
 5254        telemetry::event!(
 5255            event_type,
 5256            provider = provider.name(),
 5257            prediction_id = id,
 5258            suggestion_accepted = accepted,
 5259            file_extension = extension,
 5260        );
 5261    }
 5262
 5263    pub fn has_active_inline_completion(&self) -> bool {
 5264        self.active_inline_completion.is_some()
 5265    }
 5266
 5267    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5268        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5269            return false;
 5270        };
 5271
 5272        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5273        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5274        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5275        true
 5276    }
 5277
 5278    /// Returns true when we're displaying the edit prediction popover below the cursor
 5279    /// like we are not previewing and the LSP autocomplete menu is visible
 5280    /// or we are in `when_holding_modifier` mode.
 5281    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5282        if self.edit_prediction_preview_is_active()
 5283            || !self.show_edit_predictions_in_menu()
 5284            || !self.edit_predictions_enabled()
 5285        {
 5286            return false;
 5287        }
 5288
 5289        if self.has_visible_completions_menu() {
 5290            return true;
 5291        }
 5292
 5293        has_completion && self.edit_prediction_requires_modifier()
 5294    }
 5295
 5296    fn handle_modifiers_changed(
 5297        &mut self,
 5298        modifiers: Modifiers,
 5299        position_map: &PositionMap,
 5300        window: &mut Window,
 5301        cx: &mut Context<Self>,
 5302    ) {
 5303        if self.show_edit_predictions_in_menu() {
 5304            self.update_edit_prediction_preview(&modifiers, window, cx);
 5305        }
 5306
 5307        self.update_selection_mode(&modifiers, position_map, window, cx);
 5308
 5309        let mouse_position = window.mouse_position();
 5310        if !position_map.text_hitbox.is_hovered(window) {
 5311            return;
 5312        }
 5313
 5314        self.update_hovered_link(
 5315            position_map.point_for_position(mouse_position),
 5316            &position_map.snapshot,
 5317            modifiers,
 5318            window,
 5319            cx,
 5320        )
 5321    }
 5322
 5323    fn update_selection_mode(
 5324        &mut self,
 5325        modifiers: &Modifiers,
 5326        position_map: &PositionMap,
 5327        window: &mut Window,
 5328        cx: &mut Context<Self>,
 5329    ) {
 5330        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5331            return;
 5332        }
 5333
 5334        let mouse_position = window.mouse_position();
 5335        let point_for_position = position_map.point_for_position(mouse_position);
 5336        let position = point_for_position.previous_valid;
 5337
 5338        self.select(
 5339            SelectPhase::BeginColumnar {
 5340                position,
 5341                reset: false,
 5342                goal_column: point_for_position.exact_unclipped.column(),
 5343            },
 5344            window,
 5345            cx,
 5346        );
 5347    }
 5348
 5349    fn update_edit_prediction_preview(
 5350        &mut self,
 5351        modifiers: &Modifiers,
 5352        window: &mut Window,
 5353        cx: &mut Context<Self>,
 5354    ) {
 5355        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5356        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5357            return;
 5358        };
 5359
 5360        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5361            if matches!(
 5362                self.edit_prediction_preview,
 5363                EditPredictionPreview::Inactive
 5364            ) {
 5365                self.edit_prediction_preview = EditPredictionPreview::Active {
 5366                    previous_scroll_position: None,
 5367                };
 5368
 5369                self.update_visible_inline_completion(window, cx);
 5370                cx.notify();
 5371            }
 5372        } else if let EditPredictionPreview::Active {
 5373            previous_scroll_position,
 5374        } = self.edit_prediction_preview
 5375        {
 5376            if let (Some(previous_scroll_position), Some(position_map)) =
 5377                (previous_scroll_position, self.last_position_map.as_ref())
 5378            {
 5379                self.set_scroll_position(
 5380                    previous_scroll_position
 5381                        .scroll_position(&position_map.snapshot.display_snapshot),
 5382                    window,
 5383                    cx,
 5384                );
 5385            }
 5386
 5387            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5388            self.clear_row_highlights::<EditPredictionPreview>();
 5389            self.update_visible_inline_completion(window, cx);
 5390            cx.notify();
 5391        }
 5392    }
 5393
 5394    fn update_visible_inline_completion(
 5395        &mut self,
 5396        _window: &mut Window,
 5397        cx: &mut Context<Self>,
 5398    ) -> Option<()> {
 5399        let selection = self.selections.newest_anchor();
 5400        let cursor = selection.head();
 5401        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5402        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5403        let excerpt_id = cursor.excerpt_id;
 5404
 5405        let show_in_menu = self.show_edit_predictions_in_menu();
 5406        let completions_menu_has_precedence = !show_in_menu
 5407            && (self.context_menu.borrow().is_some()
 5408                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5409
 5410        if completions_menu_has_precedence
 5411            || !offset_selection.is_empty()
 5412            || self
 5413                .active_inline_completion
 5414                .as_ref()
 5415                .map_or(false, |completion| {
 5416                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5417                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5418                    !invalidation_range.contains(&offset_selection.head())
 5419                })
 5420        {
 5421            self.discard_inline_completion(false, cx);
 5422            return None;
 5423        }
 5424
 5425        self.take_active_inline_completion(cx);
 5426        let Some(provider) = self.edit_prediction_provider() else {
 5427            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5428            return None;
 5429        };
 5430
 5431        let (buffer, cursor_buffer_position) =
 5432            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5433
 5434        self.edit_prediction_settings =
 5435            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5436
 5437        self.edit_prediction_cursor_on_leading_whitespace =
 5438            multibuffer.is_line_whitespace_upto(cursor);
 5439
 5440        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5441        let edits = inline_completion
 5442            .edits
 5443            .into_iter()
 5444            .flat_map(|(range, new_text)| {
 5445                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5446                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5447                Some((start..end, new_text))
 5448            })
 5449            .collect::<Vec<_>>();
 5450        if edits.is_empty() {
 5451            return None;
 5452        }
 5453
 5454        let first_edit_start = edits.first().unwrap().0.start;
 5455        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5456        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5457
 5458        let last_edit_end = edits.last().unwrap().0.end;
 5459        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5460        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5461
 5462        let cursor_row = cursor.to_point(&multibuffer).row;
 5463
 5464        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5465
 5466        let mut inlay_ids = Vec::new();
 5467        let invalidation_row_range;
 5468        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5469            Some(cursor_row..edit_end_row)
 5470        } else if cursor_row > edit_end_row {
 5471            Some(edit_start_row..cursor_row)
 5472        } else {
 5473            None
 5474        };
 5475        let is_move =
 5476            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5477        let completion = if is_move {
 5478            invalidation_row_range =
 5479                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5480            let target = first_edit_start;
 5481            InlineCompletion::Move { target, snapshot }
 5482        } else {
 5483            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5484                && !self.inline_completions_hidden_for_vim_mode;
 5485
 5486            if show_completions_in_buffer {
 5487                if edits
 5488                    .iter()
 5489                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5490                {
 5491                    let mut inlays = Vec::new();
 5492                    for (range, new_text) in &edits {
 5493                        let inlay = Inlay::inline_completion(
 5494                            post_inc(&mut self.next_inlay_id),
 5495                            range.start,
 5496                            new_text.as_str(),
 5497                        );
 5498                        inlay_ids.push(inlay.id);
 5499                        inlays.push(inlay);
 5500                    }
 5501
 5502                    self.splice_inlays(&[], inlays, cx);
 5503                } else {
 5504                    let background_color = cx.theme().status().deleted_background;
 5505                    self.highlight_text::<InlineCompletionHighlight>(
 5506                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5507                        HighlightStyle {
 5508                            background_color: Some(background_color),
 5509                            ..Default::default()
 5510                        },
 5511                        cx,
 5512                    );
 5513                }
 5514            }
 5515
 5516            invalidation_row_range = edit_start_row..edit_end_row;
 5517
 5518            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5519                if provider.show_tab_accept_marker() {
 5520                    EditDisplayMode::TabAccept
 5521                } else {
 5522                    EditDisplayMode::Inline
 5523                }
 5524            } else {
 5525                EditDisplayMode::DiffPopover
 5526            };
 5527
 5528            InlineCompletion::Edit {
 5529                edits,
 5530                edit_preview: inline_completion.edit_preview,
 5531                display_mode,
 5532                snapshot,
 5533            }
 5534        };
 5535
 5536        let invalidation_range = multibuffer
 5537            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5538            ..multibuffer.anchor_after(Point::new(
 5539                invalidation_row_range.end,
 5540                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5541            ));
 5542
 5543        self.stale_inline_completion_in_menu = None;
 5544        self.active_inline_completion = Some(InlineCompletionState {
 5545            inlay_ids,
 5546            completion,
 5547            completion_id: inline_completion.id,
 5548            invalidation_range,
 5549        });
 5550
 5551        cx.notify();
 5552
 5553        Some(())
 5554    }
 5555
 5556    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5557        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5558    }
 5559
 5560    fn render_code_actions_indicator(
 5561        &self,
 5562        _style: &EditorStyle,
 5563        row: DisplayRow,
 5564        is_active: bool,
 5565        cx: &mut Context<Self>,
 5566    ) -> Option<IconButton> {
 5567        if self.available_code_actions.is_some() {
 5568            Some(
 5569                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5570                    .shape(ui::IconButtonShape::Square)
 5571                    .icon_size(IconSize::XSmall)
 5572                    .icon_color(Color::Muted)
 5573                    .toggle_state(is_active)
 5574                    .tooltip({
 5575                        let focus_handle = self.focus_handle.clone();
 5576                        move |window, cx| {
 5577                            Tooltip::for_action_in(
 5578                                "Toggle Code Actions",
 5579                                &ToggleCodeActions {
 5580                                    deployed_from_indicator: None,
 5581                                },
 5582                                &focus_handle,
 5583                                window,
 5584                                cx,
 5585                            )
 5586                        }
 5587                    })
 5588                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5589                        window.focus(&editor.focus_handle(cx));
 5590                        editor.toggle_code_actions(
 5591                            &ToggleCodeActions {
 5592                                deployed_from_indicator: Some(row),
 5593                            },
 5594                            window,
 5595                            cx,
 5596                        );
 5597                    })),
 5598            )
 5599        } else {
 5600            None
 5601        }
 5602    }
 5603
 5604    fn clear_tasks(&mut self) {
 5605        self.tasks.clear()
 5606    }
 5607
 5608    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5609        if self.tasks.insert(key, value).is_some() {
 5610            // This case should hopefully be rare, but just in case...
 5611            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5612        }
 5613    }
 5614
 5615    fn build_tasks_context(
 5616        project: &Entity<Project>,
 5617        buffer: &Entity<Buffer>,
 5618        buffer_row: u32,
 5619        tasks: &Arc<RunnableTasks>,
 5620        cx: &mut Context<Self>,
 5621    ) -> Task<Option<task::TaskContext>> {
 5622        let position = Point::new(buffer_row, tasks.column);
 5623        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5624        let location = Location {
 5625            buffer: buffer.clone(),
 5626            range: range_start..range_start,
 5627        };
 5628        // Fill in the environmental variables from the tree-sitter captures
 5629        let mut captured_task_variables = TaskVariables::default();
 5630        for (capture_name, value) in tasks.extra_variables.clone() {
 5631            captured_task_variables.insert(
 5632                task::VariableName::Custom(capture_name.into()),
 5633                value.clone(),
 5634            );
 5635        }
 5636        project.update(cx, |project, cx| {
 5637            project.task_store().update(cx, |task_store, cx| {
 5638                task_store.task_context_for_location(captured_task_variables, location, cx)
 5639            })
 5640        })
 5641    }
 5642
 5643    pub fn spawn_nearest_task(
 5644        &mut self,
 5645        action: &SpawnNearestTask,
 5646        window: &mut Window,
 5647        cx: &mut Context<Self>,
 5648    ) {
 5649        let Some((workspace, _)) = self.workspace.clone() else {
 5650            return;
 5651        };
 5652        let Some(project) = self.project.clone() else {
 5653            return;
 5654        };
 5655
 5656        // Try to find a closest, enclosing node using tree-sitter that has a
 5657        // task
 5658        let Some((buffer, buffer_row, tasks)) = self
 5659            .find_enclosing_node_task(cx)
 5660            // Or find the task that's closest in row-distance.
 5661            .or_else(|| self.find_closest_task(cx))
 5662        else {
 5663            return;
 5664        };
 5665
 5666        let reveal_strategy = action.reveal;
 5667        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5668        cx.spawn_in(window, |_, mut cx| async move {
 5669            let context = task_context.await?;
 5670            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5671
 5672            let resolved = resolved_task.resolved.as_mut()?;
 5673            resolved.reveal = reveal_strategy;
 5674
 5675            workspace
 5676                .update(&mut cx, |workspace, cx| {
 5677                    workspace::tasks::schedule_resolved_task(
 5678                        workspace,
 5679                        task_source_kind,
 5680                        resolved_task,
 5681                        false,
 5682                        cx,
 5683                    );
 5684                })
 5685                .ok()
 5686        })
 5687        .detach();
 5688    }
 5689
 5690    fn find_closest_task(
 5691        &mut self,
 5692        cx: &mut Context<Self>,
 5693    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5694        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5695
 5696        let ((buffer_id, row), tasks) = self
 5697            .tasks
 5698            .iter()
 5699            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5700
 5701        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5702        let tasks = Arc::new(tasks.to_owned());
 5703        Some((buffer, *row, tasks))
 5704    }
 5705
 5706    fn find_enclosing_node_task(
 5707        &mut self,
 5708        cx: &mut Context<Self>,
 5709    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5710        let snapshot = self.buffer.read(cx).snapshot(cx);
 5711        let offset = self.selections.newest::<usize>(cx).head();
 5712        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5713        let buffer_id = excerpt.buffer().remote_id();
 5714
 5715        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5716        let mut cursor = layer.node().walk();
 5717
 5718        while cursor.goto_first_child_for_byte(offset).is_some() {
 5719            if cursor.node().end_byte() == offset {
 5720                cursor.goto_next_sibling();
 5721            }
 5722        }
 5723
 5724        // Ascend to the smallest ancestor that contains the range and has a task.
 5725        loop {
 5726            let node = cursor.node();
 5727            let node_range = node.byte_range();
 5728            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5729
 5730            // Check if this node contains our offset
 5731            if node_range.start <= offset && node_range.end >= offset {
 5732                // If it contains offset, check for task
 5733                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5734                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5735                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5736                }
 5737            }
 5738
 5739            if !cursor.goto_parent() {
 5740                break;
 5741            }
 5742        }
 5743        None
 5744    }
 5745
 5746    fn render_run_indicator(
 5747        &self,
 5748        _style: &EditorStyle,
 5749        is_active: bool,
 5750        row: DisplayRow,
 5751        cx: &mut Context<Self>,
 5752    ) -> IconButton {
 5753        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5754            .shape(ui::IconButtonShape::Square)
 5755            .icon_size(IconSize::XSmall)
 5756            .icon_color(Color::Muted)
 5757            .toggle_state(is_active)
 5758            .on_click(cx.listener(move |editor, _e, window, cx| {
 5759                window.focus(&editor.focus_handle(cx));
 5760                editor.toggle_code_actions(
 5761                    &ToggleCodeActions {
 5762                        deployed_from_indicator: Some(row),
 5763                    },
 5764                    window,
 5765                    cx,
 5766                );
 5767            }))
 5768    }
 5769
 5770    pub fn context_menu_visible(&self) -> bool {
 5771        !self.edit_prediction_preview_is_active()
 5772            && self
 5773                .context_menu
 5774                .borrow()
 5775                .as_ref()
 5776                .map_or(false, |menu| menu.visible())
 5777    }
 5778
 5779    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5780        self.context_menu
 5781            .borrow()
 5782            .as_ref()
 5783            .map(|menu| menu.origin())
 5784    }
 5785
 5786    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5787    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5788
 5789    #[allow(clippy::too_many_arguments)]
 5790    fn render_edit_prediction_popover(
 5791        &mut self,
 5792        text_bounds: &Bounds<Pixels>,
 5793        content_origin: gpui::Point<Pixels>,
 5794        editor_snapshot: &EditorSnapshot,
 5795        visible_row_range: Range<DisplayRow>,
 5796        scroll_top: f32,
 5797        scroll_bottom: f32,
 5798        line_layouts: &[LineWithInvisibles],
 5799        line_height: Pixels,
 5800        scroll_pixel_position: gpui::Point<Pixels>,
 5801        newest_selection_head: Option<DisplayPoint>,
 5802        editor_width: Pixels,
 5803        style: &EditorStyle,
 5804        window: &mut Window,
 5805        cx: &mut App,
 5806    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5807        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5808
 5809        if self.edit_prediction_visible_in_cursor_popover(true) {
 5810            return None;
 5811        }
 5812
 5813        match &active_inline_completion.completion {
 5814            InlineCompletion::Move { target, .. } => {
 5815                let target_display_point = target.to_display_point(editor_snapshot);
 5816
 5817                if self.edit_prediction_requires_modifier() {
 5818                    if !self.edit_prediction_preview_is_active() {
 5819                        return None;
 5820                    }
 5821
 5822                    self.render_edit_prediction_modifier_jump_popover(
 5823                        text_bounds,
 5824                        content_origin,
 5825                        visible_row_range,
 5826                        line_layouts,
 5827                        line_height,
 5828                        scroll_pixel_position,
 5829                        newest_selection_head,
 5830                        target_display_point,
 5831                        window,
 5832                        cx,
 5833                    )
 5834                } else {
 5835                    self.render_edit_prediction_eager_jump_popover(
 5836                        text_bounds,
 5837                        content_origin,
 5838                        editor_snapshot,
 5839                        visible_row_range,
 5840                        scroll_top,
 5841                        scroll_bottom,
 5842                        line_height,
 5843                        scroll_pixel_position,
 5844                        target_display_point,
 5845                        editor_width,
 5846                        window,
 5847                        cx,
 5848                    )
 5849                }
 5850            }
 5851            InlineCompletion::Edit {
 5852                display_mode: EditDisplayMode::Inline,
 5853                ..
 5854            } => None,
 5855            InlineCompletion::Edit {
 5856                display_mode: EditDisplayMode::TabAccept,
 5857                edits,
 5858                ..
 5859            } => {
 5860                let range = &edits.first()?.0;
 5861                let target_display_point = range.end.to_display_point(editor_snapshot);
 5862
 5863                self.render_edit_prediction_end_of_line_popover(
 5864                    "Accept",
 5865                    editor_snapshot,
 5866                    visible_row_range,
 5867                    target_display_point,
 5868                    line_height,
 5869                    scroll_pixel_position,
 5870                    content_origin,
 5871                    editor_width,
 5872                    window,
 5873                    cx,
 5874                )
 5875            }
 5876            InlineCompletion::Edit {
 5877                edits,
 5878                edit_preview,
 5879                display_mode: EditDisplayMode::DiffPopover,
 5880                snapshot,
 5881            } => self.render_edit_prediction_diff_popover(
 5882                text_bounds,
 5883                content_origin,
 5884                editor_snapshot,
 5885                visible_row_range,
 5886                line_layouts,
 5887                line_height,
 5888                scroll_pixel_position,
 5889                newest_selection_head,
 5890                editor_width,
 5891                style,
 5892                edits,
 5893                edit_preview,
 5894                snapshot,
 5895                window,
 5896                cx,
 5897            ),
 5898        }
 5899    }
 5900
 5901    #[allow(clippy::too_many_arguments)]
 5902    fn render_edit_prediction_modifier_jump_popover(
 5903        &mut self,
 5904        text_bounds: &Bounds<Pixels>,
 5905        content_origin: gpui::Point<Pixels>,
 5906        visible_row_range: Range<DisplayRow>,
 5907        line_layouts: &[LineWithInvisibles],
 5908        line_height: Pixels,
 5909        scroll_pixel_position: gpui::Point<Pixels>,
 5910        newest_selection_head: Option<DisplayPoint>,
 5911        target_display_point: DisplayPoint,
 5912        window: &mut Window,
 5913        cx: &mut App,
 5914    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5915        let scrolled_content_origin =
 5916            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 5917
 5918        const SCROLL_PADDING_Y: Pixels = px(12.);
 5919
 5920        if target_display_point.row() < visible_row_range.start {
 5921            return self.render_edit_prediction_scroll_popover(
 5922                |_| SCROLL_PADDING_Y,
 5923                IconName::ArrowUp,
 5924                visible_row_range,
 5925                line_layouts,
 5926                newest_selection_head,
 5927                scrolled_content_origin,
 5928                window,
 5929                cx,
 5930            );
 5931        } else if target_display_point.row() >= visible_row_range.end {
 5932            return self.render_edit_prediction_scroll_popover(
 5933                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 5934                IconName::ArrowDown,
 5935                visible_row_range,
 5936                line_layouts,
 5937                newest_selection_head,
 5938                scrolled_content_origin,
 5939                window,
 5940                cx,
 5941            );
 5942        }
 5943
 5944        const POLE_WIDTH: Pixels = px(2.);
 5945
 5946        let mut element = v_flex()
 5947            .items_end()
 5948            .child(
 5949                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 5950                    .rounded_br(px(0.))
 5951                    .rounded_tr(px(0.))
 5952                    .border_r_2(),
 5953            )
 5954            .child(
 5955                div()
 5956                    .w(POLE_WIDTH)
 5957                    .bg(Editor::edit_prediction_callout_popover_border_color(cx))
 5958                    .h(line_height),
 5959            )
 5960            .into_any();
 5961
 5962        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 5963
 5964        let line_layout =
 5965            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 5966        let target_column = target_display_point.column() as usize;
 5967
 5968        let target_x = line_layout.x_for_index(target_column);
 5969        let target_y =
 5970            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 5971
 5972        let mut origin = scrolled_content_origin + point(target_x, target_y)
 5973            - point(size.width - POLE_WIDTH, size.height - line_height);
 5974
 5975        origin.x = origin.x.max(content_origin.x);
 5976
 5977        element.prepaint_at(origin, window, cx);
 5978
 5979        Some((element, origin))
 5980    }
 5981
 5982    #[allow(clippy::too_many_arguments)]
 5983    fn render_edit_prediction_scroll_popover(
 5984        &mut self,
 5985        to_y: impl Fn(Size<Pixels>) -> Pixels,
 5986        scroll_icon: IconName,
 5987        visible_row_range: Range<DisplayRow>,
 5988        line_layouts: &[LineWithInvisibles],
 5989        newest_selection_head: Option<DisplayPoint>,
 5990        scrolled_content_origin: gpui::Point<Pixels>,
 5991        window: &mut Window,
 5992        cx: &mut App,
 5993    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5994        let mut element = self
 5995            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 5996            .into_any();
 5997
 5998        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 5999
 6000        let cursor = newest_selection_head?;
 6001        let cursor_row_layout =
 6002            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6003        let cursor_column = cursor.column() as usize;
 6004
 6005        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6006
 6007        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6008
 6009        element.prepaint_at(origin, window, cx);
 6010        Some((element, origin))
 6011    }
 6012
 6013    #[allow(clippy::too_many_arguments)]
 6014    fn render_edit_prediction_eager_jump_popover(
 6015        &mut self,
 6016        text_bounds: &Bounds<Pixels>,
 6017        content_origin: gpui::Point<Pixels>,
 6018        editor_snapshot: &EditorSnapshot,
 6019        visible_row_range: Range<DisplayRow>,
 6020        scroll_top: f32,
 6021        scroll_bottom: f32,
 6022        line_height: Pixels,
 6023        scroll_pixel_position: gpui::Point<Pixels>,
 6024        target_display_point: DisplayPoint,
 6025        editor_width: Pixels,
 6026        window: &mut Window,
 6027        cx: &mut App,
 6028    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6029        if target_display_point.row().as_f32() < scroll_top {
 6030            let mut element = self
 6031                .render_edit_prediction_line_popover(
 6032                    "Jump to Edit",
 6033                    Some(IconName::ArrowUp),
 6034                    window,
 6035                    cx,
 6036                )?
 6037                .into_any();
 6038
 6039            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6040            let offset = point(
 6041                (text_bounds.size.width - size.width) / 2.,
 6042                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6043            );
 6044
 6045            let origin = text_bounds.origin + offset;
 6046            element.prepaint_at(origin, window, cx);
 6047            Some((element, origin))
 6048        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6049            let mut element = self
 6050                .render_edit_prediction_line_popover(
 6051                    "Jump to Edit",
 6052                    Some(IconName::ArrowDown),
 6053                    window,
 6054                    cx,
 6055                )?
 6056                .into_any();
 6057
 6058            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6059            let offset = point(
 6060                (text_bounds.size.width - size.width) / 2.,
 6061                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6062            );
 6063
 6064            let origin = text_bounds.origin + offset;
 6065            element.prepaint_at(origin, window, cx);
 6066            Some((element, origin))
 6067        } else {
 6068            self.render_edit_prediction_end_of_line_popover(
 6069                "Jump to Edit",
 6070                editor_snapshot,
 6071                visible_row_range,
 6072                target_display_point,
 6073                line_height,
 6074                scroll_pixel_position,
 6075                content_origin,
 6076                editor_width,
 6077                window,
 6078                cx,
 6079            )
 6080        }
 6081    }
 6082
 6083    #[allow(clippy::too_many_arguments)]
 6084    fn render_edit_prediction_end_of_line_popover(
 6085        self: &mut Editor,
 6086        label: &'static str,
 6087        editor_snapshot: &EditorSnapshot,
 6088        visible_row_range: Range<DisplayRow>,
 6089        target_display_point: DisplayPoint,
 6090        line_height: Pixels,
 6091        scroll_pixel_position: gpui::Point<Pixels>,
 6092        content_origin: gpui::Point<Pixels>,
 6093        editor_width: Pixels,
 6094        window: &mut Window,
 6095        cx: &mut App,
 6096    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6097        let target_line_end = DisplayPoint::new(
 6098            target_display_point.row(),
 6099            editor_snapshot.line_len(target_display_point.row()),
 6100        );
 6101
 6102        let mut element = self
 6103            .render_edit_prediction_line_popover(label, None, window, cx)?
 6104            .into_any();
 6105
 6106        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6107
 6108        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6109
 6110        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6111        let mut origin = start_point
 6112            + line_origin
 6113            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6114        origin.x = origin.x.max(content_origin.x);
 6115
 6116        let max_x = content_origin.x + editor_width - size.width;
 6117
 6118        if origin.x > max_x {
 6119            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6120
 6121            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6122                origin.y += offset;
 6123                IconName::ArrowUp
 6124            } else {
 6125                origin.y -= offset;
 6126                IconName::ArrowDown
 6127            };
 6128
 6129            element = self
 6130                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6131                .into_any();
 6132
 6133            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6134
 6135            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6136        }
 6137
 6138        element.prepaint_at(origin, window, cx);
 6139        Some((element, origin))
 6140    }
 6141
 6142    #[allow(clippy::too_many_arguments)]
 6143    fn render_edit_prediction_diff_popover(
 6144        self: &Editor,
 6145        text_bounds: &Bounds<Pixels>,
 6146        content_origin: gpui::Point<Pixels>,
 6147        editor_snapshot: &EditorSnapshot,
 6148        visible_row_range: Range<DisplayRow>,
 6149        line_layouts: &[LineWithInvisibles],
 6150        line_height: Pixels,
 6151        scroll_pixel_position: gpui::Point<Pixels>,
 6152        newest_selection_head: Option<DisplayPoint>,
 6153        editor_width: Pixels,
 6154        style: &EditorStyle,
 6155        edits: &Vec<(Range<Anchor>, String)>,
 6156        edit_preview: &Option<language::EditPreview>,
 6157        snapshot: &language::BufferSnapshot,
 6158        window: &mut Window,
 6159        cx: &mut App,
 6160    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6161        let edit_start = edits
 6162            .first()
 6163            .unwrap()
 6164            .0
 6165            .start
 6166            .to_display_point(editor_snapshot);
 6167        let edit_end = edits
 6168            .last()
 6169            .unwrap()
 6170            .0
 6171            .end
 6172            .to_display_point(editor_snapshot);
 6173
 6174        let is_visible = visible_row_range.contains(&edit_start.row())
 6175            || visible_row_range.contains(&edit_end.row());
 6176        if !is_visible {
 6177            return None;
 6178        }
 6179
 6180        let highlighted_edits =
 6181            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6182
 6183        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6184        let line_count = highlighted_edits.text.lines().count();
 6185
 6186        const BORDER_WIDTH: Pixels = px(1.);
 6187
 6188        let mut element = h_flex()
 6189            .items_start()
 6190            .child(
 6191                h_flex()
 6192                    .bg(cx.theme().colors().editor_background)
 6193                    .border(BORDER_WIDTH)
 6194                    .shadow_sm()
 6195                    .border_color(cx.theme().colors().border)
 6196                    .rounded_l_lg()
 6197                    .when(line_count > 1, |el| el.rounded_br_lg())
 6198                    .pr_1()
 6199                    .child(styled_text),
 6200            )
 6201            .child(
 6202                h_flex()
 6203                    .h(line_height + BORDER_WIDTH * px(2.))
 6204                    .px_1p5()
 6205                    .gap_1()
 6206                    // Workaround: For some reason, there's a gap if we don't do this
 6207                    .ml(-BORDER_WIDTH)
 6208                    .shadow(smallvec![gpui::BoxShadow {
 6209                        color: gpui::black().opacity(0.05),
 6210                        offset: point(px(1.), px(1.)),
 6211                        blur_radius: px(2.),
 6212                        spread_radius: px(0.),
 6213                    }])
 6214                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6215                    .border(BORDER_WIDTH)
 6216                    .border_color(cx.theme().colors().border)
 6217                    .rounded_r_lg()
 6218                    .children(self.render_edit_prediction_accept_keybind(window, cx)),
 6219            )
 6220            .into_any();
 6221
 6222        let longest_row =
 6223            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6224        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6225            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6226        } else {
 6227            layout_line(
 6228                longest_row,
 6229                editor_snapshot,
 6230                style,
 6231                editor_width,
 6232                |_| false,
 6233                window,
 6234                cx,
 6235            )
 6236            .width
 6237        };
 6238
 6239        let viewport_bounds =
 6240            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6241                right: -EditorElement::SCROLLBAR_WIDTH,
 6242                ..Default::default()
 6243            });
 6244
 6245        let x_after_longest =
 6246            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6247                - scroll_pixel_position.x;
 6248
 6249        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6250
 6251        // Fully visible if it can be displayed within the window (allow overlapping other
 6252        // panes). However, this is only allowed if the popover starts within text_bounds.
 6253        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6254            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6255
 6256        let mut origin = if can_position_to_the_right {
 6257            point(
 6258                x_after_longest,
 6259                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6260                    - scroll_pixel_position.y,
 6261            )
 6262        } else {
 6263            let cursor_row = newest_selection_head.map(|head| head.row());
 6264            let above_edit = edit_start
 6265                .row()
 6266                .0
 6267                .checked_sub(line_count as u32)
 6268                .map(DisplayRow);
 6269            let below_edit = Some(edit_end.row() + 1);
 6270            let above_cursor =
 6271                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6272            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6273
 6274            // Place the edit popover adjacent to the edit if there is a location
 6275            // available that is onscreen and does not obscure the cursor. Otherwise,
 6276            // place it adjacent to the cursor.
 6277            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6278                .into_iter()
 6279                .flatten()
 6280                .find(|&start_row| {
 6281                    let end_row = start_row + line_count as u32;
 6282                    visible_row_range.contains(&start_row)
 6283                        && visible_row_range.contains(&end_row)
 6284                        && cursor_row.map_or(true, |cursor_row| {
 6285                            !((start_row..end_row).contains(&cursor_row))
 6286                        })
 6287                })?;
 6288
 6289            content_origin
 6290                + point(
 6291                    -scroll_pixel_position.x,
 6292                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6293                )
 6294        };
 6295
 6296        origin.x -= BORDER_WIDTH;
 6297
 6298        window.defer_draw(element, origin, 1);
 6299
 6300        // Do not return an element, since it will already be drawn due to defer_draw.
 6301        None
 6302    }
 6303
 6304    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6305        px(30.)
 6306    }
 6307
 6308    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6309        if self.read_only(cx) {
 6310            cx.theme().players().read_only()
 6311        } else {
 6312            self.style.as_ref().unwrap().local_player
 6313        }
 6314    }
 6315
 6316    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 6317        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6318        let accept_keystroke = accept_binding.keystroke()?;
 6319
 6320        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6321
 6322        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6323            Color::Accent
 6324        } else {
 6325            Color::Muted
 6326        };
 6327
 6328        h_flex()
 6329            .px_0p5()
 6330            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6331            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6332            .text_size(TextSize::XSmall.rems(cx))
 6333            .child(h_flex().children(ui::render_modifiers(
 6334                &accept_keystroke.modifiers,
 6335                PlatformStyle::platform(),
 6336                Some(modifiers_color),
 6337                Some(IconSize::XSmall.rems().into()),
 6338                true,
 6339            )))
 6340            .when(is_platform_style_mac, |parent| {
 6341                parent.child(accept_keystroke.key.clone())
 6342            })
 6343            .when(!is_platform_style_mac, |parent| {
 6344                parent.child(
 6345                    Key::new(
 6346                        util::capitalize(&accept_keystroke.key),
 6347                        Some(Color::Default),
 6348                    )
 6349                    .size(Some(IconSize::XSmall.rems().into())),
 6350                )
 6351            })
 6352            .into()
 6353    }
 6354
 6355    fn render_edit_prediction_line_popover(
 6356        &self,
 6357        label: impl Into<SharedString>,
 6358        icon: Option<IconName>,
 6359        window: &mut Window,
 6360        cx: &App,
 6361    ) -> Option<Div> {
 6362        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6363
 6364        let result = h_flex()
 6365            .py_0p5()
 6366            .pl_1()
 6367            .pr(padding_right)
 6368            .gap_1()
 6369            .rounded(px(6.))
 6370            .border_1()
 6371            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6372            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6373            .shadow_sm()
 6374            .children(self.render_edit_prediction_accept_keybind(window, cx))
 6375            .child(Label::new(label).size(LabelSize::Small))
 6376            .when_some(icon, |element, icon| {
 6377                element.child(
 6378                    div()
 6379                        .mt(px(1.5))
 6380                        .child(Icon::new(icon).size(IconSize::Small)),
 6381                )
 6382            });
 6383
 6384        Some(result)
 6385    }
 6386
 6387    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6388        let accent_color = cx.theme().colors().text_accent;
 6389        let editor_bg_color = cx.theme().colors().editor_background;
 6390        editor_bg_color.blend(accent_color.opacity(0.1))
 6391    }
 6392
 6393    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6394        let accent_color = cx.theme().colors().text_accent;
 6395        let editor_bg_color = cx.theme().colors().editor_background;
 6396        editor_bg_color.blend(accent_color.opacity(0.6))
 6397    }
 6398
 6399    #[allow(clippy::too_many_arguments)]
 6400    fn render_edit_prediction_cursor_popover(
 6401        &self,
 6402        min_width: Pixels,
 6403        max_width: Pixels,
 6404        cursor_point: Point,
 6405        style: &EditorStyle,
 6406        accept_keystroke: Option<&gpui::Keystroke>,
 6407        _window: &Window,
 6408        cx: &mut Context<Editor>,
 6409    ) -> Option<AnyElement> {
 6410        let provider = self.edit_prediction_provider.as_ref()?;
 6411
 6412        if provider.provider.needs_terms_acceptance(cx) {
 6413            return Some(
 6414                h_flex()
 6415                    .min_w(min_width)
 6416                    .flex_1()
 6417                    .px_2()
 6418                    .py_1()
 6419                    .gap_3()
 6420                    .elevation_2(cx)
 6421                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6422                    .id("accept-terms")
 6423                    .cursor_pointer()
 6424                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6425                    .on_click(cx.listener(|this, _event, window, cx| {
 6426                        cx.stop_propagation();
 6427                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6428                        window.dispatch_action(
 6429                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6430                            cx,
 6431                        );
 6432                    }))
 6433                    .child(
 6434                        h_flex()
 6435                            .flex_1()
 6436                            .gap_2()
 6437                            .child(Icon::new(IconName::ZedPredict))
 6438                            .child(Label::new("Accept Terms of Service"))
 6439                            .child(div().w_full())
 6440                            .child(
 6441                                Icon::new(IconName::ArrowUpRight)
 6442                                    .color(Color::Muted)
 6443                                    .size(IconSize::Small),
 6444                            )
 6445                            .into_any_element(),
 6446                    )
 6447                    .into_any(),
 6448            );
 6449        }
 6450
 6451        let is_refreshing = provider.provider.is_refreshing(cx);
 6452
 6453        fn pending_completion_container() -> Div {
 6454            h_flex()
 6455                .h_full()
 6456                .flex_1()
 6457                .gap_2()
 6458                .child(Icon::new(IconName::ZedPredict))
 6459        }
 6460
 6461        let completion = match &self.active_inline_completion {
 6462            Some(completion) => match &completion.completion {
 6463                InlineCompletion::Move {
 6464                    target, snapshot, ..
 6465                } if !self.has_visible_completions_menu() => {
 6466                    use text::ToPoint as _;
 6467
 6468                    return Some(
 6469                        h_flex()
 6470                            .px_2()
 6471                            .py_1()
 6472                            .gap_2()
 6473                            .elevation_2(cx)
 6474                            .border_color(cx.theme().colors().border)
 6475                            .rounded(px(6.))
 6476                            .rounded_tl(px(0.))
 6477                            .child(
 6478                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6479                                    Icon::new(IconName::ZedPredictDown)
 6480                                } else {
 6481                                    Icon::new(IconName::ZedPredictUp)
 6482                                },
 6483                            )
 6484                            .child(Label::new("Hold").size(LabelSize::Small))
 6485                            .child(h_flex().children(ui::render_modifiers(
 6486                                &accept_keystroke?.modifiers,
 6487                                PlatformStyle::platform(),
 6488                                Some(Color::Default),
 6489                                Some(IconSize::Small.rems().into()),
 6490                                false,
 6491                            )))
 6492                            .into_any(),
 6493                    );
 6494                }
 6495                _ => self.render_edit_prediction_cursor_popover_preview(
 6496                    completion,
 6497                    cursor_point,
 6498                    style,
 6499                    cx,
 6500                )?,
 6501            },
 6502
 6503            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6504                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6505                    stale_completion,
 6506                    cursor_point,
 6507                    style,
 6508                    cx,
 6509                )?,
 6510
 6511                None => {
 6512                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6513                }
 6514            },
 6515
 6516            None => pending_completion_container().child(Label::new("No Prediction")),
 6517        };
 6518
 6519        let completion = if is_refreshing {
 6520            completion
 6521                .with_animation(
 6522                    "loading-completion",
 6523                    Animation::new(Duration::from_secs(2))
 6524                        .repeat()
 6525                        .with_easing(pulsating_between(0.4, 0.8)),
 6526                    |label, delta| label.opacity(delta),
 6527                )
 6528                .into_any_element()
 6529        } else {
 6530            completion.into_any_element()
 6531        };
 6532
 6533        let has_completion = self.active_inline_completion.is_some();
 6534
 6535        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6536        Some(
 6537            h_flex()
 6538                .min_w(min_width)
 6539                .max_w(max_width)
 6540                .flex_1()
 6541                .elevation_2(cx)
 6542                .border_color(cx.theme().colors().border)
 6543                .child(
 6544                    div()
 6545                        .flex_1()
 6546                        .py_1()
 6547                        .px_2()
 6548                        .overflow_hidden()
 6549                        .child(completion),
 6550                )
 6551                .when_some(accept_keystroke, |el, accept_keystroke| {
 6552                    if !accept_keystroke.modifiers.modified() {
 6553                        return el;
 6554                    }
 6555
 6556                    el.child(
 6557                        h_flex()
 6558                            .h_full()
 6559                            .border_l_1()
 6560                            .rounded_r_lg()
 6561                            .border_color(cx.theme().colors().border)
 6562                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6563                            .gap_1()
 6564                            .py_1()
 6565                            .px_2()
 6566                            .child(
 6567                                h_flex()
 6568                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6569                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6570                                    .child(h_flex().children(ui::render_modifiers(
 6571                                        &accept_keystroke.modifiers,
 6572                                        PlatformStyle::platform(),
 6573                                        Some(if !has_completion {
 6574                                            Color::Muted
 6575                                        } else {
 6576                                            Color::Default
 6577                                        }),
 6578                                        None,
 6579                                        false,
 6580                                    ))),
 6581                            )
 6582                            .child(Label::new("Preview").into_any_element())
 6583                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6584                    )
 6585                })
 6586                .into_any(),
 6587        )
 6588    }
 6589
 6590    fn render_edit_prediction_cursor_popover_preview(
 6591        &self,
 6592        completion: &InlineCompletionState,
 6593        cursor_point: Point,
 6594        style: &EditorStyle,
 6595        cx: &mut Context<Editor>,
 6596    ) -> Option<Div> {
 6597        use text::ToPoint as _;
 6598
 6599        fn render_relative_row_jump(
 6600            prefix: impl Into<String>,
 6601            current_row: u32,
 6602            target_row: u32,
 6603        ) -> Div {
 6604            let (row_diff, arrow) = if target_row < current_row {
 6605                (current_row - target_row, IconName::ArrowUp)
 6606            } else {
 6607                (target_row - current_row, IconName::ArrowDown)
 6608            };
 6609
 6610            h_flex()
 6611                .child(
 6612                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6613                        .color(Color::Muted)
 6614                        .size(LabelSize::Small),
 6615                )
 6616                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6617        }
 6618
 6619        match &completion.completion {
 6620            InlineCompletion::Move {
 6621                target, snapshot, ..
 6622            } => Some(
 6623                h_flex()
 6624                    .px_2()
 6625                    .gap_2()
 6626                    .flex_1()
 6627                    .child(
 6628                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6629                            Icon::new(IconName::ZedPredictDown)
 6630                        } else {
 6631                            Icon::new(IconName::ZedPredictUp)
 6632                        },
 6633                    )
 6634                    .child(Label::new("Jump to Edit")),
 6635            ),
 6636
 6637            InlineCompletion::Edit {
 6638                edits,
 6639                edit_preview,
 6640                snapshot,
 6641                display_mode: _,
 6642            } => {
 6643                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6644
 6645                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6646                    &snapshot,
 6647                    &edits,
 6648                    edit_preview.as_ref()?,
 6649                    true,
 6650                    cx,
 6651                )
 6652                .first_line_preview();
 6653
 6654                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6655                    .with_highlights(&style.text, highlighted_edits.highlights);
 6656
 6657                let preview = h_flex()
 6658                    .gap_1()
 6659                    .min_w_16()
 6660                    .child(styled_text)
 6661                    .when(has_more_lines, |parent| parent.child(""));
 6662
 6663                let left = if first_edit_row != cursor_point.row {
 6664                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6665                        .into_any_element()
 6666                } else {
 6667                    Icon::new(IconName::ZedPredict).into_any_element()
 6668                };
 6669
 6670                Some(
 6671                    h_flex()
 6672                        .h_full()
 6673                        .flex_1()
 6674                        .gap_2()
 6675                        .pr_1()
 6676                        .overflow_x_hidden()
 6677                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6678                        .child(left)
 6679                        .child(preview),
 6680                )
 6681            }
 6682        }
 6683    }
 6684
 6685    fn render_context_menu(
 6686        &self,
 6687        style: &EditorStyle,
 6688        max_height_in_lines: u32,
 6689        y_flipped: bool,
 6690        window: &mut Window,
 6691        cx: &mut Context<Editor>,
 6692    ) -> Option<AnyElement> {
 6693        let menu = self.context_menu.borrow();
 6694        let menu = menu.as_ref()?;
 6695        if !menu.visible() {
 6696            return None;
 6697        };
 6698        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6699    }
 6700
 6701    fn render_context_menu_aside(
 6702        &mut self,
 6703        max_size: Size<Pixels>,
 6704        window: &mut Window,
 6705        cx: &mut Context<Editor>,
 6706    ) -> Option<AnyElement> {
 6707        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6708            if menu.visible() {
 6709                menu.render_aside(self, max_size, window, cx)
 6710            } else {
 6711                None
 6712            }
 6713        })
 6714    }
 6715
 6716    fn hide_context_menu(
 6717        &mut self,
 6718        window: &mut Window,
 6719        cx: &mut Context<Self>,
 6720    ) -> Option<CodeContextMenu> {
 6721        cx.notify();
 6722        self.completion_tasks.clear();
 6723        let context_menu = self.context_menu.borrow_mut().take();
 6724        self.stale_inline_completion_in_menu.take();
 6725        self.update_visible_inline_completion(window, cx);
 6726        context_menu
 6727    }
 6728
 6729    fn show_snippet_choices(
 6730        &mut self,
 6731        choices: &Vec<String>,
 6732        selection: Range<Anchor>,
 6733        cx: &mut Context<Self>,
 6734    ) {
 6735        if selection.start.buffer_id.is_none() {
 6736            return;
 6737        }
 6738        let buffer_id = selection.start.buffer_id.unwrap();
 6739        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6740        let id = post_inc(&mut self.next_completion_id);
 6741
 6742        if let Some(buffer) = buffer {
 6743            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6744                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6745            ));
 6746        }
 6747    }
 6748
 6749    pub fn insert_snippet(
 6750        &mut self,
 6751        insertion_ranges: &[Range<usize>],
 6752        snippet: Snippet,
 6753        window: &mut Window,
 6754        cx: &mut Context<Self>,
 6755    ) -> Result<()> {
 6756        struct Tabstop<T> {
 6757            is_end_tabstop: bool,
 6758            ranges: Vec<Range<T>>,
 6759            choices: Option<Vec<String>>,
 6760        }
 6761
 6762        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6763            let snippet_text: Arc<str> = snippet.text.clone().into();
 6764            buffer.edit(
 6765                insertion_ranges
 6766                    .iter()
 6767                    .cloned()
 6768                    .map(|range| (range, snippet_text.clone())),
 6769                Some(AutoindentMode::EachLine),
 6770                cx,
 6771            );
 6772
 6773            let snapshot = &*buffer.read(cx);
 6774            let snippet = &snippet;
 6775            snippet
 6776                .tabstops
 6777                .iter()
 6778                .map(|tabstop| {
 6779                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6780                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6781                    });
 6782                    let mut tabstop_ranges = tabstop
 6783                        .ranges
 6784                        .iter()
 6785                        .flat_map(|tabstop_range| {
 6786                            let mut delta = 0_isize;
 6787                            insertion_ranges.iter().map(move |insertion_range| {
 6788                                let insertion_start = insertion_range.start as isize + delta;
 6789                                delta +=
 6790                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6791
 6792                                let start = ((insertion_start + tabstop_range.start) as usize)
 6793                                    .min(snapshot.len());
 6794                                let end = ((insertion_start + tabstop_range.end) as usize)
 6795                                    .min(snapshot.len());
 6796                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6797                            })
 6798                        })
 6799                        .collect::<Vec<_>>();
 6800                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6801
 6802                    Tabstop {
 6803                        is_end_tabstop,
 6804                        ranges: tabstop_ranges,
 6805                        choices: tabstop.choices.clone(),
 6806                    }
 6807                })
 6808                .collect::<Vec<_>>()
 6809        });
 6810        if let Some(tabstop) = tabstops.first() {
 6811            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6812                s.select_ranges(tabstop.ranges.iter().cloned());
 6813            });
 6814
 6815            if let Some(choices) = &tabstop.choices {
 6816                if let Some(selection) = tabstop.ranges.first() {
 6817                    self.show_snippet_choices(choices, selection.clone(), cx)
 6818                }
 6819            }
 6820
 6821            // If we're already at the last tabstop and it's at the end of the snippet,
 6822            // we're done, we don't need to keep the state around.
 6823            if !tabstop.is_end_tabstop {
 6824                let choices = tabstops
 6825                    .iter()
 6826                    .map(|tabstop| tabstop.choices.clone())
 6827                    .collect();
 6828
 6829                let ranges = tabstops
 6830                    .into_iter()
 6831                    .map(|tabstop| tabstop.ranges)
 6832                    .collect::<Vec<_>>();
 6833
 6834                self.snippet_stack.push(SnippetState {
 6835                    active_index: 0,
 6836                    ranges,
 6837                    choices,
 6838                });
 6839            }
 6840
 6841            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6842            if self.autoclose_regions.is_empty() {
 6843                let snapshot = self.buffer.read(cx).snapshot(cx);
 6844                for selection in &mut self.selections.all::<Point>(cx) {
 6845                    let selection_head = selection.head();
 6846                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6847                        continue;
 6848                    };
 6849
 6850                    let mut bracket_pair = None;
 6851                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6852                    let prev_chars = snapshot
 6853                        .reversed_chars_at(selection_head)
 6854                        .collect::<String>();
 6855                    for (pair, enabled) in scope.brackets() {
 6856                        if enabled
 6857                            && pair.close
 6858                            && prev_chars.starts_with(pair.start.as_str())
 6859                            && next_chars.starts_with(pair.end.as_str())
 6860                        {
 6861                            bracket_pair = Some(pair.clone());
 6862                            break;
 6863                        }
 6864                    }
 6865                    if let Some(pair) = bracket_pair {
 6866                        let start = snapshot.anchor_after(selection_head);
 6867                        let end = snapshot.anchor_after(selection_head);
 6868                        self.autoclose_regions.push(AutocloseRegion {
 6869                            selection_id: selection.id,
 6870                            range: start..end,
 6871                            pair,
 6872                        });
 6873                    }
 6874                }
 6875            }
 6876        }
 6877        Ok(())
 6878    }
 6879
 6880    pub fn move_to_next_snippet_tabstop(
 6881        &mut self,
 6882        window: &mut Window,
 6883        cx: &mut Context<Self>,
 6884    ) -> bool {
 6885        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6886    }
 6887
 6888    pub fn move_to_prev_snippet_tabstop(
 6889        &mut self,
 6890        window: &mut Window,
 6891        cx: &mut Context<Self>,
 6892    ) -> bool {
 6893        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6894    }
 6895
 6896    pub fn move_to_snippet_tabstop(
 6897        &mut self,
 6898        bias: Bias,
 6899        window: &mut Window,
 6900        cx: &mut Context<Self>,
 6901    ) -> bool {
 6902        if let Some(mut snippet) = self.snippet_stack.pop() {
 6903            match bias {
 6904                Bias::Left => {
 6905                    if snippet.active_index > 0 {
 6906                        snippet.active_index -= 1;
 6907                    } else {
 6908                        self.snippet_stack.push(snippet);
 6909                        return false;
 6910                    }
 6911                }
 6912                Bias::Right => {
 6913                    if snippet.active_index + 1 < snippet.ranges.len() {
 6914                        snippet.active_index += 1;
 6915                    } else {
 6916                        self.snippet_stack.push(snippet);
 6917                        return false;
 6918                    }
 6919                }
 6920            }
 6921            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6922                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6923                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6924                });
 6925
 6926                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6927                    if let Some(selection) = current_ranges.first() {
 6928                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6929                    }
 6930                }
 6931
 6932                // If snippet state is not at the last tabstop, push it back on the stack
 6933                if snippet.active_index + 1 < snippet.ranges.len() {
 6934                    self.snippet_stack.push(snippet);
 6935                }
 6936                return true;
 6937            }
 6938        }
 6939
 6940        false
 6941    }
 6942
 6943    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6944        self.transact(window, cx, |this, window, cx| {
 6945            this.select_all(&SelectAll, window, cx);
 6946            this.insert("", window, cx);
 6947        });
 6948    }
 6949
 6950    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6951        self.transact(window, cx, |this, window, cx| {
 6952            this.select_autoclose_pair(window, cx);
 6953            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6954            if !this.linked_edit_ranges.is_empty() {
 6955                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6956                let snapshot = this.buffer.read(cx).snapshot(cx);
 6957
 6958                for selection in selections.iter() {
 6959                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6960                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6961                    if selection_start.buffer_id != selection_end.buffer_id {
 6962                        continue;
 6963                    }
 6964                    if let Some(ranges) =
 6965                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6966                    {
 6967                        for (buffer, entries) in ranges {
 6968                            linked_ranges.entry(buffer).or_default().extend(entries);
 6969                        }
 6970                    }
 6971                }
 6972            }
 6973
 6974            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6975            if !this.selections.line_mode {
 6976                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6977                for selection in &mut selections {
 6978                    if selection.is_empty() {
 6979                        let old_head = selection.head();
 6980                        let mut new_head =
 6981                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6982                                .to_point(&display_map);
 6983                        if let Some((buffer, line_buffer_range)) = display_map
 6984                            .buffer_snapshot
 6985                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6986                        {
 6987                            let indent_size =
 6988                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6989                            let indent_len = match indent_size.kind {
 6990                                IndentKind::Space => {
 6991                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6992                                }
 6993                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6994                            };
 6995                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6996                                let indent_len = indent_len.get();
 6997                                new_head = cmp::min(
 6998                                    new_head,
 6999                                    MultiBufferPoint::new(
 7000                                        old_head.row,
 7001                                        ((old_head.column - 1) / indent_len) * indent_len,
 7002                                    ),
 7003                                );
 7004                            }
 7005                        }
 7006
 7007                        selection.set_head(new_head, SelectionGoal::None);
 7008                    }
 7009                }
 7010            }
 7011
 7012            this.signature_help_state.set_backspace_pressed(true);
 7013            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7014                s.select(selections)
 7015            });
 7016            this.insert("", window, cx);
 7017            let empty_str: Arc<str> = Arc::from("");
 7018            for (buffer, edits) in linked_ranges {
 7019                let snapshot = buffer.read(cx).snapshot();
 7020                use text::ToPoint as TP;
 7021
 7022                let edits = edits
 7023                    .into_iter()
 7024                    .map(|range| {
 7025                        let end_point = TP::to_point(&range.end, &snapshot);
 7026                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7027
 7028                        if end_point == start_point {
 7029                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7030                                .saturating_sub(1);
 7031                            start_point =
 7032                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7033                        };
 7034
 7035                        (start_point..end_point, empty_str.clone())
 7036                    })
 7037                    .sorted_by_key(|(range, _)| range.start)
 7038                    .collect::<Vec<_>>();
 7039                buffer.update(cx, |this, cx| {
 7040                    this.edit(edits, None, cx);
 7041                })
 7042            }
 7043            this.refresh_inline_completion(true, false, window, cx);
 7044            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7045        });
 7046    }
 7047
 7048    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7049        self.transact(window, cx, |this, window, cx| {
 7050            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7051                let line_mode = s.line_mode;
 7052                s.move_with(|map, selection| {
 7053                    if selection.is_empty() && !line_mode {
 7054                        let cursor = movement::right(map, selection.head());
 7055                        selection.end = cursor;
 7056                        selection.reversed = true;
 7057                        selection.goal = SelectionGoal::None;
 7058                    }
 7059                })
 7060            });
 7061            this.insert("", window, cx);
 7062            this.refresh_inline_completion(true, false, window, cx);
 7063        });
 7064    }
 7065
 7066    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 7067        if self.move_to_prev_snippet_tabstop(window, cx) {
 7068            return;
 7069        }
 7070
 7071        self.outdent(&Outdent, window, cx);
 7072    }
 7073
 7074    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7075        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7076            return;
 7077        }
 7078
 7079        let mut selections = self.selections.all_adjusted(cx);
 7080        let buffer = self.buffer.read(cx);
 7081        let snapshot = buffer.snapshot(cx);
 7082        let rows_iter = selections.iter().map(|s| s.head().row);
 7083        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7084
 7085        let mut edits = Vec::new();
 7086        let mut prev_edited_row = 0;
 7087        let mut row_delta = 0;
 7088        for selection in &mut selections {
 7089            if selection.start.row != prev_edited_row {
 7090                row_delta = 0;
 7091            }
 7092            prev_edited_row = selection.end.row;
 7093
 7094            // If the selection is non-empty, then increase the indentation of the selected lines.
 7095            if !selection.is_empty() {
 7096                row_delta =
 7097                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7098                continue;
 7099            }
 7100
 7101            // If the selection is empty and the cursor is in the leading whitespace before the
 7102            // suggested indentation, then auto-indent the line.
 7103            let cursor = selection.head();
 7104            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7105            if let Some(suggested_indent) =
 7106                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7107            {
 7108                if cursor.column < suggested_indent.len
 7109                    && cursor.column <= current_indent.len
 7110                    && current_indent.len <= suggested_indent.len
 7111                {
 7112                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7113                    selection.end = selection.start;
 7114                    if row_delta == 0 {
 7115                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7116                            cursor.row,
 7117                            current_indent,
 7118                            suggested_indent,
 7119                        ));
 7120                        row_delta = suggested_indent.len - current_indent.len;
 7121                    }
 7122                    continue;
 7123                }
 7124            }
 7125
 7126            // Otherwise, insert a hard or soft tab.
 7127            let settings = buffer.settings_at(cursor, cx);
 7128            let tab_size = if settings.hard_tabs {
 7129                IndentSize::tab()
 7130            } else {
 7131                let tab_size = settings.tab_size.get();
 7132                let char_column = snapshot
 7133                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7134                    .flat_map(str::chars)
 7135                    .count()
 7136                    + row_delta as usize;
 7137                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7138                IndentSize::spaces(chars_to_next_tab_stop)
 7139            };
 7140            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7141            selection.end = selection.start;
 7142            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7143            row_delta += tab_size.len;
 7144        }
 7145
 7146        self.transact(window, cx, |this, window, cx| {
 7147            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7148            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7149                s.select(selections)
 7150            });
 7151            this.refresh_inline_completion(true, false, window, cx);
 7152        });
 7153    }
 7154
 7155    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7156        if self.read_only(cx) {
 7157            return;
 7158        }
 7159        let mut selections = self.selections.all::<Point>(cx);
 7160        let mut prev_edited_row = 0;
 7161        let mut row_delta = 0;
 7162        let mut edits = Vec::new();
 7163        let buffer = self.buffer.read(cx);
 7164        let snapshot = buffer.snapshot(cx);
 7165        for selection in &mut selections {
 7166            if selection.start.row != prev_edited_row {
 7167                row_delta = 0;
 7168            }
 7169            prev_edited_row = selection.end.row;
 7170
 7171            row_delta =
 7172                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7173        }
 7174
 7175        self.transact(window, cx, |this, window, cx| {
 7176            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7177            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7178                s.select(selections)
 7179            });
 7180        });
 7181    }
 7182
 7183    fn indent_selection(
 7184        buffer: &MultiBuffer,
 7185        snapshot: &MultiBufferSnapshot,
 7186        selection: &mut Selection<Point>,
 7187        edits: &mut Vec<(Range<Point>, String)>,
 7188        delta_for_start_row: u32,
 7189        cx: &App,
 7190    ) -> u32 {
 7191        let settings = buffer.settings_at(selection.start, cx);
 7192        let tab_size = settings.tab_size.get();
 7193        let indent_kind = if settings.hard_tabs {
 7194            IndentKind::Tab
 7195        } else {
 7196            IndentKind::Space
 7197        };
 7198        let mut start_row = selection.start.row;
 7199        let mut end_row = selection.end.row + 1;
 7200
 7201        // If a selection ends at the beginning of a line, don't indent
 7202        // that last line.
 7203        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7204            end_row -= 1;
 7205        }
 7206
 7207        // Avoid re-indenting a row that has already been indented by a
 7208        // previous selection, but still update this selection's column
 7209        // to reflect that indentation.
 7210        if delta_for_start_row > 0 {
 7211            start_row += 1;
 7212            selection.start.column += delta_for_start_row;
 7213            if selection.end.row == selection.start.row {
 7214                selection.end.column += delta_for_start_row;
 7215            }
 7216        }
 7217
 7218        let mut delta_for_end_row = 0;
 7219        let has_multiple_rows = start_row + 1 != end_row;
 7220        for row in start_row..end_row {
 7221            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7222            let indent_delta = match (current_indent.kind, indent_kind) {
 7223                (IndentKind::Space, IndentKind::Space) => {
 7224                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7225                    IndentSize::spaces(columns_to_next_tab_stop)
 7226                }
 7227                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7228                (_, IndentKind::Tab) => IndentSize::tab(),
 7229            };
 7230
 7231            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7232                0
 7233            } else {
 7234                selection.start.column
 7235            };
 7236            let row_start = Point::new(row, start);
 7237            edits.push((
 7238                row_start..row_start,
 7239                indent_delta.chars().collect::<String>(),
 7240            ));
 7241
 7242            // Update this selection's endpoints to reflect the indentation.
 7243            if row == selection.start.row {
 7244                selection.start.column += indent_delta.len;
 7245            }
 7246            if row == selection.end.row {
 7247                selection.end.column += indent_delta.len;
 7248                delta_for_end_row = indent_delta.len;
 7249            }
 7250        }
 7251
 7252        if selection.start.row == selection.end.row {
 7253            delta_for_start_row + delta_for_end_row
 7254        } else {
 7255            delta_for_end_row
 7256        }
 7257    }
 7258
 7259    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7260        if self.read_only(cx) {
 7261            return;
 7262        }
 7263        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7264        let selections = self.selections.all::<Point>(cx);
 7265        let mut deletion_ranges = Vec::new();
 7266        let mut last_outdent = None;
 7267        {
 7268            let buffer = self.buffer.read(cx);
 7269            let snapshot = buffer.snapshot(cx);
 7270            for selection in &selections {
 7271                let settings = buffer.settings_at(selection.start, cx);
 7272                let tab_size = settings.tab_size.get();
 7273                let mut rows = selection.spanned_rows(false, &display_map);
 7274
 7275                // Avoid re-outdenting a row that has already been outdented by a
 7276                // previous selection.
 7277                if let Some(last_row) = last_outdent {
 7278                    if last_row == rows.start {
 7279                        rows.start = rows.start.next_row();
 7280                    }
 7281                }
 7282                let has_multiple_rows = rows.len() > 1;
 7283                for row in rows.iter_rows() {
 7284                    let indent_size = snapshot.indent_size_for_line(row);
 7285                    if indent_size.len > 0 {
 7286                        let deletion_len = match indent_size.kind {
 7287                            IndentKind::Space => {
 7288                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7289                                if columns_to_prev_tab_stop == 0 {
 7290                                    tab_size
 7291                                } else {
 7292                                    columns_to_prev_tab_stop
 7293                                }
 7294                            }
 7295                            IndentKind::Tab => 1,
 7296                        };
 7297                        let start = if has_multiple_rows
 7298                            || deletion_len > selection.start.column
 7299                            || indent_size.len < selection.start.column
 7300                        {
 7301                            0
 7302                        } else {
 7303                            selection.start.column - deletion_len
 7304                        };
 7305                        deletion_ranges.push(
 7306                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7307                        );
 7308                        last_outdent = Some(row);
 7309                    }
 7310                }
 7311            }
 7312        }
 7313
 7314        self.transact(window, cx, |this, window, cx| {
 7315            this.buffer.update(cx, |buffer, cx| {
 7316                let empty_str: Arc<str> = Arc::default();
 7317                buffer.edit(
 7318                    deletion_ranges
 7319                        .into_iter()
 7320                        .map(|range| (range, empty_str.clone())),
 7321                    None,
 7322                    cx,
 7323                );
 7324            });
 7325            let selections = this.selections.all::<usize>(cx);
 7326            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7327                s.select(selections)
 7328            });
 7329        });
 7330    }
 7331
 7332    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7333        if self.read_only(cx) {
 7334            return;
 7335        }
 7336        let selections = self
 7337            .selections
 7338            .all::<usize>(cx)
 7339            .into_iter()
 7340            .map(|s| s.range());
 7341
 7342        self.transact(window, cx, |this, window, cx| {
 7343            this.buffer.update(cx, |buffer, cx| {
 7344                buffer.autoindent_ranges(selections, cx);
 7345            });
 7346            let selections = this.selections.all::<usize>(cx);
 7347            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7348                s.select(selections)
 7349            });
 7350        });
 7351    }
 7352
 7353    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7354        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7355        let selections = self.selections.all::<Point>(cx);
 7356
 7357        let mut new_cursors = Vec::new();
 7358        let mut edit_ranges = Vec::new();
 7359        let mut selections = selections.iter().peekable();
 7360        while let Some(selection) = selections.next() {
 7361            let mut rows = selection.spanned_rows(false, &display_map);
 7362            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7363
 7364            // Accumulate contiguous regions of rows that we want to delete.
 7365            while let Some(next_selection) = selections.peek() {
 7366                let next_rows = next_selection.spanned_rows(false, &display_map);
 7367                if next_rows.start <= rows.end {
 7368                    rows.end = next_rows.end;
 7369                    selections.next().unwrap();
 7370                } else {
 7371                    break;
 7372                }
 7373            }
 7374
 7375            let buffer = &display_map.buffer_snapshot;
 7376            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7377            let edit_end;
 7378            let cursor_buffer_row;
 7379            if buffer.max_point().row >= rows.end.0 {
 7380                // If there's a line after the range, delete the \n from the end of the row range
 7381                // and position the cursor on the next line.
 7382                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7383                cursor_buffer_row = rows.end;
 7384            } else {
 7385                // If there isn't a line after the range, delete the \n from the line before the
 7386                // start of the row range and position the cursor there.
 7387                edit_start = edit_start.saturating_sub(1);
 7388                edit_end = buffer.len();
 7389                cursor_buffer_row = rows.start.previous_row();
 7390            }
 7391
 7392            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7393            *cursor.column_mut() =
 7394                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7395
 7396            new_cursors.push((
 7397                selection.id,
 7398                buffer.anchor_after(cursor.to_point(&display_map)),
 7399            ));
 7400            edit_ranges.push(edit_start..edit_end);
 7401        }
 7402
 7403        self.transact(window, cx, |this, window, cx| {
 7404            let buffer = this.buffer.update(cx, |buffer, cx| {
 7405                let empty_str: Arc<str> = Arc::default();
 7406                buffer.edit(
 7407                    edit_ranges
 7408                        .into_iter()
 7409                        .map(|range| (range, empty_str.clone())),
 7410                    None,
 7411                    cx,
 7412                );
 7413                buffer.snapshot(cx)
 7414            });
 7415            let new_selections = new_cursors
 7416                .into_iter()
 7417                .map(|(id, cursor)| {
 7418                    let cursor = cursor.to_point(&buffer);
 7419                    Selection {
 7420                        id,
 7421                        start: cursor,
 7422                        end: cursor,
 7423                        reversed: false,
 7424                        goal: SelectionGoal::None,
 7425                    }
 7426                })
 7427                .collect();
 7428
 7429            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7430                s.select(new_selections);
 7431            });
 7432        });
 7433    }
 7434
 7435    pub fn join_lines_impl(
 7436        &mut self,
 7437        insert_whitespace: bool,
 7438        window: &mut Window,
 7439        cx: &mut Context<Self>,
 7440    ) {
 7441        if self.read_only(cx) {
 7442            return;
 7443        }
 7444        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7445        for selection in self.selections.all::<Point>(cx) {
 7446            let start = MultiBufferRow(selection.start.row);
 7447            // Treat single line selections as if they include the next line. Otherwise this action
 7448            // would do nothing for single line selections individual cursors.
 7449            let end = if selection.start.row == selection.end.row {
 7450                MultiBufferRow(selection.start.row + 1)
 7451            } else {
 7452                MultiBufferRow(selection.end.row)
 7453            };
 7454
 7455            if let Some(last_row_range) = row_ranges.last_mut() {
 7456                if start <= last_row_range.end {
 7457                    last_row_range.end = end;
 7458                    continue;
 7459                }
 7460            }
 7461            row_ranges.push(start..end);
 7462        }
 7463
 7464        let snapshot = self.buffer.read(cx).snapshot(cx);
 7465        let mut cursor_positions = Vec::new();
 7466        for row_range in &row_ranges {
 7467            let anchor = snapshot.anchor_before(Point::new(
 7468                row_range.end.previous_row().0,
 7469                snapshot.line_len(row_range.end.previous_row()),
 7470            ));
 7471            cursor_positions.push(anchor..anchor);
 7472        }
 7473
 7474        self.transact(window, cx, |this, window, cx| {
 7475            for row_range in row_ranges.into_iter().rev() {
 7476                for row in row_range.iter_rows().rev() {
 7477                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7478                    let next_line_row = row.next_row();
 7479                    let indent = snapshot.indent_size_for_line(next_line_row);
 7480                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7481
 7482                    let replace =
 7483                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7484                            " "
 7485                        } else {
 7486                            ""
 7487                        };
 7488
 7489                    this.buffer.update(cx, |buffer, cx| {
 7490                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7491                    });
 7492                }
 7493            }
 7494
 7495            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7496                s.select_anchor_ranges(cursor_positions)
 7497            });
 7498        });
 7499    }
 7500
 7501    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7502        self.join_lines_impl(true, window, cx);
 7503    }
 7504
 7505    pub fn sort_lines_case_sensitive(
 7506        &mut self,
 7507        _: &SortLinesCaseSensitive,
 7508        window: &mut Window,
 7509        cx: &mut Context<Self>,
 7510    ) {
 7511        self.manipulate_lines(window, cx, |lines| lines.sort())
 7512    }
 7513
 7514    pub fn sort_lines_case_insensitive(
 7515        &mut self,
 7516        _: &SortLinesCaseInsensitive,
 7517        window: &mut Window,
 7518        cx: &mut Context<Self>,
 7519    ) {
 7520        self.manipulate_lines(window, cx, |lines| {
 7521            lines.sort_by_key(|line| line.to_lowercase())
 7522        })
 7523    }
 7524
 7525    pub fn unique_lines_case_insensitive(
 7526        &mut self,
 7527        _: &UniqueLinesCaseInsensitive,
 7528        window: &mut Window,
 7529        cx: &mut Context<Self>,
 7530    ) {
 7531        self.manipulate_lines(window, cx, |lines| {
 7532            let mut seen = HashSet::default();
 7533            lines.retain(|line| seen.insert(line.to_lowercase()));
 7534        })
 7535    }
 7536
 7537    pub fn unique_lines_case_sensitive(
 7538        &mut self,
 7539        _: &UniqueLinesCaseSensitive,
 7540        window: &mut Window,
 7541        cx: &mut Context<Self>,
 7542    ) {
 7543        self.manipulate_lines(window, cx, |lines| {
 7544            let mut seen = HashSet::default();
 7545            lines.retain(|line| seen.insert(*line));
 7546        })
 7547    }
 7548
 7549    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7550        let Some(project) = self.project.clone() else {
 7551            return;
 7552        };
 7553        self.reload(project, window, cx)
 7554            .detach_and_notify_err(window, cx);
 7555    }
 7556
 7557    pub fn restore_file(
 7558        &mut self,
 7559        _: &::git::RestoreFile,
 7560        window: &mut Window,
 7561        cx: &mut Context<Self>,
 7562    ) {
 7563        let mut buffer_ids = HashSet::default();
 7564        let snapshot = self.buffer().read(cx).snapshot(cx);
 7565        for selection in self.selections.all::<usize>(cx) {
 7566            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7567        }
 7568
 7569        let buffer = self.buffer().read(cx);
 7570        let ranges = buffer_ids
 7571            .into_iter()
 7572            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7573            .collect::<Vec<_>>();
 7574
 7575        self.restore_hunks_in_ranges(ranges, window, cx);
 7576    }
 7577
 7578    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7579        let selections = self
 7580            .selections
 7581            .all(cx)
 7582            .into_iter()
 7583            .map(|s| s.range())
 7584            .collect();
 7585        self.restore_hunks_in_ranges(selections, window, cx);
 7586    }
 7587
 7588    fn restore_hunks_in_ranges(
 7589        &mut self,
 7590        ranges: Vec<Range<Point>>,
 7591        window: &mut Window,
 7592        cx: &mut Context<Editor>,
 7593    ) {
 7594        let mut revert_changes = HashMap::default();
 7595        let snapshot = self.buffer.read(cx).snapshot(cx);
 7596        let Some(project) = &self.project else {
 7597            return;
 7598        };
 7599
 7600        let chunk_by = self
 7601            .snapshot(window, cx)
 7602            .hunks_for_ranges(ranges.into_iter())
 7603            .into_iter()
 7604            .chunk_by(|hunk| hunk.buffer_id);
 7605        for (buffer_id, hunks) in &chunk_by {
 7606            let hunks = hunks.collect::<Vec<_>>();
 7607            for hunk in &hunks {
 7608                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7609            }
 7610            Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
 7611        }
 7612        drop(chunk_by);
 7613        if !revert_changes.is_empty() {
 7614            self.transact(window, cx, |editor, window, cx| {
 7615                editor.revert(revert_changes, window, cx);
 7616            });
 7617        }
 7618    }
 7619
 7620    pub fn open_active_item_in_terminal(
 7621        &mut self,
 7622        _: &OpenInTerminal,
 7623        window: &mut Window,
 7624        cx: &mut Context<Self>,
 7625    ) {
 7626        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7627            let project_path = buffer.read(cx).project_path(cx)?;
 7628            let project = self.project.as_ref()?.read(cx);
 7629            let entry = project.entry_for_path(&project_path, cx)?;
 7630            let parent = match &entry.canonical_path {
 7631                Some(canonical_path) => canonical_path.to_path_buf(),
 7632                None => project.absolute_path(&project_path, cx)?,
 7633            }
 7634            .parent()?
 7635            .to_path_buf();
 7636            Some(parent)
 7637        }) {
 7638            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7639        }
 7640    }
 7641
 7642    pub fn prepare_restore_change(
 7643        &self,
 7644        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7645        hunk: &MultiBufferDiffHunk,
 7646        cx: &mut App,
 7647    ) -> Option<()> {
 7648        let buffer = self.buffer.read(cx);
 7649        let diff = buffer.diff_for(hunk.buffer_id)?;
 7650        let buffer = buffer.buffer(hunk.buffer_id)?;
 7651        let buffer = buffer.read(cx);
 7652        let original_text = diff
 7653            .read(cx)
 7654            .base_text()
 7655            .as_ref()?
 7656            .as_rope()
 7657            .slice(hunk.diff_base_byte_range.clone());
 7658        let buffer_snapshot = buffer.snapshot();
 7659        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7660        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7661            probe
 7662                .0
 7663                .start
 7664                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7665                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7666        }) {
 7667            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7668            Some(())
 7669        } else {
 7670            None
 7671        }
 7672    }
 7673
 7674    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7675        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7676    }
 7677
 7678    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7679        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7680    }
 7681
 7682    fn manipulate_lines<Fn>(
 7683        &mut self,
 7684        window: &mut Window,
 7685        cx: &mut Context<Self>,
 7686        mut callback: Fn,
 7687    ) where
 7688        Fn: FnMut(&mut Vec<&str>),
 7689    {
 7690        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7691        let buffer = self.buffer.read(cx).snapshot(cx);
 7692
 7693        let mut edits = Vec::new();
 7694
 7695        let selections = self.selections.all::<Point>(cx);
 7696        let mut selections = selections.iter().peekable();
 7697        let mut contiguous_row_selections = Vec::new();
 7698        let mut new_selections = Vec::new();
 7699        let mut added_lines = 0;
 7700        let mut removed_lines = 0;
 7701
 7702        while let Some(selection) = selections.next() {
 7703            let (start_row, end_row) = consume_contiguous_rows(
 7704                &mut contiguous_row_selections,
 7705                selection,
 7706                &display_map,
 7707                &mut selections,
 7708            );
 7709
 7710            let start_point = Point::new(start_row.0, 0);
 7711            let end_point = Point::new(
 7712                end_row.previous_row().0,
 7713                buffer.line_len(end_row.previous_row()),
 7714            );
 7715            let text = buffer
 7716                .text_for_range(start_point..end_point)
 7717                .collect::<String>();
 7718
 7719            let mut lines = text.split('\n').collect_vec();
 7720
 7721            let lines_before = lines.len();
 7722            callback(&mut lines);
 7723            let lines_after = lines.len();
 7724
 7725            edits.push((start_point..end_point, lines.join("\n")));
 7726
 7727            // Selections must change based on added and removed line count
 7728            let start_row =
 7729                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7730            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7731            new_selections.push(Selection {
 7732                id: selection.id,
 7733                start: start_row,
 7734                end: end_row,
 7735                goal: SelectionGoal::None,
 7736                reversed: selection.reversed,
 7737            });
 7738
 7739            if lines_after > lines_before {
 7740                added_lines += lines_after - lines_before;
 7741            } else if lines_before > lines_after {
 7742                removed_lines += lines_before - lines_after;
 7743            }
 7744        }
 7745
 7746        self.transact(window, cx, |this, window, cx| {
 7747            let buffer = this.buffer.update(cx, |buffer, cx| {
 7748                buffer.edit(edits, None, cx);
 7749                buffer.snapshot(cx)
 7750            });
 7751
 7752            // Recalculate offsets on newly edited buffer
 7753            let new_selections = new_selections
 7754                .iter()
 7755                .map(|s| {
 7756                    let start_point = Point::new(s.start.0, 0);
 7757                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7758                    Selection {
 7759                        id: s.id,
 7760                        start: buffer.point_to_offset(start_point),
 7761                        end: buffer.point_to_offset(end_point),
 7762                        goal: s.goal,
 7763                        reversed: s.reversed,
 7764                    }
 7765                })
 7766                .collect();
 7767
 7768            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7769                s.select(new_selections);
 7770            });
 7771
 7772            this.request_autoscroll(Autoscroll::fit(), cx);
 7773        });
 7774    }
 7775
 7776    pub fn convert_to_upper_case(
 7777        &mut self,
 7778        _: &ConvertToUpperCase,
 7779        window: &mut Window,
 7780        cx: &mut Context<Self>,
 7781    ) {
 7782        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7783    }
 7784
 7785    pub fn convert_to_lower_case(
 7786        &mut self,
 7787        _: &ConvertToLowerCase,
 7788        window: &mut Window,
 7789        cx: &mut Context<Self>,
 7790    ) {
 7791        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7792    }
 7793
 7794    pub fn convert_to_title_case(
 7795        &mut self,
 7796        _: &ConvertToTitleCase,
 7797        window: &mut Window,
 7798        cx: &mut Context<Self>,
 7799    ) {
 7800        self.manipulate_text(window, cx, |text| {
 7801            text.split('\n')
 7802                .map(|line| line.to_case(Case::Title))
 7803                .join("\n")
 7804        })
 7805    }
 7806
 7807    pub fn convert_to_snake_case(
 7808        &mut self,
 7809        _: &ConvertToSnakeCase,
 7810        window: &mut Window,
 7811        cx: &mut Context<Self>,
 7812    ) {
 7813        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7814    }
 7815
 7816    pub fn convert_to_kebab_case(
 7817        &mut self,
 7818        _: &ConvertToKebabCase,
 7819        window: &mut Window,
 7820        cx: &mut Context<Self>,
 7821    ) {
 7822        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7823    }
 7824
 7825    pub fn convert_to_upper_camel_case(
 7826        &mut self,
 7827        _: &ConvertToUpperCamelCase,
 7828        window: &mut Window,
 7829        cx: &mut Context<Self>,
 7830    ) {
 7831        self.manipulate_text(window, cx, |text| {
 7832            text.split('\n')
 7833                .map(|line| line.to_case(Case::UpperCamel))
 7834                .join("\n")
 7835        })
 7836    }
 7837
 7838    pub fn convert_to_lower_camel_case(
 7839        &mut self,
 7840        _: &ConvertToLowerCamelCase,
 7841        window: &mut Window,
 7842        cx: &mut Context<Self>,
 7843    ) {
 7844        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7845    }
 7846
 7847    pub fn convert_to_opposite_case(
 7848        &mut self,
 7849        _: &ConvertToOppositeCase,
 7850        window: &mut Window,
 7851        cx: &mut Context<Self>,
 7852    ) {
 7853        self.manipulate_text(window, cx, |text| {
 7854            text.chars()
 7855                .fold(String::with_capacity(text.len()), |mut t, c| {
 7856                    if c.is_uppercase() {
 7857                        t.extend(c.to_lowercase());
 7858                    } else {
 7859                        t.extend(c.to_uppercase());
 7860                    }
 7861                    t
 7862                })
 7863        })
 7864    }
 7865
 7866    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7867    where
 7868        Fn: FnMut(&str) -> String,
 7869    {
 7870        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7871        let buffer = self.buffer.read(cx).snapshot(cx);
 7872
 7873        let mut new_selections = Vec::new();
 7874        let mut edits = Vec::new();
 7875        let mut selection_adjustment = 0i32;
 7876
 7877        for selection in self.selections.all::<usize>(cx) {
 7878            let selection_is_empty = selection.is_empty();
 7879
 7880            let (start, end) = if selection_is_empty {
 7881                let word_range = movement::surrounding_word(
 7882                    &display_map,
 7883                    selection.start.to_display_point(&display_map),
 7884                );
 7885                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7886                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7887                (start, end)
 7888            } else {
 7889                (selection.start, selection.end)
 7890            };
 7891
 7892            let text = buffer.text_for_range(start..end).collect::<String>();
 7893            let old_length = text.len() as i32;
 7894            let text = callback(&text);
 7895
 7896            new_selections.push(Selection {
 7897                start: (start as i32 - selection_adjustment) as usize,
 7898                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7899                goal: SelectionGoal::None,
 7900                ..selection
 7901            });
 7902
 7903            selection_adjustment += old_length - text.len() as i32;
 7904
 7905            edits.push((start..end, text));
 7906        }
 7907
 7908        self.transact(window, cx, |this, window, cx| {
 7909            this.buffer.update(cx, |buffer, cx| {
 7910                buffer.edit(edits, None, cx);
 7911            });
 7912
 7913            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7914                s.select(new_selections);
 7915            });
 7916
 7917            this.request_autoscroll(Autoscroll::fit(), cx);
 7918        });
 7919    }
 7920
 7921    pub fn duplicate(
 7922        &mut self,
 7923        upwards: bool,
 7924        whole_lines: bool,
 7925        window: &mut Window,
 7926        cx: &mut Context<Self>,
 7927    ) {
 7928        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7929        let buffer = &display_map.buffer_snapshot;
 7930        let selections = self.selections.all::<Point>(cx);
 7931
 7932        let mut edits = Vec::new();
 7933        let mut selections_iter = selections.iter().peekable();
 7934        while let Some(selection) = selections_iter.next() {
 7935            let mut rows = selection.spanned_rows(false, &display_map);
 7936            // duplicate line-wise
 7937            if whole_lines || selection.start == selection.end {
 7938                // Avoid duplicating the same lines twice.
 7939                while let Some(next_selection) = selections_iter.peek() {
 7940                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7941                    if next_rows.start < rows.end {
 7942                        rows.end = next_rows.end;
 7943                        selections_iter.next().unwrap();
 7944                    } else {
 7945                        break;
 7946                    }
 7947                }
 7948
 7949                // Copy the text from the selected row region and splice it either at the start
 7950                // or end of the region.
 7951                let start = Point::new(rows.start.0, 0);
 7952                let end = Point::new(
 7953                    rows.end.previous_row().0,
 7954                    buffer.line_len(rows.end.previous_row()),
 7955                );
 7956                let text = buffer
 7957                    .text_for_range(start..end)
 7958                    .chain(Some("\n"))
 7959                    .collect::<String>();
 7960                let insert_location = if upwards {
 7961                    Point::new(rows.end.0, 0)
 7962                } else {
 7963                    start
 7964                };
 7965                edits.push((insert_location..insert_location, text));
 7966            } else {
 7967                // duplicate character-wise
 7968                let start = selection.start;
 7969                let end = selection.end;
 7970                let text = buffer.text_for_range(start..end).collect::<String>();
 7971                edits.push((selection.end..selection.end, text));
 7972            }
 7973        }
 7974
 7975        self.transact(window, cx, |this, _, cx| {
 7976            this.buffer.update(cx, |buffer, cx| {
 7977                buffer.edit(edits, None, cx);
 7978            });
 7979
 7980            this.request_autoscroll(Autoscroll::fit(), cx);
 7981        });
 7982    }
 7983
 7984    pub fn duplicate_line_up(
 7985        &mut self,
 7986        _: &DuplicateLineUp,
 7987        window: &mut Window,
 7988        cx: &mut Context<Self>,
 7989    ) {
 7990        self.duplicate(true, true, window, cx);
 7991    }
 7992
 7993    pub fn duplicate_line_down(
 7994        &mut self,
 7995        _: &DuplicateLineDown,
 7996        window: &mut Window,
 7997        cx: &mut Context<Self>,
 7998    ) {
 7999        self.duplicate(false, true, window, cx);
 8000    }
 8001
 8002    pub fn duplicate_selection(
 8003        &mut self,
 8004        _: &DuplicateSelection,
 8005        window: &mut Window,
 8006        cx: &mut Context<Self>,
 8007    ) {
 8008        self.duplicate(false, false, window, cx);
 8009    }
 8010
 8011    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8012        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8013        let buffer = self.buffer.read(cx).snapshot(cx);
 8014
 8015        let mut edits = Vec::new();
 8016        let mut unfold_ranges = Vec::new();
 8017        let mut refold_creases = Vec::new();
 8018
 8019        let selections = self.selections.all::<Point>(cx);
 8020        let mut selections = selections.iter().peekable();
 8021        let mut contiguous_row_selections = Vec::new();
 8022        let mut new_selections = Vec::new();
 8023
 8024        while let Some(selection) = selections.next() {
 8025            // Find all the selections that span a contiguous row range
 8026            let (start_row, end_row) = consume_contiguous_rows(
 8027                &mut contiguous_row_selections,
 8028                selection,
 8029                &display_map,
 8030                &mut selections,
 8031            );
 8032
 8033            // Move the text spanned by the row range to be before the line preceding the row range
 8034            if start_row.0 > 0 {
 8035                let range_to_move = Point::new(
 8036                    start_row.previous_row().0,
 8037                    buffer.line_len(start_row.previous_row()),
 8038                )
 8039                    ..Point::new(
 8040                        end_row.previous_row().0,
 8041                        buffer.line_len(end_row.previous_row()),
 8042                    );
 8043                let insertion_point = display_map
 8044                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8045                    .0;
 8046
 8047                // Don't move lines across excerpts
 8048                if buffer
 8049                    .excerpt_containing(insertion_point..range_to_move.end)
 8050                    .is_some()
 8051                {
 8052                    let text = buffer
 8053                        .text_for_range(range_to_move.clone())
 8054                        .flat_map(|s| s.chars())
 8055                        .skip(1)
 8056                        .chain(['\n'])
 8057                        .collect::<String>();
 8058
 8059                    edits.push((
 8060                        buffer.anchor_after(range_to_move.start)
 8061                            ..buffer.anchor_before(range_to_move.end),
 8062                        String::new(),
 8063                    ));
 8064                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8065                    edits.push((insertion_anchor..insertion_anchor, text));
 8066
 8067                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8068
 8069                    // Move selections up
 8070                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8071                        |mut selection| {
 8072                            selection.start.row -= row_delta;
 8073                            selection.end.row -= row_delta;
 8074                            selection
 8075                        },
 8076                    ));
 8077
 8078                    // Move folds up
 8079                    unfold_ranges.push(range_to_move.clone());
 8080                    for fold in display_map.folds_in_range(
 8081                        buffer.anchor_before(range_to_move.start)
 8082                            ..buffer.anchor_after(range_to_move.end),
 8083                    ) {
 8084                        let mut start = fold.range.start.to_point(&buffer);
 8085                        let mut end = fold.range.end.to_point(&buffer);
 8086                        start.row -= row_delta;
 8087                        end.row -= row_delta;
 8088                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8089                    }
 8090                }
 8091            }
 8092
 8093            // If we didn't move line(s), preserve the existing selections
 8094            new_selections.append(&mut contiguous_row_selections);
 8095        }
 8096
 8097        self.transact(window, cx, |this, window, cx| {
 8098            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8099            this.buffer.update(cx, |buffer, cx| {
 8100                for (range, text) in edits {
 8101                    buffer.edit([(range, text)], None, cx);
 8102                }
 8103            });
 8104            this.fold_creases(refold_creases, true, window, cx);
 8105            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8106                s.select(new_selections);
 8107            })
 8108        });
 8109    }
 8110
 8111    pub fn move_line_down(
 8112        &mut self,
 8113        _: &MoveLineDown,
 8114        window: &mut Window,
 8115        cx: &mut Context<Self>,
 8116    ) {
 8117        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8118        let buffer = self.buffer.read(cx).snapshot(cx);
 8119
 8120        let mut edits = Vec::new();
 8121        let mut unfold_ranges = Vec::new();
 8122        let mut refold_creases = Vec::new();
 8123
 8124        let selections = self.selections.all::<Point>(cx);
 8125        let mut selections = selections.iter().peekable();
 8126        let mut contiguous_row_selections = Vec::new();
 8127        let mut new_selections = Vec::new();
 8128
 8129        while let Some(selection) = selections.next() {
 8130            // Find all the selections that span a contiguous row range
 8131            let (start_row, end_row) = consume_contiguous_rows(
 8132                &mut contiguous_row_selections,
 8133                selection,
 8134                &display_map,
 8135                &mut selections,
 8136            );
 8137
 8138            // Move the text spanned by the row range to be after the last line of the row range
 8139            if end_row.0 <= buffer.max_point().row {
 8140                let range_to_move =
 8141                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8142                let insertion_point = display_map
 8143                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8144                    .0;
 8145
 8146                // Don't move lines across excerpt boundaries
 8147                if buffer
 8148                    .excerpt_containing(range_to_move.start..insertion_point)
 8149                    .is_some()
 8150                {
 8151                    let mut text = String::from("\n");
 8152                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8153                    text.pop(); // Drop trailing newline
 8154                    edits.push((
 8155                        buffer.anchor_after(range_to_move.start)
 8156                            ..buffer.anchor_before(range_to_move.end),
 8157                        String::new(),
 8158                    ));
 8159                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8160                    edits.push((insertion_anchor..insertion_anchor, text));
 8161
 8162                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8163
 8164                    // Move selections down
 8165                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8166                        |mut selection| {
 8167                            selection.start.row += row_delta;
 8168                            selection.end.row += row_delta;
 8169                            selection
 8170                        },
 8171                    ));
 8172
 8173                    // Move folds down
 8174                    unfold_ranges.push(range_to_move.clone());
 8175                    for fold in display_map.folds_in_range(
 8176                        buffer.anchor_before(range_to_move.start)
 8177                            ..buffer.anchor_after(range_to_move.end),
 8178                    ) {
 8179                        let mut start = fold.range.start.to_point(&buffer);
 8180                        let mut end = fold.range.end.to_point(&buffer);
 8181                        start.row += row_delta;
 8182                        end.row += row_delta;
 8183                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8184                    }
 8185                }
 8186            }
 8187
 8188            // If we didn't move line(s), preserve the existing selections
 8189            new_selections.append(&mut contiguous_row_selections);
 8190        }
 8191
 8192        self.transact(window, cx, |this, window, cx| {
 8193            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8194            this.buffer.update(cx, |buffer, cx| {
 8195                for (range, text) in edits {
 8196                    buffer.edit([(range, text)], None, cx);
 8197                }
 8198            });
 8199            this.fold_creases(refold_creases, true, window, cx);
 8200            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8201                s.select(new_selections)
 8202            });
 8203        });
 8204    }
 8205
 8206    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8207        let text_layout_details = &self.text_layout_details(window);
 8208        self.transact(window, cx, |this, window, cx| {
 8209            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8210                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8211                let line_mode = s.line_mode;
 8212                s.move_with(|display_map, selection| {
 8213                    if !selection.is_empty() || line_mode {
 8214                        return;
 8215                    }
 8216
 8217                    let mut head = selection.head();
 8218                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8219                    if head.column() == display_map.line_len(head.row()) {
 8220                        transpose_offset = display_map
 8221                            .buffer_snapshot
 8222                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8223                    }
 8224
 8225                    if transpose_offset == 0 {
 8226                        return;
 8227                    }
 8228
 8229                    *head.column_mut() += 1;
 8230                    head = display_map.clip_point(head, Bias::Right);
 8231                    let goal = SelectionGoal::HorizontalPosition(
 8232                        display_map
 8233                            .x_for_display_point(head, text_layout_details)
 8234                            .into(),
 8235                    );
 8236                    selection.collapse_to(head, goal);
 8237
 8238                    let transpose_start = display_map
 8239                        .buffer_snapshot
 8240                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8241                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8242                        let transpose_end = display_map
 8243                            .buffer_snapshot
 8244                            .clip_offset(transpose_offset + 1, Bias::Right);
 8245                        if let Some(ch) =
 8246                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8247                        {
 8248                            edits.push((transpose_start..transpose_offset, String::new()));
 8249                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8250                        }
 8251                    }
 8252                });
 8253                edits
 8254            });
 8255            this.buffer
 8256                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8257            let selections = this.selections.all::<usize>(cx);
 8258            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8259                s.select(selections);
 8260            });
 8261        });
 8262    }
 8263
 8264    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8265        self.rewrap_impl(IsVimMode::No, cx)
 8266    }
 8267
 8268    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8269        let buffer = self.buffer.read(cx).snapshot(cx);
 8270        let selections = self.selections.all::<Point>(cx);
 8271        let mut selections = selections.iter().peekable();
 8272
 8273        let mut edits = Vec::new();
 8274        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8275
 8276        while let Some(selection) = selections.next() {
 8277            let mut start_row = selection.start.row;
 8278            let mut end_row = selection.end.row;
 8279
 8280            // Skip selections that overlap with a range that has already been rewrapped.
 8281            let selection_range = start_row..end_row;
 8282            if rewrapped_row_ranges
 8283                .iter()
 8284                .any(|range| range.overlaps(&selection_range))
 8285            {
 8286                continue;
 8287            }
 8288
 8289            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 8290
 8291            // Since not all lines in the selection may be at the same indent
 8292            // level, choose the indent size that is the most common between all
 8293            // of the lines.
 8294            //
 8295            // If there is a tie, we use the deepest indent.
 8296            let (indent_size, indent_end) = {
 8297                let mut indent_size_occurrences = HashMap::default();
 8298                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8299
 8300                for row in start_row..=end_row {
 8301                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8302                    rows_by_indent_size.entry(indent).or_default().push(row);
 8303                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8304                }
 8305
 8306                let indent_size = indent_size_occurrences
 8307                    .into_iter()
 8308                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8309                    .map(|(indent, _)| indent)
 8310                    .unwrap_or_default();
 8311                let row = rows_by_indent_size[&indent_size][0];
 8312                let indent_end = Point::new(row, indent_size.len);
 8313
 8314                (indent_size, indent_end)
 8315            };
 8316
 8317            let mut line_prefix = indent_size.chars().collect::<String>();
 8318
 8319            let mut inside_comment = false;
 8320            if let Some(comment_prefix) =
 8321                buffer
 8322                    .language_scope_at(selection.head())
 8323                    .and_then(|language| {
 8324                        language
 8325                            .line_comment_prefixes()
 8326                            .iter()
 8327                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8328                            .cloned()
 8329                    })
 8330            {
 8331                line_prefix.push_str(&comment_prefix);
 8332                inside_comment = true;
 8333            }
 8334
 8335            let language_settings = buffer.settings_at(selection.head(), cx);
 8336            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8337                RewrapBehavior::InComments => inside_comment,
 8338                RewrapBehavior::InSelections => !selection.is_empty(),
 8339                RewrapBehavior::Anywhere => true,
 8340            };
 8341
 8342            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8343            if !should_rewrap {
 8344                continue;
 8345            }
 8346
 8347            if selection.is_empty() {
 8348                'expand_upwards: while start_row > 0 {
 8349                    let prev_row = start_row - 1;
 8350                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8351                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8352                    {
 8353                        start_row = prev_row;
 8354                    } else {
 8355                        break 'expand_upwards;
 8356                    }
 8357                }
 8358
 8359                'expand_downwards: while end_row < buffer.max_point().row {
 8360                    let next_row = end_row + 1;
 8361                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8362                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8363                    {
 8364                        end_row = next_row;
 8365                    } else {
 8366                        break 'expand_downwards;
 8367                    }
 8368                }
 8369            }
 8370
 8371            let start = Point::new(start_row, 0);
 8372            let start_offset = start.to_offset(&buffer);
 8373            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8374            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8375            let Some(lines_without_prefixes) = selection_text
 8376                .lines()
 8377                .map(|line| {
 8378                    line.strip_prefix(&line_prefix)
 8379                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8380                        .ok_or_else(|| {
 8381                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8382                        })
 8383                })
 8384                .collect::<Result<Vec<_>, _>>()
 8385                .log_err()
 8386            else {
 8387                continue;
 8388            };
 8389
 8390            let wrap_column = buffer
 8391                .settings_at(Point::new(start_row, 0), cx)
 8392                .preferred_line_length as usize;
 8393            let wrapped_text = wrap_with_prefix(
 8394                line_prefix,
 8395                lines_without_prefixes.join(" "),
 8396                wrap_column,
 8397                tab_size,
 8398            );
 8399
 8400            // TODO: should always use char-based diff while still supporting cursor behavior that
 8401            // matches vim.
 8402            let mut diff_options = DiffOptions::default();
 8403            if is_vim_mode == IsVimMode::Yes {
 8404                diff_options.max_word_diff_len = 0;
 8405                diff_options.max_word_diff_line_count = 0;
 8406            } else {
 8407                diff_options.max_word_diff_len = usize::MAX;
 8408                diff_options.max_word_diff_line_count = usize::MAX;
 8409            }
 8410
 8411            for (old_range, new_text) in
 8412                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8413            {
 8414                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8415                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8416                edits.push((edit_start..edit_end, new_text));
 8417            }
 8418
 8419            rewrapped_row_ranges.push(start_row..=end_row);
 8420        }
 8421
 8422        self.buffer
 8423            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8424    }
 8425
 8426    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8427        let mut text = String::new();
 8428        let buffer = self.buffer.read(cx).snapshot(cx);
 8429        let mut selections = self.selections.all::<Point>(cx);
 8430        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8431        {
 8432            let max_point = buffer.max_point();
 8433            let mut is_first = true;
 8434            for selection in &mut selections {
 8435                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8436                if is_entire_line {
 8437                    selection.start = Point::new(selection.start.row, 0);
 8438                    if !selection.is_empty() && selection.end.column == 0 {
 8439                        selection.end = cmp::min(max_point, selection.end);
 8440                    } else {
 8441                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8442                    }
 8443                    selection.goal = SelectionGoal::None;
 8444                }
 8445                if is_first {
 8446                    is_first = false;
 8447                } else {
 8448                    text += "\n";
 8449                }
 8450                let mut len = 0;
 8451                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8452                    text.push_str(chunk);
 8453                    len += chunk.len();
 8454                }
 8455                clipboard_selections.push(ClipboardSelection {
 8456                    len,
 8457                    is_entire_line,
 8458                    start_column: selection.start.column,
 8459                });
 8460            }
 8461        }
 8462
 8463        self.transact(window, cx, |this, window, cx| {
 8464            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8465                s.select(selections);
 8466            });
 8467            this.insert("", window, cx);
 8468        });
 8469        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8470    }
 8471
 8472    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8473        let item = self.cut_common(window, cx);
 8474        cx.write_to_clipboard(item);
 8475    }
 8476
 8477    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8478        self.change_selections(None, window, cx, |s| {
 8479            s.move_with(|snapshot, sel| {
 8480                if sel.is_empty() {
 8481                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8482                }
 8483            });
 8484        });
 8485        let item = self.cut_common(window, cx);
 8486        cx.set_global(KillRing(item))
 8487    }
 8488
 8489    pub fn kill_ring_yank(
 8490        &mut self,
 8491        _: &KillRingYank,
 8492        window: &mut Window,
 8493        cx: &mut Context<Self>,
 8494    ) {
 8495        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8496            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8497                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8498            } else {
 8499                return;
 8500            }
 8501        } else {
 8502            return;
 8503        };
 8504        self.do_paste(&text, metadata, false, window, cx);
 8505    }
 8506
 8507    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8508        let selections = self.selections.all::<Point>(cx);
 8509        let buffer = self.buffer.read(cx).read(cx);
 8510        let mut text = String::new();
 8511
 8512        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8513        {
 8514            let max_point = buffer.max_point();
 8515            let mut is_first = true;
 8516            for selection in selections.iter() {
 8517                let mut start = selection.start;
 8518                let mut end = selection.end;
 8519                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8520                if is_entire_line {
 8521                    start = Point::new(start.row, 0);
 8522                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8523                }
 8524                if is_first {
 8525                    is_first = false;
 8526                } else {
 8527                    text += "\n";
 8528                }
 8529                let mut len = 0;
 8530                for chunk in buffer.text_for_range(start..end) {
 8531                    text.push_str(chunk);
 8532                    len += chunk.len();
 8533                }
 8534                clipboard_selections.push(ClipboardSelection {
 8535                    len,
 8536                    is_entire_line,
 8537                    start_column: start.column,
 8538                });
 8539            }
 8540        }
 8541
 8542        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8543            text,
 8544            clipboard_selections,
 8545        ));
 8546    }
 8547
 8548    pub fn do_paste(
 8549        &mut self,
 8550        text: &String,
 8551        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8552        handle_entire_lines: bool,
 8553        window: &mut Window,
 8554        cx: &mut Context<Self>,
 8555    ) {
 8556        if self.read_only(cx) {
 8557            return;
 8558        }
 8559
 8560        let clipboard_text = Cow::Borrowed(text);
 8561
 8562        self.transact(window, cx, |this, window, cx| {
 8563            if let Some(mut clipboard_selections) = clipboard_selections {
 8564                let old_selections = this.selections.all::<usize>(cx);
 8565                let all_selections_were_entire_line =
 8566                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8567                let first_selection_start_column =
 8568                    clipboard_selections.first().map(|s| s.start_column);
 8569                if clipboard_selections.len() != old_selections.len() {
 8570                    clipboard_selections.drain(..);
 8571                }
 8572                let cursor_offset = this.selections.last::<usize>(cx).head();
 8573                let mut auto_indent_on_paste = true;
 8574
 8575                this.buffer.update(cx, |buffer, cx| {
 8576                    let snapshot = buffer.read(cx);
 8577                    auto_indent_on_paste =
 8578                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8579
 8580                    let mut start_offset = 0;
 8581                    let mut edits = Vec::new();
 8582                    let mut original_start_columns = Vec::new();
 8583                    for (ix, selection) in old_selections.iter().enumerate() {
 8584                        let to_insert;
 8585                        let entire_line;
 8586                        let original_start_column;
 8587                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8588                            let end_offset = start_offset + clipboard_selection.len;
 8589                            to_insert = &clipboard_text[start_offset..end_offset];
 8590                            entire_line = clipboard_selection.is_entire_line;
 8591                            start_offset = end_offset + 1;
 8592                            original_start_column = Some(clipboard_selection.start_column);
 8593                        } else {
 8594                            to_insert = clipboard_text.as_str();
 8595                            entire_line = all_selections_were_entire_line;
 8596                            original_start_column = first_selection_start_column
 8597                        }
 8598
 8599                        // If the corresponding selection was empty when this slice of the
 8600                        // clipboard text was written, then the entire line containing the
 8601                        // selection was copied. If this selection is also currently empty,
 8602                        // then paste the line before the current line of the buffer.
 8603                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8604                            let column = selection.start.to_point(&snapshot).column as usize;
 8605                            let line_start = selection.start - column;
 8606                            line_start..line_start
 8607                        } else {
 8608                            selection.range()
 8609                        };
 8610
 8611                        edits.push((range, to_insert));
 8612                        original_start_columns.extend(original_start_column);
 8613                    }
 8614                    drop(snapshot);
 8615
 8616                    buffer.edit(
 8617                        edits,
 8618                        if auto_indent_on_paste {
 8619                            Some(AutoindentMode::Block {
 8620                                original_start_columns,
 8621                            })
 8622                        } else {
 8623                            None
 8624                        },
 8625                        cx,
 8626                    );
 8627                });
 8628
 8629                let selections = this.selections.all::<usize>(cx);
 8630                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8631                    s.select(selections)
 8632                });
 8633            } else {
 8634                this.insert(&clipboard_text, window, cx);
 8635            }
 8636        });
 8637    }
 8638
 8639    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8640        if let Some(item) = cx.read_from_clipboard() {
 8641            let entries = item.entries();
 8642
 8643            match entries.first() {
 8644                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8645                // of all the pasted entries.
 8646                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8647                    .do_paste(
 8648                        clipboard_string.text(),
 8649                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8650                        true,
 8651                        window,
 8652                        cx,
 8653                    ),
 8654                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8655            }
 8656        }
 8657    }
 8658
 8659    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8660        if self.read_only(cx) {
 8661            return;
 8662        }
 8663
 8664        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8665            if let Some((selections, _)) =
 8666                self.selection_history.transaction(transaction_id).cloned()
 8667            {
 8668                self.change_selections(None, window, cx, |s| {
 8669                    s.select_anchors(selections.to_vec());
 8670                });
 8671            }
 8672            self.request_autoscroll(Autoscroll::fit(), cx);
 8673            self.unmark_text(window, cx);
 8674            self.refresh_inline_completion(true, false, window, cx);
 8675            cx.emit(EditorEvent::Edited { transaction_id });
 8676            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8677        }
 8678    }
 8679
 8680    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8681        if self.read_only(cx) {
 8682            return;
 8683        }
 8684
 8685        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8686            if let Some((_, Some(selections))) =
 8687                self.selection_history.transaction(transaction_id).cloned()
 8688            {
 8689                self.change_selections(None, window, cx, |s| {
 8690                    s.select_anchors(selections.to_vec());
 8691                });
 8692            }
 8693            self.request_autoscroll(Autoscroll::fit(), cx);
 8694            self.unmark_text(window, cx);
 8695            self.refresh_inline_completion(true, false, window, cx);
 8696            cx.emit(EditorEvent::Edited { transaction_id });
 8697        }
 8698    }
 8699
 8700    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8701        self.buffer
 8702            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8703    }
 8704
 8705    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8706        self.buffer
 8707            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8708    }
 8709
 8710    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8711        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8712            let line_mode = s.line_mode;
 8713            s.move_with(|map, selection| {
 8714                let cursor = if selection.is_empty() && !line_mode {
 8715                    movement::left(map, selection.start)
 8716                } else {
 8717                    selection.start
 8718                };
 8719                selection.collapse_to(cursor, SelectionGoal::None);
 8720            });
 8721        })
 8722    }
 8723
 8724    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8725        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8726            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8727        })
 8728    }
 8729
 8730    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8731        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8732            let line_mode = s.line_mode;
 8733            s.move_with(|map, selection| {
 8734                let cursor = if selection.is_empty() && !line_mode {
 8735                    movement::right(map, selection.end)
 8736                } else {
 8737                    selection.end
 8738                };
 8739                selection.collapse_to(cursor, SelectionGoal::None)
 8740            });
 8741        })
 8742    }
 8743
 8744    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8745        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8746            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8747        })
 8748    }
 8749
 8750    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8751        if self.take_rename(true, window, cx).is_some() {
 8752            return;
 8753        }
 8754
 8755        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8756            cx.propagate();
 8757            return;
 8758        }
 8759
 8760        let text_layout_details = &self.text_layout_details(window);
 8761        let selection_count = self.selections.count();
 8762        let first_selection = self.selections.first_anchor();
 8763
 8764        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8765            let line_mode = s.line_mode;
 8766            s.move_with(|map, selection| {
 8767                if !selection.is_empty() && !line_mode {
 8768                    selection.goal = SelectionGoal::None;
 8769                }
 8770                let (cursor, goal) = movement::up(
 8771                    map,
 8772                    selection.start,
 8773                    selection.goal,
 8774                    false,
 8775                    text_layout_details,
 8776                );
 8777                selection.collapse_to(cursor, goal);
 8778            });
 8779        });
 8780
 8781        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8782        {
 8783            cx.propagate();
 8784        }
 8785    }
 8786
 8787    pub fn move_up_by_lines(
 8788        &mut self,
 8789        action: &MoveUpByLines,
 8790        window: &mut Window,
 8791        cx: &mut Context<Self>,
 8792    ) {
 8793        if self.take_rename(true, window, cx).is_some() {
 8794            return;
 8795        }
 8796
 8797        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8798            cx.propagate();
 8799            return;
 8800        }
 8801
 8802        let text_layout_details = &self.text_layout_details(window);
 8803
 8804        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8805            let line_mode = s.line_mode;
 8806            s.move_with(|map, selection| {
 8807                if !selection.is_empty() && !line_mode {
 8808                    selection.goal = SelectionGoal::None;
 8809                }
 8810                let (cursor, goal) = movement::up_by_rows(
 8811                    map,
 8812                    selection.start,
 8813                    action.lines,
 8814                    selection.goal,
 8815                    false,
 8816                    text_layout_details,
 8817                );
 8818                selection.collapse_to(cursor, goal);
 8819            });
 8820        })
 8821    }
 8822
 8823    pub fn move_down_by_lines(
 8824        &mut self,
 8825        action: &MoveDownByLines,
 8826        window: &mut Window,
 8827        cx: &mut Context<Self>,
 8828    ) {
 8829        if self.take_rename(true, window, cx).is_some() {
 8830            return;
 8831        }
 8832
 8833        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8834            cx.propagate();
 8835            return;
 8836        }
 8837
 8838        let text_layout_details = &self.text_layout_details(window);
 8839
 8840        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8841            let line_mode = s.line_mode;
 8842            s.move_with(|map, selection| {
 8843                if !selection.is_empty() && !line_mode {
 8844                    selection.goal = SelectionGoal::None;
 8845                }
 8846                let (cursor, goal) = movement::down_by_rows(
 8847                    map,
 8848                    selection.start,
 8849                    action.lines,
 8850                    selection.goal,
 8851                    false,
 8852                    text_layout_details,
 8853                );
 8854                selection.collapse_to(cursor, goal);
 8855            });
 8856        })
 8857    }
 8858
 8859    pub fn select_down_by_lines(
 8860        &mut self,
 8861        action: &SelectDownByLines,
 8862        window: &mut Window,
 8863        cx: &mut Context<Self>,
 8864    ) {
 8865        let text_layout_details = &self.text_layout_details(window);
 8866        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8867            s.move_heads_with(|map, head, goal| {
 8868                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8869            })
 8870        })
 8871    }
 8872
 8873    pub fn select_up_by_lines(
 8874        &mut self,
 8875        action: &SelectUpByLines,
 8876        window: &mut Window,
 8877        cx: &mut Context<Self>,
 8878    ) {
 8879        let text_layout_details = &self.text_layout_details(window);
 8880        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8881            s.move_heads_with(|map, head, goal| {
 8882                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8883            })
 8884        })
 8885    }
 8886
 8887    pub fn select_page_up(
 8888        &mut self,
 8889        _: &SelectPageUp,
 8890        window: &mut Window,
 8891        cx: &mut Context<Self>,
 8892    ) {
 8893        let Some(row_count) = self.visible_row_count() else {
 8894            return;
 8895        };
 8896
 8897        let text_layout_details = &self.text_layout_details(window);
 8898
 8899        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8900            s.move_heads_with(|map, head, goal| {
 8901                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8902            })
 8903        })
 8904    }
 8905
 8906    pub fn move_page_up(
 8907        &mut self,
 8908        action: &MovePageUp,
 8909        window: &mut Window,
 8910        cx: &mut Context<Self>,
 8911    ) {
 8912        if self.take_rename(true, window, cx).is_some() {
 8913            return;
 8914        }
 8915
 8916        if self
 8917            .context_menu
 8918            .borrow_mut()
 8919            .as_mut()
 8920            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8921            .unwrap_or(false)
 8922        {
 8923            return;
 8924        }
 8925
 8926        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8927            cx.propagate();
 8928            return;
 8929        }
 8930
 8931        let Some(row_count) = self.visible_row_count() else {
 8932            return;
 8933        };
 8934
 8935        let autoscroll = if action.center_cursor {
 8936            Autoscroll::center()
 8937        } else {
 8938            Autoscroll::fit()
 8939        };
 8940
 8941        let text_layout_details = &self.text_layout_details(window);
 8942
 8943        self.change_selections(Some(autoscroll), window, cx, |s| {
 8944            let line_mode = s.line_mode;
 8945            s.move_with(|map, selection| {
 8946                if !selection.is_empty() && !line_mode {
 8947                    selection.goal = SelectionGoal::None;
 8948                }
 8949                let (cursor, goal) = movement::up_by_rows(
 8950                    map,
 8951                    selection.end,
 8952                    row_count,
 8953                    selection.goal,
 8954                    false,
 8955                    text_layout_details,
 8956                );
 8957                selection.collapse_to(cursor, goal);
 8958            });
 8959        });
 8960    }
 8961
 8962    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8963        let text_layout_details = &self.text_layout_details(window);
 8964        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8965            s.move_heads_with(|map, head, goal| {
 8966                movement::up(map, head, goal, false, text_layout_details)
 8967            })
 8968        })
 8969    }
 8970
 8971    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8972        self.take_rename(true, window, cx);
 8973
 8974        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8975            cx.propagate();
 8976            return;
 8977        }
 8978
 8979        let text_layout_details = &self.text_layout_details(window);
 8980        let selection_count = self.selections.count();
 8981        let first_selection = self.selections.first_anchor();
 8982
 8983        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8984            let line_mode = s.line_mode;
 8985            s.move_with(|map, selection| {
 8986                if !selection.is_empty() && !line_mode {
 8987                    selection.goal = SelectionGoal::None;
 8988                }
 8989                let (cursor, goal) = movement::down(
 8990                    map,
 8991                    selection.end,
 8992                    selection.goal,
 8993                    false,
 8994                    text_layout_details,
 8995                );
 8996                selection.collapse_to(cursor, goal);
 8997            });
 8998        });
 8999
 9000        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9001        {
 9002            cx.propagate();
 9003        }
 9004    }
 9005
 9006    pub fn select_page_down(
 9007        &mut self,
 9008        _: &SelectPageDown,
 9009        window: &mut Window,
 9010        cx: &mut Context<Self>,
 9011    ) {
 9012        let Some(row_count) = self.visible_row_count() else {
 9013            return;
 9014        };
 9015
 9016        let text_layout_details = &self.text_layout_details(window);
 9017
 9018        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9019            s.move_heads_with(|map, head, goal| {
 9020                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9021            })
 9022        })
 9023    }
 9024
 9025    pub fn move_page_down(
 9026        &mut self,
 9027        action: &MovePageDown,
 9028        window: &mut Window,
 9029        cx: &mut Context<Self>,
 9030    ) {
 9031        if self.take_rename(true, window, cx).is_some() {
 9032            return;
 9033        }
 9034
 9035        if self
 9036            .context_menu
 9037            .borrow_mut()
 9038            .as_mut()
 9039            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9040            .unwrap_or(false)
 9041        {
 9042            return;
 9043        }
 9044
 9045        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9046            cx.propagate();
 9047            return;
 9048        }
 9049
 9050        let Some(row_count) = self.visible_row_count() else {
 9051            return;
 9052        };
 9053
 9054        let autoscroll = if action.center_cursor {
 9055            Autoscroll::center()
 9056        } else {
 9057            Autoscroll::fit()
 9058        };
 9059
 9060        let text_layout_details = &self.text_layout_details(window);
 9061        self.change_selections(Some(autoscroll), window, cx, |s| {
 9062            let line_mode = s.line_mode;
 9063            s.move_with(|map, selection| {
 9064                if !selection.is_empty() && !line_mode {
 9065                    selection.goal = SelectionGoal::None;
 9066                }
 9067                let (cursor, goal) = movement::down_by_rows(
 9068                    map,
 9069                    selection.end,
 9070                    row_count,
 9071                    selection.goal,
 9072                    false,
 9073                    text_layout_details,
 9074                );
 9075                selection.collapse_to(cursor, goal);
 9076            });
 9077        });
 9078    }
 9079
 9080    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9081        let text_layout_details = &self.text_layout_details(window);
 9082        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9083            s.move_heads_with(|map, head, goal| {
 9084                movement::down(map, head, goal, false, text_layout_details)
 9085            })
 9086        });
 9087    }
 9088
 9089    pub fn context_menu_first(
 9090        &mut self,
 9091        _: &ContextMenuFirst,
 9092        _window: &mut Window,
 9093        cx: &mut Context<Self>,
 9094    ) {
 9095        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9096            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9097        }
 9098    }
 9099
 9100    pub fn context_menu_prev(
 9101        &mut self,
 9102        _: &ContextMenuPrev,
 9103        _window: &mut Window,
 9104        cx: &mut Context<Self>,
 9105    ) {
 9106        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9107            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9108        }
 9109    }
 9110
 9111    pub fn context_menu_next(
 9112        &mut self,
 9113        _: &ContextMenuNext,
 9114        _window: &mut Window,
 9115        cx: &mut Context<Self>,
 9116    ) {
 9117        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9118            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9119        }
 9120    }
 9121
 9122    pub fn context_menu_last(
 9123        &mut self,
 9124        _: &ContextMenuLast,
 9125        _window: &mut Window,
 9126        cx: &mut Context<Self>,
 9127    ) {
 9128        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9129            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9130        }
 9131    }
 9132
 9133    pub fn move_to_previous_word_start(
 9134        &mut self,
 9135        _: &MoveToPreviousWordStart,
 9136        window: &mut Window,
 9137        cx: &mut Context<Self>,
 9138    ) {
 9139        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9140            s.move_cursors_with(|map, head, _| {
 9141                (
 9142                    movement::previous_word_start(map, head),
 9143                    SelectionGoal::None,
 9144                )
 9145            });
 9146        })
 9147    }
 9148
 9149    pub fn move_to_previous_subword_start(
 9150        &mut self,
 9151        _: &MoveToPreviousSubwordStart,
 9152        window: &mut Window,
 9153        cx: &mut Context<Self>,
 9154    ) {
 9155        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9156            s.move_cursors_with(|map, head, _| {
 9157                (
 9158                    movement::previous_subword_start(map, head),
 9159                    SelectionGoal::None,
 9160                )
 9161            });
 9162        })
 9163    }
 9164
 9165    pub fn select_to_previous_word_start(
 9166        &mut self,
 9167        _: &SelectToPreviousWordStart,
 9168        window: &mut Window,
 9169        cx: &mut Context<Self>,
 9170    ) {
 9171        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9172            s.move_heads_with(|map, head, _| {
 9173                (
 9174                    movement::previous_word_start(map, head),
 9175                    SelectionGoal::None,
 9176                )
 9177            });
 9178        })
 9179    }
 9180
 9181    pub fn select_to_previous_subword_start(
 9182        &mut self,
 9183        _: &SelectToPreviousSubwordStart,
 9184        window: &mut Window,
 9185        cx: &mut Context<Self>,
 9186    ) {
 9187        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9188            s.move_heads_with(|map, head, _| {
 9189                (
 9190                    movement::previous_subword_start(map, head),
 9191                    SelectionGoal::None,
 9192                )
 9193            });
 9194        })
 9195    }
 9196
 9197    pub fn delete_to_previous_word_start(
 9198        &mut self,
 9199        action: &DeleteToPreviousWordStart,
 9200        window: &mut Window,
 9201        cx: &mut Context<Self>,
 9202    ) {
 9203        self.transact(window, cx, |this, window, cx| {
 9204            this.select_autoclose_pair(window, cx);
 9205            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9206                let line_mode = s.line_mode;
 9207                s.move_with(|map, selection| {
 9208                    if selection.is_empty() && !line_mode {
 9209                        let cursor = if action.ignore_newlines {
 9210                            movement::previous_word_start(map, selection.head())
 9211                        } else {
 9212                            movement::previous_word_start_or_newline(map, selection.head())
 9213                        };
 9214                        selection.set_head(cursor, SelectionGoal::None);
 9215                    }
 9216                });
 9217            });
 9218            this.insert("", window, cx);
 9219        });
 9220    }
 9221
 9222    pub fn delete_to_previous_subword_start(
 9223        &mut self,
 9224        _: &DeleteToPreviousSubwordStart,
 9225        window: &mut Window,
 9226        cx: &mut Context<Self>,
 9227    ) {
 9228        self.transact(window, cx, |this, window, cx| {
 9229            this.select_autoclose_pair(window, cx);
 9230            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9231                let line_mode = s.line_mode;
 9232                s.move_with(|map, selection| {
 9233                    if selection.is_empty() && !line_mode {
 9234                        let cursor = movement::previous_subword_start(map, selection.head());
 9235                        selection.set_head(cursor, SelectionGoal::None);
 9236                    }
 9237                });
 9238            });
 9239            this.insert("", window, cx);
 9240        });
 9241    }
 9242
 9243    pub fn move_to_next_word_end(
 9244        &mut self,
 9245        _: &MoveToNextWordEnd,
 9246        window: &mut Window,
 9247        cx: &mut Context<Self>,
 9248    ) {
 9249        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9250            s.move_cursors_with(|map, head, _| {
 9251                (movement::next_word_end(map, head), SelectionGoal::None)
 9252            });
 9253        })
 9254    }
 9255
 9256    pub fn move_to_next_subword_end(
 9257        &mut self,
 9258        _: &MoveToNextSubwordEnd,
 9259        window: &mut Window,
 9260        cx: &mut Context<Self>,
 9261    ) {
 9262        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9263            s.move_cursors_with(|map, head, _| {
 9264                (movement::next_subword_end(map, head), SelectionGoal::None)
 9265            });
 9266        })
 9267    }
 9268
 9269    pub fn select_to_next_word_end(
 9270        &mut self,
 9271        _: &SelectToNextWordEnd,
 9272        window: &mut Window,
 9273        cx: &mut Context<Self>,
 9274    ) {
 9275        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9276            s.move_heads_with(|map, head, _| {
 9277                (movement::next_word_end(map, head), SelectionGoal::None)
 9278            });
 9279        })
 9280    }
 9281
 9282    pub fn select_to_next_subword_end(
 9283        &mut self,
 9284        _: &SelectToNextSubwordEnd,
 9285        window: &mut Window,
 9286        cx: &mut Context<Self>,
 9287    ) {
 9288        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9289            s.move_heads_with(|map, head, _| {
 9290                (movement::next_subword_end(map, head), SelectionGoal::None)
 9291            });
 9292        })
 9293    }
 9294
 9295    pub fn delete_to_next_word_end(
 9296        &mut self,
 9297        action: &DeleteToNextWordEnd,
 9298        window: &mut Window,
 9299        cx: &mut Context<Self>,
 9300    ) {
 9301        self.transact(window, cx, |this, window, cx| {
 9302            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9303                let line_mode = s.line_mode;
 9304                s.move_with(|map, selection| {
 9305                    if selection.is_empty() && !line_mode {
 9306                        let cursor = if action.ignore_newlines {
 9307                            movement::next_word_end(map, selection.head())
 9308                        } else {
 9309                            movement::next_word_end_or_newline(map, selection.head())
 9310                        };
 9311                        selection.set_head(cursor, SelectionGoal::None);
 9312                    }
 9313                });
 9314            });
 9315            this.insert("", window, cx);
 9316        });
 9317    }
 9318
 9319    pub fn delete_to_next_subword_end(
 9320        &mut self,
 9321        _: &DeleteToNextSubwordEnd,
 9322        window: &mut Window,
 9323        cx: &mut Context<Self>,
 9324    ) {
 9325        self.transact(window, cx, |this, window, cx| {
 9326            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9327                s.move_with(|map, selection| {
 9328                    if selection.is_empty() {
 9329                        let cursor = movement::next_subword_end(map, selection.head());
 9330                        selection.set_head(cursor, SelectionGoal::None);
 9331                    }
 9332                });
 9333            });
 9334            this.insert("", window, cx);
 9335        });
 9336    }
 9337
 9338    pub fn move_to_beginning_of_line(
 9339        &mut self,
 9340        action: &MoveToBeginningOfLine,
 9341        window: &mut Window,
 9342        cx: &mut Context<Self>,
 9343    ) {
 9344        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9345            s.move_cursors_with(|map, head, _| {
 9346                (
 9347                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 9348                    SelectionGoal::None,
 9349                )
 9350            });
 9351        })
 9352    }
 9353
 9354    pub fn select_to_beginning_of_line(
 9355        &mut self,
 9356        action: &SelectToBeginningOfLine,
 9357        window: &mut Window,
 9358        cx: &mut Context<Self>,
 9359    ) {
 9360        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9361            s.move_heads_with(|map, head, _| {
 9362                (
 9363                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 9364                    SelectionGoal::None,
 9365                )
 9366            });
 9367        });
 9368    }
 9369
 9370    pub fn delete_to_beginning_of_line(
 9371        &mut self,
 9372        _: &DeleteToBeginningOfLine,
 9373        window: &mut Window,
 9374        cx: &mut Context<Self>,
 9375    ) {
 9376        self.transact(window, cx, |this, window, cx| {
 9377            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9378                s.move_with(|_, selection| {
 9379                    selection.reversed = true;
 9380                });
 9381            });
 9382
 9383            this.select_to_beginning_of_line(
 9384                &SelectToBeginningOfLine {
 9385                    stop_at_soft_wraps: false,
 9386                },
 9387                window,
 9388                cx,
 9389            );
 9390            this.backspace(&Backspace, window, cx);
 9391        });
 9392    }
 9393
 9394    pub fn move_to_end_of_line(
 9395        &mut self,
 9396        action: &MoveToEndOfLine,
 9397        window: &mut Window,
 9398        cx: &mut Context<Self>,
 9399    ) {
 9400        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9401            s.move_cursors_with(|map, head, _| {
 9402                (
 9403                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9404                    SelectionGoal::None,
 9405                )
 9406            });
 9407        })
 9408    }
 9409
 9410    pub fn select_to_end_of_line(
 9411        &mut self,
 9412        action: &SelectToEndOfLine,
 9413        window: &mut Window,
 9414        cx: &mut Context<Self>,
 9415    ) {
 9416        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9417            s.move_heads_with(|map, head, _| {
 9418                (
 9419                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9420                    SelectionGoal::None,
 9421                )
 9422            });
 9423        })
 9424    }
 9425
 9426    pub fn delete_to_end_of_line(
 9427        &mut self,
 9428        _: &DeleteToEndOfLine,
 9429        window: &mut Window,
 9430        cx: &mut Context<Self>,
 9431    ) {
 9432        self.transact(window, cx, |this, window, cx| {
 9433            this.select_to_end_of_line(
 9434                &SelectToEndOfLine {
 9435                    stop_at_soft_wraps: false,
 9436                },
 9437                window,
 9438                cx,
 9439            );
 9440            this.delete(&Delete, window, cx);
 9441        });
 9442    }
 9443
 9444    pub fn cut_to_end_of_line(
 9445        &mut self,
 9446        _: &CutToEndOfLine,
 9447        window: &mut Window,
 9448        cx: &mut Context<Self>,
 9449    ) {
 9450        self.transact(window, cx, |this, window, cx| {
 9451            this.select_to_end_of_line(
 9452                &SelectToEndOfLine {
 9453                    stop_at_soft_wraps: false,
 9454                },
 9455                window,
 9456                cx,
 9457            );
 9458            this.cut(&Cut, window, cx);
 9459        });
 9460    }
 9461
 9462    pub fn move_to_start_of_paragraph(
 9463        &mut self,
 9464        _: &MoveToStartOfParagraph,
 9465        window: &mut Window,
 9466        cx: &mut Context<Self>,
 9467    ) {
 9468        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9469            cx.propagate();
 9470            return;
 9471        }
 9472
 9473        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9474            s.move_with(|map, selection| {
 9475                selection.collapse_to(
 9476                    movement::start_of_paragraph(map, selection.head(), 1),
 9477                    SelectionGoal::None,
 9478                )
 9479            });
 9480        })
 9481    }
 9482
 9483    pub fn move_to_end_of_paragraph(
 9484        &mut self,
 9485        _: &MoveToEndOfParagraph,
 9486        window: &mut Window,
 9487        cx: &mut Context<Self>,
 9488    ) {
 9489        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9490            cx.propagate();
 9491            return;
 9492        }
 9493
 9494        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9495            s.move_with(|map, selection| {
 9496                selection.collapse_to(
 9497                    movement::end_of_paragraph(map, selection.head(), 1),
 9498                    SelectionGoal::None,
 9499                )
 9500            });
 9501        })
 9502    }
 9503
 9504    pub fn select_to_start_of_paragraph(
 9505        &mut self,
 9506        _: &SelectToStartOfParagraph,
 9507        window: &mut Window,
 9508        cx: &mut Context<Self>,
 9509    ) {
 9510        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9511            cx.propagate();
 9512            return;
 9513        }
 9514
 9515        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9516            s.move_heads_with(|map, head, _| {
 9517                (
 9518                    movement::start_of_paragraph(map, head, 1),
 9519                    SelectionGoal::None,
 9520                )
 9521            });
 9522        })
 9523    }
 9524
 9525    pub fn select_to_end_of_paragraph(
 9526        &mut self,
 9527        _: &SelectToEndOfParagraph,
 9528        window: &mut Window,
 9529        cx: &mut Context<Self>,
 9530    ) {
 9531        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9532            cx.propagate();
 9533            return;
 9534        }
 9535
 9536        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9537            s.move_heads_with(|map, head, _| {
 9538                (
 9539                    movement::end_of_paragraph(map, head, 1),
 9540                    SelectionGoal::None,
 9541                )
 9542            });
 9543        })
 9544    }
 9545
 9546    pub fn move_to_start_of_excerpt(
 9547        &mut self,
 9548        _: &MoveToStartOfExcerpt,
 9549        window: &mut Window,
 9550        cx: &mut Context<Self>,
 9551    ) {
 9552        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9553            cx.propagate();
 9554            return;
 9555        }
 9556
 9557        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9558            s.move_with(|map, selection| {
 9559                selection.collapse_to(
 9560                    movement::start_of_excerpt(
 9561                        map,
 9562                        selection.head(),
 9563                        workspace::searchable::Direction::Prev,
 9564                    ),
 9565                    SelectionGoal::None,
 9566                )
 9567            });
 9568        })
 9569    }
 9570
 9571    pub fn move_to_end_of_excerpt(
 9572        &mut self,
 9573        _: &MoveToEndOfExcerpt,
 9574        window: &mut Window,
 9575        cx: &mut Context<Self>,
 9576    ) {
 9577        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9578            cx.propagate();
 9579            return;
 9580        }
 9581
 9582        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9583            s.move_with(|map, selection| {
 9584                selection.collapse_to(
 9585                    movement::end_of_excerpt(
 9586                        map,
 9587                        selection.head(),
 9588                        workspace::searchable::Direction::Next,
 9589                    ),
 9590                    SelectionGoal::None,
 9591                )
 9592            });
 9593        })
 9594    }
 9595
 9596    pub fn select_to_start_of_excerpt(
 9597        &mut self,
 9598        _: &SelectToStartOfExcerpt,
 9599        window: &mut Window,
 9600        cx: &mut Context<Self>,
 9601    ) {
 9602        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9603            cx.propagate();
 9604            return;
 9605        }
 9606
 9607        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9608            s.move_heads_with(|map, head, _| {
 9609                (
 9610                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9611                    SelectionGoal::None,
 9612                )
 9613            });
 9614        })
 9615    }
 9616
 9617    pub fn select_to_end_of_excerpt(
 9618        &mut self,
 9619        _: &SelectToEndOfExcerpt,
 9620        window: &mut Window,
 9621        cx: &mut Context<Self>,
 9622    ) {
 9623        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9624            cx.propagate();
 9625            return;
 9626        }
 9627
 9628        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9629            s.move_heads_with(|map, head, _| {
 9630                (
 9631                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9632                    SelectionGoal::None,
 9633                )
 9634            });
 9635        })
 9636    }
 9637
 9638    pub fn move_to_beginning(
 9639        &mut self,
 9640        _: &MoveToBeginning,
 9641        window: &mut Window,
 9642        cx: &mut Context<Self>,
 9643    ) {
 9644        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9645            cx.propagate();
 9646            return;
 9647        }
 9648
 9649        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9650            s.select_ranges(vec![0..0]);
 9651        });
 9652    }
 9653
 9654    pub fn select_to_beginning(
 9655        &mut self,
 9656        _: &SelectToBeginning,
 9657        window: &mut Window,
 9658        cx: &mut Context<Self>,
 9659    ) {
 9660        let mut selection = self.selections.last::<Point>(cx);
 9661        selection.set_head(Point::zero(), SelectionGoal::None);
 9662
 9663        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9664            s.select(vec![selection]);
 9665        });
 9666    }
 9667
 9668    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9669        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9670            cx.propagate();
 9671            return;
 9672        }
 9673
 9674        let cursor = self.buffer.read(cx).read(cx).len();
 9675        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9676            s.select_ranges(vec![cursor..cursor])
 9677        });
 9678    }
 9679
 9680    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9681        self.nav_history = nav_history;
 9682    }
 9683
 9684    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9685        self.nav_history.as_ref()
 9686    }
 9687
 9688    fn push_to_nav_history(
 9689        &mut self,
 9690        cursor_anchor: Anchor,
 9691        new_position: Option<Point>,
 9692        cx: &mut Context<Self>,
 9693    ) {
 9694        if let Some(nav_history) = self.nav_history.as_mut() {
 9695            let buffer = self.buffer.read(cx).read(cx);
 9696            let cursor_position = cursor_anchor.to_point(&buffer);
 9697            let scroll_state = self.scroll_manager.anchor();
 9698            let scroll_top_row = scroll_state.top_row(&buffer);
 9699            drop(buffer);
 9700
 9701            if let Some(new_position) = new_position {
 9702                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9703                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9704                    return;
 9705                }
 9706            }
 9707
 9708            nav_history.push(
 9709                Some(NavigationData {
 9710                    cursor_anchor,
 9711                    cursor_position,
 9712                    scroll_anchor: scroll_state,
 9713                    scroll_top_row,
 9714                }),
 9715                cx,
 9716            );
 9717        }
 9718    }
 9719
 9720    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9721        let buffer = self.buffer.read(cx).snapshot(cx);
 9722        let mut selection = self.selections.first::<usize>(cx);
 9723        selection.set_head(buffer.len(), SelectionGoal::None);
 9724        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9725            s.select(vec![selection]);
 9726        });
 9727    }
 9728
 9729    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9730        let end = self.buffer.read(cx).read(cx).len();
 9731        self.change_selections(None, window, cx, |s| {
 9732            s.select_ranges(vec![0..end]);
 9733        });
 9734    }
 9735
 9736    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9737        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9738        let mut selections = self.selections.all::<Point>(cx);
 9739        let max_point = display_map.buffer_snapshot.max_point();
 9740        for selection in &mut selections {
 9741            let rows = selection.spanned_rows(true, &display_map);
 9742            selection.start = Point::new(rows.start.0, 0);
 9743            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9744            selection.reversed = false;
 9745        }
 9746        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9747            s.select(selections);
 9748        });
 9749    }
 9750
 9751    pub fn split_selection_into_lines(
 9752        &mut self,
 9753        _: &SplitSelectionIntoLines,
 9754        window: &mut Window,
 9755        cx: &mut Context<Self>,
 9756    ) {
 9757        let selections = self
 9758            .selections
 9759            .all::<Point>(cx)
 9760            .into_iter()
 9761            .map(|selection| selection.start..selection.end)
 9762            .collect::<Vec<_>>();
 9763        self.unfold_ranges(&selections, true, true, cx);
 9764
 9765        let mut new_selection_ranges = Vec::new();
 9766        {
 9767            let buffer = self.buffer.read(cx).read(cx);
 9768            for selection in selections {
 9769                for row in selection.start.row..selection.end.row {
 9770                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9771                    new_selection_ranges.push(cursor..cursor);
 9772                }
 9773
 9774                let is_multiline_selection = selection.start.row != selection.end.row;
 9775                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9776                // so this action feels more ergonomic when paired with other selection operations
 9777                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9778                if !should_skip_last {
 9779                    new_selection_ranges.push(selection.end..selection.end);
 9780                }
 9781            }
 9782        }
 9783        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9784            s.select_ranges(new_selection_ranges);
 9785        });
 9786    }
 9787
 9788    pub fn add_selection_above(
 9789        &mut self,
 9790        _: &AddSelectionAbove,
 9791        window: &mut Window,
 9792        cx: &mut Context<Self>,
 9793    ) {
 9794        self.add_selection(true, window, cx);
 9795    }
 9796
 9797    pub fn add_selection_below(
 9798        &mut self,
 9799        _: &AddSelectionBelow,
 9800        window: &mut Window,
 9801        cx: &mut Context<Self>,
 9802    ) {
 9803        self.add_selection(false, window, cx);
 9804    }
 9805
 9806    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9807        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9808        let mut selections = self.selections.all::<Point>(cx);
 9809        let text_layout_details = self.text_layout_details(window);
 9810        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9811            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9812            let range = oldest_selection.display_range(&display_map).sorted();
 9813
 9814            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9815            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9816            let positions = start_x.min(end_x)..start_x.max(end_x);
 9817
 9818            selections.clear();
 9819            let mut stack = Vec::new();
 9820            for row in range.start.row().0..=range.end.row().0 {
 9821                if let Some(selection) = self.selections.build_columnar_selection(
 9822                    &display_map,
 9823                    DisplayRow(row),
 9824                    &positions,
 9825                    oldest_selection.reversed,
 9826                    &text_layout_details,
 9827                ) {
 9828                    stack.push(selection.id);
 9829                    selections.push(selection);
 9830                }
 9831            }
 9832
 9833            if above {
 9834                stack.reverse();
 9835            }
 9836
 9837            AddSelectionsState { above, stack }
 9838        });
 9839
 9840        let last_added_selection = *state.stack.last().unwrap();
 9841        let mut new_selections = Vec::new();
 9842        if above == state.above {
 9843            let end_row = if above {
 9844                DisplayRow(0)
 9845            } else {
 9846                display_map.max_point().row()
 9847            };
 9848
 9849            'outer: for selection in selections {
 9850                if selection.id == last_added_selection {
 9851                    let range = selection.display_range(&display_map).sorted();
 9852                    debug_assert_eq!(range.start.row(), range.end.row());
 9853                    let mut row = range.start.row();
 9854                    let positions =
 9855                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9856                            px(start)..px(end)
 9857                        } else {
 9858                            let start_x =
 9859                                display_map.x_for_display_point(range.start, &text_layout_details);
 9860                            let end_x =
 9861                                display_map.x_for_display_point(range.end, &text_layout_details);
 9862                            start_x.min(end_x)..start_x.max(end_x)
 9863                        };
 9864
 9865                    while row != end_row {
 9866                        if above {
 9867                            row.0 -= 1;
 9868                        } else {
 9869                            row.0 += 1;
 9870                        }
 9871
 9872                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9873                            &display_map,
 9874                            row,
 9875                            &positions,
 9876                            selection.reversed,
 9877                            &text_layout_details,
 9878                        ) {
 9879                            state.stack.push(new_selection.id);
 9880                            if above {
 9881                                new_selections.push(new_selection);
 9882                                new_selections.push(selection);
 9883                            } else {
 9884                                new_selections.push(selection);
 9885                                new_selections.push(new_selection);
 9886                            }
 9887
 9888                            continue 'outer;
 9889                        }
 9890                    }
 9891                }
 9892
 9893                new_selections.push(selection);
 9894            }
 9895        } else {
 9896            new_selections = selections;
 9897            new_selections.retain(|s| s.id != last_added_selection);
 9898            state.stack.pop();
 9899        }
 9900
 9901        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9902            s.select(new_selections);
 9903        });
 9904        if state.stack.len() > 1 {
 9905            self.add_selections_state = Some(state);
 9906        }
 9907    }
 9908
 9909    pub fn select_next_match_internal(
 9910        &mut self,
 9911        display_map: &DisplaySnapshot,
 9912        replace_newest: bool,
 9913        autoscroll: Option<Autoscroll>,
 9914        window: &mut Window,
 9915        cx: &mut Context<Self>,
 9916    ) -> Result<()> {
 9917        fn select_next_match_ranges(
 9918            this: &mut Editor,
 9919            range: Range<usize>,
 9920            replace_newest: bool,
 9921            auto_scroll: Option<Autoscroll>,
 9922            window: &mut Window,
 9923            cx: &mut Context<Editor>,
 9924        ) {
 9925            this.unfold_ranges(&[range.clone()], false, true, cx);
 9926            this.change_selections(auto_scroll, window, cx, |s| {
 9927                if replace_newest {
 9928                    s.delete(s.newest_anchor().id);
 9929                }
 9930                s.insert_range(range.clone());
 9931            });
 9932        }
 9933
 9934        let buffer = &display_map.buffer_snapshot;
 9935        let mut selections = self.selections.all::<usize>(cx);
 9936        if let Some(mut select_next_state) = self.select_next_state.take() {
 9937            let query = &select_next_state.query;
 9938            if !select_next_state.done {
 9939                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9940                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9941                let mut next_selected_range = None;
 9942
 9943                let bytes_after_last_selection =
 9944                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9945                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9946                let query_matches = query
 9947                    .stream_find_iter(bytes_after_last_selection)
 9948                    .map(|result| (last_selection.end, result))
 9949                    .chain(
 9950                        query
 9951                            .stream_find_iter(bytes_before_first_selection)
 9952                            .map(|result| (0, result)),
 9953                    );
 9954
 9955                for (start_offset, query_match) in query_matches {
 9956                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9957                    let offset_range =
 9958                        start_offset + query_match.start()..start_offset + query_match.end();
 9959                    let display_range = offset_range.start.to_display_point(display_map)
 9960                        ..offset_range.end.to_display_point(display_map);
 9961
 9962                    if !select_next_state.wordwise
 9963                        || (!movement::is_inside_word(display_map, display_range.start)
 9964                            && !movement::is_inside_word(display_map, display_range.end))
 9965                    {
 9966                        // TODO: This is n^2, because we might check all the selections
 9967                        if !selections
 9968                            .iter()
 9969                            .any(|selection| selection.range().overlaps(&offset_range))
 9970                        {
 9971                            next_selected_range = Some(offset_range);
 9972                            break;
 9973                        }
 9974                    }
 9975                }
 9976
 9977                if let Some(next_selected_range) = next_selected_range {
 9978                    select_next_match_ranges(
 9979                        self,
 9980                        next_selected_range,
 9981                        replace_newest,
 9982                        autoscroll,
 9983                        window,
 9984                        cx,
 9985                    );
 9986                } else {
 9987                    select_next_state.done = true;
 9988                }
 9989            }
 9990
 9991            self.select_next_state = Some(select_next_state);
 9992        } else {
 9993            let mut only_carets = true;
 9994            let mut same_text_selected = true;
 9995            let mut selected_text = None;
 9996
 9997            let mut selections_iter = selections.iter().peekable();
 9998            while let Some(selection) = selections_iter.next() {
 9999                if selection.start != selection.end {
10000                    only_carets = false;
10001                }
10002
10003                if same_text_selected {
10004                    if selected_text.is_none() {
10005                        selected_text =
10006                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10007                    }
10008
10009                    if let Some(next_selection) = selections_iter.peek() {
10010                        if next_selection.range().len() == selection.range().len() {
10011                            let next_selected_text = buffer
10012                                .text_for_range(next_selection.range())
10013                                .collect::<String>();
10014                            if Some(next_selected_text) != selected_text {
10015                                same_text_selected = false;
10016                                selected_text = None;
10017                            }
10018                        } else {
10019                            same_text_selected = false;
10020                            selected_text = None;
10021                        }
10022                    }
10023                }
10024            }
10025
10026            if only_carets {
10027                for selection in &mut selections {
10028                    let word_range = movement::surrounding_word(
10029                        display_map,
10030                        selection.start.to_display_point(display_map),
10031                    );
10032                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10033                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10034                    selection.goal = SelectionGoal::None;
10035                    selection.reversed = false;
10036                    select_next_match_ranges(
10037                        self,
10038                        selection.start..selection.end,
10039                        replace_newest,
10040                        autoscroll,
10041                        window,
10042                        cx,
10043                    );
10044                }
10045
10046                if selections.len() == 1 {
10047                    let selection = selections
10048                        .last()
10049                        .expect("ensured that there's only one selection");
10050                    let query = buffer
10051                        .text_for_range(selection.start..selection.end)
10052                        .collect::<String>();
10053                    let is_empty = query.is_empty();
10054                    let select_state = SelectNextState {
10055                        query: AhoCorasick::new(&[query])?,
10056                        wordwise: true,
10057                        done: is_empty,
10058                    };
10059                    self.select_next_state = Some(select_state);
10060                } else {
10061                    self.select_next_state = None;
10062                }
10063            } else if let Some(selected_text) = selected_text {
10064                self.select_next_state = Some(SelectNextState {
10065                    query: AhoCorasick::new(&[selected_text])?,
10066                    wordwise: false,
10067                    done: false,
10068                });
10069                self.select_next_match_internal(
10070                    display_map,
10071                    replace_newest,
10072                    autoscroll,
10073                    window,
10074                    cx,
10075                )?;
10076            }
10077        }
10078        Ok(())
10079    }
10080
10081    pub fn select_all_matches(
10082        &mut self,
10083        _action: &SelectAllMatches,
10084        window: &mut Window,
10085        cx: &mut Context<Self>,
10086    ) -> Result<()> {
10087        self.push_to_selection_history();
10088        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10089
10090        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10091        let Some(select_next_state) = self.select_next_state.as_mut() else {
10092            return Ok(());
10093        };
10094        if select_next_state.done {
10095            return Ok(());
10096        }
10097
10098        let mut new_selections = self.selections.all::<usize>(cx);
10099
10100        let buffer = &display_map.buffer_snapshot;
10101        let query_matches = select_next_state
10102            .query
10103            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10104
10105        for query_match in query_matches {
10106            let query_match = query_match.unwrap(); // can only fail due to I/O
10107            let offset_range = query_match.start()..query_match.end();
10108            let display_range = offset_range.start.to_display_point(&display_map)
10109                ..offset_range.end.to_display_point(&display_map);
10110
10111            if !select_next_state.wordwise
10112                || (!movement::is_inside_word(&display_map, display_range.start)
10113                    && !movement::is_inside_word(&display_map, display_range.end))
10114            {
10115                self.selections.change_with(cx, |selections| {
10116                    new_selections.push(Selection {
10117                        id: selections.new_selection_id(),
10118                        start: offset_range.start,
10119                        end: offset_range.end,
10120                        reversed: false,
10121                        goal: SelectionGoal::None,
10122                    });
10123                });
10124            }
10125        }
10126
10127        new_selections.sort_by_key(|selection| selection.start);
10128        let mut ix = 0;
10129        while ix + 1 < new_selections.len() {
10130            let current_selection = &new_selections[ix];
10131            let next_selection = &new_selections[ix + 1];
10132            if current_selection.range().overlaps(&next_selection.range()) {
10133                if current_selection.id < next_selection.id {
10134                    new_selections.remove(ix + 1);
10135                } else {
10136                    new_selections.remove(ix);
10137                }
10138            } else {
10139                ix += 1;
10140            }
10141        }
10142
10143        let reversed = self.selections.oldest::<usize>(cx).reversed;
10144
10145        for selection in new_selections.iter_mut() {
10146            selection.reversed = reversed;
10147        }
10148
10149        select_next_state.done = true;
10150        self.unfold_ranges(
10151            &new_selections
10152                .iter()
10153                .map(|selection| selection.range())
10154                .collect::<Vec<_>>(),
10155            false,
10156            false,
10157            cx,
10158        );
10159        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10160            selections.select(new_selections)
10161        });
10162
10163        Ok(())
10164    }
10165
10166    pub fn select_next(
10167        &mut self,
10168        action: &SelectNext,
10169        window: &mut Window,
10170        cx: &mut Context<Self>,
10171    ) -> Result<()> {
10172        self.push_to_selection_history();
10173        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10174        self.select_next_match_internal(
10175            &display_map,
10176            action.replace_newest,
10177            Some(Autoscroll::newest()),
10178            window,
10179            cx,
10180        )?;
10181        Ok(())
10182    }
10183
10184    pub fn select_previous(
10185        &mut self,
10186        action: &SelectPrevious,
10187        window: &mut Window,
10188        cx: &mut Context<Self>,
10189    ) -> Result<()> {
10190        self.push_to_selection_history();
10191        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10192        let buffer = &display_map.buffer_snapshot;
10193        let mut selections = self.selections.all::<usize>(cx);
10194        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10195            let query = &select_prev_state.query;
10196            if !select_prev_state.done {
10197                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10198                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10199                let mut next_selected_range = None;
10200                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10201                let bytes_before_last_selection =
10202                    buffer.reversed_bytes_in_range(0..last_selection.start);
10203                let bytes_after_first_selection =
10204                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10205                let query_matches = query
10206                    .stream_find_iter(bytes_before_last_selection)
10207                    .map(|result| (last_selection.start, result))
10208                    .chain(
10209                        query
10210                            .stream_find_iter(bytes_after_first_selection)
10211                            .map(|result| (buffer.len(), result)),
10212                    );
10213                for (end_offset, query_match) in query_matches {
10214                    let query_match = query_match.unwrap(); // can only fail due to I/O
10215                    let offset_range =
10216                        end_offset - query_match.end()..end_offset - query_match.start();
10217                    let display_range = offset_range.start.to_display_point(&display_map)
10218                        ..offset_range.end.to_display_point(&display_map);
10219
10220                    if !select_prev_state.wordwise
10221                        || (!movement::is_inside_word(&display_map, display_range.start)
10222                            && !movement::is_inside_word(&display_map, display_range.end))
10223                    {
10224                        next_selected_range = Some(offset_range);
10225                        break;
10226                    }
10227                }
10228
10229                if let Some(next_selected_range) = next_selected_range {
10230                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10231                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10232                        if action.replace_newest {
10233                            s.delete(s.newest_anchor().id);
10234                        }
10235                        s.insert_range(next_selected_range);
10236                    });
10237                } else {
10238                    select_prev_state.done = true;
10239                }
10240            }
10241
10242            self.select_prev_state = Some(select_prev_state);
10243        } else {
10244            let mut only_carets = true;
10245            let mut same_text_selected = true;
10246            let mut selected_text = None;
10247
10248            let mut selections_iter = selections.iter().peekable();
10249            while let Some(selection) = selections_iter.next() {
10250                if selection.start != selection.end {
10251                    only_carets = false;
10252                }
10253
10254                if same_text_selected {
10255                    if selected_text.is_none() {
10256                        selected_text =
10257                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10258                    }
10259
10260                    if let Some(next_selection) = selections_iter.peek() {
10261                        if next_selection.range().len() == selection.range().len() {
10262                            let next_selected_text = buffer
10263                                .text_for_range(next_selection.range())
10264                                .collect::<String>();
10265                            if Some(next_selected_text) != selected_text {
10266                                same_text_selected = false;
10267                                selected_text = None;
10268                            }
10269                        } else {
10270                            same_text_selected = false;
10271                            selected_text = None;
10272                        }
10273                    }
10274                }
10275            }
10276
10277            if only_carets {
10278                for selection in &mut selections {
10279                    let word_range = movement::surrounding_word(
10280                        &display_map,
10281                        selection.start.to_display_point(&display_map),
10282                    );
10283                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10284                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10285                    selection.goal = SelectionGoal::None;
10286                    selection.reversed = false;
10287                }
10288                if selections.len() == 1 {
10289                    let selection = selections
10290                        .last()
10291                        .expect("ensured that there's only one selection");
10292                    let query = buffer
10293                        .text_for_range(selection.start..selection.end)
10294                        .collect::<String>();
10295                    let is_empty = query.is_empty();
10296                    let select_state = SelectNextState {
10297                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10298                        wordwise: true,
10299                        done: is_empty,
10300                    };
10301                    self.select_prev_state = Some(select_state);
10302                } else {
10303                    self.select_prev_state = None;
10304                }
10305
10306                self.unfold_ranges(
10307                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10308                    false,
10309                    true,
10310                    cx,
10311                );
10312                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10313                    s.select(selections);
10314                });
10315            } else if let Some(selected_text) = selected_text {
10316                self.select_prev_state = Some(SelectNextState {
10317                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10318                    wordwise: false,
10319                    done: false,
10320                });
10321                self.select_previous(action, window, cx)?;
10322            }
10323        }
10324        Ok(())
10325    }
10326
10327    pub fn toggle_comments(
10328        &mut self,
10329        action: &ToggleComments,
10330        window: &mut Window,
10331        cx: &mut Context<Self>,
10332    ) {
10333        if self.read_only(cx) {
10334            return;
10335        }
10336        let text_layout_details = &self.text_layout_details(window);
10337        self.transact(window, cx, |this, window, cx| {
10338            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10339            let mut edits = Vec::new();
10340            let mut selection_edit_ranges = Vec::new();
10341            let mut last_toggled_row = None;
10342            let snapshot = this.buffer.read(cx).read(cx);
10343            let empty_str: Arc<str> = Arc::default();
10344            let mut suffixes_inserted = Vec::new();
10345            let ignore_indent = action.ignore_indent;
10346
10347            fn comment_prefix_range(
10348                snapshot: &MultiBufferSnapshot,
10349                row: MultiBufferRow,
10350                comment_prefix: &str,
10351                comment_prefix_whitespace: &str,
10352                ignore_indent: bool,
10353            ) -> Range<Point> {
10354                let indent_size = if ignore_indent {
10355                    0
10356                } else {
10357                    snapshot.indent_size_for_line(row).len
10358                };
10359
10360                let start = Point::new(row.0, indent_size);
10361
10362                let mut line_bytes = snapshot
10363                    .bytes_in_range(start..snapshot.max_point())
10364                    .flatten()
10365                    .copied();
10366
10367                // If this line currently begins with the line comment prefix, then record
10368                // the range containing the prefix.
10369                if line_bytes
10370                    .by_ref()
10371                    .take(comment_prefix.len())
10372                    .eq(comment_prefix.bytes())
10373                {
10374                    // Include any whitespace that matches the comment prefix.
10375                    let matching_whitespace_len = line_bytes
10376                        .zip(comment_prefix_whitespace.bytes())
10377                        .take_while(|(a, b)| a == b)
10378                        .count() as u32;
10379                    let end = Point::new(
10380                        start.row,
10381                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10382                    );
10383                    start..end
10384                } else {
10385                    start..start
10386                }
10387            }
10388
10389            fn comment_suffix_range(
10390                snapshot: &MultiBufferSnapshot,
10391                row: MultiBufferRow,
10392                comment_suffix: &str,
10393                comment_suffix_has_leading_space: bool,
10394            ) -> Range<Point> {
10395                let end = Point::new(row.0, snapshot.line_len(row));
10396                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10397
10398                let mut line_end_bytes = snapshot
10399                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10400                    .flatten()
10401                    .copied();
10402
10403                let leading_space_len = if suffix_start_column > 0
10404                    && line_end_bytes.next() == Some(b' ')
10405                    && comment_suffix_has_leading_space
10406                {
10407                    1
10408                } else {
10409                    0
10410                };
10411
10412                // If this line currently begins with the line comment prefix, then record
10413                // the range containing the prefix.
10414                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10415                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10416                    start..end
10417                } else {
10418                    end..end
10419                }
10420            }
10421
10422            // TODO: Handle selections that cross excerpts
10423            for selection in &mut selections {
10424                let start_column = snapshot
10425                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10426                    .len;
10427                let language = if let Some(language) =
10428                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10429                {
10430                    language
10431                } else {
10432                    continue;
10433                };
10434
10435                selection_edit_ranges.clear();
10436
10437                // If multiple selections contain a given row, avoid processing that
10438                // row more than once.
10439                let mut start_row = MultiBufferRow(selection.start.row);
10440                if last_toggled_row == Some(start_row) {
10441                    start_row = start_row.next_row();
10442                }
10443                let end_row =
10444                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10445                        MultiBufferRow(selection.end.row - 1)
10446                    } else {
10447                        MultiBufferRow(selection.end.row)
10448                    };
10449                last_toggled_row = Some(end_row);
10450
10451                if start_row > end_row {
10452                    continue;
10453                }
10454
10455                // If the language has line comments, toggle those.
10456                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10457
10458                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10459                if ignore_indent {
10460                    full_comment_prefixes = full_comment_prefixes
10461                        .into_iter()
10462                        .map(|s| Arc::from(s.trim_end()))
10463                        .collect();
10464                }
10465
10466                if !full_comment_prefixes.is_empty() {
10467                    let first_prefix = full_comment_prefixes
10468                        .first()
10469                        .expect("prefixes is non-empty");
10470                    let prefix_trimmed_lengths = full_comment_prefixes
10471                        .iter()
10472                        .map(|p| p.trim_end_matches(' ').len())
10473                        .collect::<SmallVec<[usize; 4]>>();
10474
10475                    let mut all_selection_lines_are_comments = true;
10476
10477                    for row in start_row.0..=end_row.0 {
10478                        let row = MultiBufferRow(row);
10479                        if start_row < end_row && snapshot.is_line_blank(row) {
10480                            continue;
10481                        }
10482
10483                        let prefix_range = full_comment_prefixes
10484                            .iter()
10485                            .zip(prefix_trimmed_lengths.iter().copied())
10486                            .map(|(prefix, trimmed_prefix_len)| {
10487                                comment_prefix_range(
10488                                    snapshot.deref(),
10489                                    row,
10490                                    &prefix[..trimmed_prefix_len],
10491                                    &prefix[trimmed_prefix_len..],
10492                                    ignore_indent,
10493                                )
10494                            })
10495                            .max_by_key(|range| range.end.column - range.start.column)
10496                            .expect("prefixes is non-empty");
10497
10498                        if prefix_range.is_empty() {
10499                            all_selection_lines_are_comments = false;
10500                        }
10501
10502                        selection_edit_ranges.push(prefix_range);
10503                    }
10504
10505                    if all_selection_lines_are_comments {
10506                        edits.extend(
10507                            selection_edit_ranges
10508                                .iter()
10509                                .cloned()
10510                                .map(|range| (range, empty_str.clone())),
10511                        );
10512                    } else {
10513                        let min_column = selection_edit_ranges
10514                            .iter()
10515                            .map(|range| range.start.column)
10516                            .min()
10517                            .unwrap_or(0);
10518                        edits.extend(selection_edit_ranges.iter().map(|range| {
10519                            let position = Point::new(range.start.row, min_column);
10520                            (position..position, first_prefix.clone())
10521                        }));
10522                    }
10523                } else if let Some((full_comment_prefix, comment_suffix)) =
10524                    language.block_comment_delimiters()
10525                {
10526                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10527                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10528                    let prefix_range = comment_prefix_range(
10529                        snapshot.deref(),
10530                        start_row,
10531                        comment_prefix,
10532                        comment_prefix_whitespace,
10533                        ignore_indent,
10534                    );
10535                    let suffix_range = comment_suffix_range(
10536                        snapshot.deref(),
10537                        end_row,
10538                        comment_suffix.trim_start_matches(' '),
10539                        comment_suffix.starts_with(' '),
10540                    );
10541
10542                    if prefix_range.is_empty() || suffix_range.is_empty() {
10543                        edits.push((
10544                            prefix_range.start..prefix_range.start,
10545                            full_comment_prefix.clone(),
10546                        ));
10547                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10548                        suffixes_inserted.push((end_row, comment_suffix.len()));
10549                    } else {
10550                        edits.push((prefix_range, empty_str.clone()));
10551                        edits.push((suffix_range, empty_str.clone()));
10552                    }
10553                } else {
10554                    continue;
10555                }
10556            }
10557
10558            drop(snapshot);
10559            this.buffer.update(cx, |buffer, cx| {
10560                buffer.edit(edits, None, cx);
10561            });
10562
10563            // Adjust selections so that they end before any comment suffixes that
10564            // were inserted.
10565            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10566            let mut selections = this.selections.all::<Point>(cx);
10567            let snapshot = this.buffer.read(cx).read(cx);
10568            for selection in &mut selections {
10569                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10570                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10571                        Ordering::Less => {
10572                            suffixes_inserted.next();
10573                            continue;
10574                        }
10575                        Ordering::Greater => break,
10576                        Ordering::Equal => {
10577                            if selection.end.column == snapshot.line_len(row) {
10578                                if selection.is_empty() {
10579                                    selection.start.column -= suffix_len as u32;
10580                                }
10581                                selection.end.column -= suffix_len as u32;
10582                            }
10583                            break;
10584                        }
10585                    }
10586                }
10587            }
10588
10589            drop(snapshot);
10590            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10591                s.select(selections)
10592            });
10593
10594            let selections = this.selections.all::<Point>(cx);
10595            let selections_on_single_row = selections.windows(2).all(|selections| {
10596                selections[0].start.row == selections[1].start.row
10597                    && selections[0].end.row == selections[1].end.row
10598                    && selections[0].start.row == selections[0].end.row
10599            });
10600            let selections_selecting = selections
10601                .iter()
10602                .any(|selection| selection.start != selection.end);
10603            let advance_downwards = action.advance_downwards
10604                && selections_on_single_row
10605                && !selections_selecting
10606                && !matches!(this.mode, EditorMode::SingleLine { .. });
10607
10608            if advance_downwards {
10609                let snapshot = this.buffer.read(cx).snapshot(cx);
10610
10611                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10612                    s.move_cursors_with(|display_snapshot, display_point, _| {
10613                        let mut point = display_point.to_point(display_snapshot);
10614                        point.row += 1;
10615                        point = snapshot.clip_point(point, Bias::Left);
10616                        let display_point = point.to_display_point(display_snapshot);
10617                        let goal = SelectionGoal::HorizontalPosition(
10618                            display_snapshot
10619                                .x_for_display_point(display_point, text_layout_details)
10620                                .into(),
10621                        );
10622                        (display_point, goal)
10623                    })
10624                });
10625            }
10626        });
10627    }
10628
10629    pub fn select_enclosing_symbol(
10630        &mut self,
10631        _: &SelectEnclosingSymbol,
10632        window: &mut Window,
10633        cx: &mut Context<Self>,
10634    ) {
10635        let buffer = self.buffer.read(cx).snapshot(cx);
10636        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10637
10638        fn update_selection(
10639            selection: &Selection<usize>,
10640            buffer_snap: &MultiBufferSnapshot,
10641        ) -> Option<Selection<usize>> {
10642            let cursor = selection.head();
10643            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10644            for symbol in symbols.iter().rev() {
10645                let start = symbol.range.start.to_offset(buffer_snap);
10646                let end = symbol.range.end.to_offset(buffer_snap);
10647                let new_range = start..end;
10648                if start < selection.start || end > selection.end {
10649                    return Some(Selection {
10650                        id: selection.id,
10651                        start: new_range.start,
10652                        end: new_range.end,
10653                        goal: SelectionGoal::None,
10654                        reversed: selection.reversed,
10655                    });
10656                }
10657            }
10658            None
10659        }
10660
10661        let mut selected_larger_symbol = false;
10662        let new_selections = old_selections
10663            .iter()
10664            .map(|selection| match update_selection(selection, &buffer) {
10665                Some(new_selection) => {
10666                    if new_selection.range() != selection.range() {
10667                        selected_larger_symbol = true;
10668                    }
10669                    new_selection
10670                }
10671                None => selection.clone(),
10672            })
10673            .collect::<Vec<_>>();
10674
10675        if selected_larger_symbol {
10676            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10677                s.select(new_selections);
10678            });
10679        }
10680    }
10681
10682    pub fn select_larger_syntax_node(
10683        &mut self,
10684        _: &SelectLargerSyntaxNode,
10685        window: &mut Window,
10686        cx: &mut Context<Self>,
10687    ) {
10688        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10689        let buffer = self.buffer.read(cx).snapshot(cx);
10690        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10691
10692        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10693        let mut selected_larger_node = false;
10694        let new_selections = old_selections
10695            .iter()
10696            .map(|selection| {
10697                let old_range = selection.start..selection.end;
10698                let mut new_range = old_range.clone();
10699                let mut new_node = None;
10700                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10701                {
10702                    new_node = Some(node);
10703                    new_range = containing_range;
10704                    if !display_map.intersects_fold(new_range.start)
10705                        && !display_map.intersects_fold(new_range.end)
10706                    {
10707                        break;
10708                    }
10709                }
10710
10711                if let Some(node) = new_node {
10712                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10713                    // nodes. Parent and grandparent are also logged because this operation will not
10714                    // visit nodes that have the same range as their parent.
10715                    log::info!("Node: {node:?}");
10716                    let parent = node.parent();
10717                    log::info!("Parent: {parent:?}");
10718                    let grandparent = parent.and_then(|x| x.parent());
10719                    log::info!("Grandparent: {grandparent:?}");
10720                }
10721
10722                selected_larger_node |= new_range != old_range;
10723                Selection {
10724                    id: selection.id,
10725                    start: new_range.start,
10726                    end: new_range.end,
10727                    goal: SelectionGoal::None,
10728                    reversed: selection.reversed,
10729                }
10730            })
10731            .collect::<Vec<_>>();
10732
10733        if selected_larger_node {
10734            stack.push(old_selections);
10735            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10736                s.select(new_selections);
10737            });
10738        }
10739        self.select_larger_syntax_node_stack = stack;
10740    }
10741
10742    pub fn select_smaller_syntax_node(
10743        &mut self,
10744        _: &SelectSmallerSyntaxNode,
10745        window: &mut Window,
10746        cx: &mut Context<Self>,
10747    ) {
10748        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10749        if let Some(selections) = stack.pop() {
10750            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10751                s.select(selections.to_vec());
10752            });
10753        }
10754        self.select_larger_syntax_node_stack = stack;
10755    }
10756
10757    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10758        if !EditorSettings::get_global(cx).gutter.runnables {
10759            self.clear_tasks();
10760            return Task::ready(());
10761        }
10762        let project = self.project.as_ref().map(Entity::downgrade);
10763        cx.spawn_in(window, |this, mut cx| async move {
10764            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10765            let Some(project) = project.and_then(|p| p.upgrade()) else {
10766                return;
10767            };
10768            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10769                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10770            }) else {
10771                return;
10772            };
10773
10774            let hide_runnables = project
10775                .update(&mut cx, |project, cx| {
10776                    // Do not display any test indicators in non-dev server remote projects.
10777                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10778                })
10779                .unwrap_or(true);
10780            if hide_runnables {
10781                return;
10782            }
10783            let new_rows =
10784                cx.background_spawn({
10785                    let snapshot = display_snapshot.clone();
10786                    async move {
10787                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10788                    }
10789                })
10790                    .await;
10791
10792            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10793            this.update(&mut cx, |this, _| {
10794                this.clear_tasks();
10795                for (key, value) in rows {
10796                    this.insert_tasks(key, value);
10797                }
10798            })
10799            .ok();
10800        })
10801    }
10802    fn fetch_runnable_ranges(
10803        snapshot: &DisplaySnapshot,
10804        range: Range<Anchor>,
10805    ) -> Vec<language::RunnableRange> {
10806        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10807    }
10808
10809    fn runnable_rows(
10810        project: Entity<Project>,
10811        snapshot: DisplaySnapshot,
10812        runnable_ranges: Vec<RunnableRange>,
10813        mut cx: AsyncWindowContext,
10814    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10815        runnable_ranges
10816            .into_iter()
10817            .filter_map(|mut runnable| {
10818                let tasks = cx
10819                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10820                    .ok()?;
10821                if tasks.is_empty() {
10822                    return None;
10823                }
10824
10825                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10826
10827                let row = snapshot
10828                    .buffer_snapshot
10829                    .buffer_line_for_row(MultiBufferRow(point.row))?
10830                    .1
10831                    .start
10832                    .row;
10833
10834                let context_range =
10835                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10836                Some((
10837                    (runnable.buffer_id, row),
10838                    RunnableTasks {
10839                        templates: tasks,
10840                        offset: MultiBufferOffset(runnable.run_range.start),
10841                        context_range,
10842                        column: point.column,
10843                        extra_variables: runnable.extra_captures,
10844                    },
10845                ))
10846            })
10847            .collect()
10848    }
10849
10850    fn templates_with_tags(
10851        project: &Entity<Project>,
10852        runnable: &mut Runnable,
10853        cx: &mut App,
10854    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10855        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10856            let (worktree_id, file) = project
10857                .buffer_for_id(runnable.buffer, cx)
10858                .and_then(|buffer| buffer.read(cx).file())
10859                .map(|file| (file.worktree_id(cx), file.clone()))
10860                .unzip();
10861
10862            (
10863                project.task_store().read(cx).task_inventory().cloned(),
10864                worktree_id,
10865                file,
10866            )
10867        });
10868
10869        let tags = mem::take(&mut runnable.tags);
10870        let mut tags: Vec<_> = tags
10871            .into_iter()
10872            .flat_map(|tag| {
10873                let tag = tag.0.clone();
10874                inventory
10875                    .as_ref()
10876                    .into_iter()
10877                    .flat_map(|inventory| {
10878                        inventory.read(cx).list_tasks(
10879                            file.clone(),
10880                            Some(runnable.language.clone()),
10881                            worktree_id,
10882                            cx,
10883                        )
10884                    })
10885                    .filter(move |(_, template)| {
10886                        template.tags.iter().any(|source_tag| source_tag == &tag)
10887                    })
10888            })
10889            .sorted_by_key(|(kind, _)| kind.to_owned())
10890            .collect();
10891        if let Some((leading_tag_source, _)) = tags.first() {
10892            // Strongest source wins; if we have worktree tag binding, prefer that to
10893            // global and language bindings;
10894            // if we have a global binding, prefer that to language binding.
10895            let first_mismatch = tags
10896                .iter()
10897                .position(|(tag_source, _)| tag_source != leading_tag_source);
10898            if let Some(index) = first_mismatch {
10899                tags.truncate(index);
10900            }
10901        }
10902
10903        tags
10904    }
10905
10906    pub fn move_to_enclosing_bracket(
10907        &mut self,
10908        _: &MoveToEnclosingBracket,
10909        window: &mut Window,
10910        cx: &mut Context<Self>,
10911    ) {
10912        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10913            s.move_offsets_with(|snapshot, selection| {
10914                let Some(enclosing_bracket_ranges) =
10915                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10916                else {
10917                    return;
10918                };
10919
10920                let mut best_length = usize::MAX;
10921                let mut best_inside = false;
10922                let mut best_in_bracket_range = false;
10923                let mut best_destination = None;
10924                for (open, close) in enclosing_bracket_ranges {
10925                    let close = close.to_inclusive();
10926                    let length = close.end() - open.start;
10927                    let inside = selection.start >= open.end && selection.end <= *close.start();
10928                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10929                        || close.contains(&selection.head());
10930
10931                    // If best is next to a bracket and current isn't, skip
10932                    if !in_bracket_range && best_in_bracket_range {
10933                        continue;
10934                    }
10935
10936                    // Prefer smaller lengths unless best is inside and current isn't
10937                    if length > best_length && (best_inside || !inside) {
10938                        continue;
10939                    }
10940
10941                    best_length = length;
10942                    best_inside = inside;
10943                    best_in_bracket_range = in_bracket_range;
10944                    best_destination = Some(
10945                        if close.contains(&selection.start) && close.contains(&selection.end) {
10946                            if inside {
10947                                open.end
10948                            } else {
10949                                open.start
10950                            }
10951                        } else if inside {
10952                            *close.start()
10953                        } else {
10954                            *close.end()
10955                        },
10956                    );
10957                }
10958
10959                if let Some(destination) = best_destination {
10960                    selection.collapse_to(destination, SelectionGoal::None);
10961                }
10962            })
10963        });
10964    }
10965
10966    pub fn undo_selection(
10967        &mut self,
10968        _: &UndoSelection,
10969        window: &mut Window,
10970        cx: &mut Context<Self>,
10971    ) {
10972        self.end_selection(window, cx);
10973        self.selection_history.mode = SelectionHistoryMode::Undoing;
10974        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10975            self.change_selections(None, window, cx, |s| {
10976                s.select_anchors(entry.selections.to_vec())
10977            });
10978            self.select_next_state = entry.select_next_state;
10979            self.select_prev_state = entry.select_prev_state;
10980            self.add_selections_state = entry.add_selections_state;
10981            self.request_autoscroll(Autoscroll::newest(), cx);
10982        }
10983        self.selection_history.mode = SelectionHistoryMode::Normal;
10984    }
10985
10986    pub fn redo_selection(
10987        &mut self,
10988        _: &RedoSelection,
10989        window: &mut Window,
10990        cx: &mut Context<Self>,
10991    ) {
10992        self.end_selection(window, cx);
10993        self.selection_history.mode = SelectionHistoryMode::Redoing;
10994        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10995            self.change_selections(None, window, cx, |s| {
10996                s.select_anchors(entry.selections.to_vec())
10997            });
10998            self.select_next_state = entry.select_next_state;
10999            self.select_prev_state = entry.select_prev_state;
11000            self.add_selections_state = entry.add_selections_state;
11001            self.request_autoscroll(Autoscroll::newest(), cx);
11002        }
11003        self.selection_history.mode = SelectionHistoryMode::Normal;
11004    }
11005
11006    pub fn expand_excerpts(
11007        &mut self,
11008        action: &ExpandExcerpts,
11009        _: &mut Window,
11010        cx: &mut Context<Self>,
11011    ) {
11012        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11013    }
11014
11015    pub fn expand_excerpts_down(
11016        &mut self,
11017        action: &ExpandExcerptsDown,
11018        _: &mut Window,
11019        cx: &mut Context<Self>,
11020    ) {
11021        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11022    }
11023
11024    pub fn expand_excerpts_up(
11025        &mut self,
11026        action: &ExpandExcerptsUp,
11027        _: &mut Window,
11028        cx: &mut Context<Self>,
11029    ) {
11030        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11031    }
11032
11033    pub fn expand_excerpts_for_direction(
11034        &mut self,
11035        lines: u32,
11036        direction: ExpandExcerptDirection,
11037
11038        cx: &mut Context<Self>,
11039    ) {
11040        let selections = self.selections.disjoint_anchors();
11041
11042        let lines = if lines == 0 {
11043            EditorSettings::get_global(cx).expand_excerpt_lines
11044        } else {
11045            lines
11046        };
11047
11048        self.buffer.update(cx, |buffer, cx| {
11049            let snapshot = buffer.snapshot(cx);
11050            let mut excerpt_ids = selections
11051                .iter()
11052                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11053                .collect::<Vec<_>>();
11054            excerpt_ids.sort();
11055            excerpt_ids.dedup();
11056            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11057        })
11058    }
11059
11060    pub fn expand_excerpt(
11061        &mut self,
11062        excerpt: ExcerptId,
11063        direction: ExpandExcerptDirection,
11064        cx: &mut Context<Self>,
11065    ) {
11066        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11067        self.buffer.update(cx, |buffer, cx| {
11068            buffer.expand_excerpts([excerpt], lines, direction, cx)
11069        })
11070    }
11071
11072    pub fn go_to_singleton_buffer_point(
11073        &mut self,
11074        point: Point,
11075        window: &mut Window,
11076        cx: &mut Context<Self>,
11077    ) {
11078        self.go_to_singleton_buffer_range(point..point, window, cx);
11079    }
11080
11081    pub fn go_to_singleton_buffer_range(
11082        &mut self,
11083        range: Range<Point>,
11084        window: &mut Window,
11085        cx: &mut Context<Self>,
11086    ) {
11087        let multibuffer = self.buffer().read(cx);
11088        let Some(buffer) = multibuffer.as_singleton() else {
11089            return;
11090        };
11091        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11092            return;
11093        };
11094        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11095            return;
11096        };
11097        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11098            s.select_anchor_ranges([start..end])
11099        });
11100    }
11101
11102    fn go_to_diagnostic(
11103        &mut self,
11104        _: &GoToDiagnostic,
11105        window: &mut Window,
11106        cx: &mut Context<Self>,
11107    ) {
11108        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11109    }
11110
11111    fn go_to_prev_diagnostic(
11112        &mut self,
11113        _: &GoToPrevDiagnostic,
11114        window: &mut Window,
11115        cx: &mut Context<Self>,
11116    ) {
11117        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11118    }
11119
11120    pub fn go_to_diagnostic_impl(
11121        &mut self,
11122        direction: Direction,
11123        window: &mut Window,
11124        cx: &mut Context<Self>,
11125    ) {
11126        let buffer = self.buffer.read(cx).snapshot(cx);
11127        let selection = self.selections.newest::<usize>(cx);
11128
11129        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11130        if direction == Direction::Next {
11131            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11132                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11133                    return;
11134                };
11135                self.activate_diagnostics(
11136                    buffer_id,
11137                    popover.local_diagnostic.diagnostic.group_id,
11138                    window,
11139                    cx,
11140                );
11141                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11142                    let primary_range_start = active_diagnostics.primary_range.start;
11143                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11144                        let mut new_selection = s.newest_anchor().clone();
11145                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11146                        s.select_anchors(vec![new_selection.clone()]);
11147                    });
11148                    self.refresh_inline_completion(false, true, window, cx);
11149                }
11150                return;
11151            }
11152        }
11153
11154        let active_group_id = self
11155            .active_diagnostics
11156            .as_ref()
11157            .map(|active_group| active_group.group_id);
11158        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11159            active_diagnostics
11160                .primary_range
11161                .to_offset(&buffer)
11162                .to_inclusive()
11163        });
11164        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11165            if active_primary_range.contains(&selection.head()) {
11166                *active_primary_range.start()
11167            } else {
11168                selection.head()
11169            }
11170        } else {
11171            selection.head()
11172        };
11173
11174        let snapshot = self.snapshot(window, cx);
11175        let primary_diagnostics_before = buffer
11176            .diagnostics_in_range::<usize>(0..search_start)
11177            .filter(|entry| entry.diagnostic.is_primary)
11178            .filter(|entry| entry.range.start != entry.range.end)
11179            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11180            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11181            .collect::<Vec<_>>();
11182        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11183            primary_diagnostics_before
11184                .iter()
11185                .position(|entry| entry.diagnostic.group_id == active_group_id)
11186        });
11187
11188        let primary_diagnostics_after = buffer
11189            .diagnostics_in_range::<usize>(search_start..buffer.len())
11190            .filter(|entry| entry.diagnostic.is_primary)
11191            .filter(|entry| entry.range.start != entry.range.end)
11192            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11193            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11194            .collect::<Vec<_>>();
11195        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11196            primary_diagnostics_after
11197                .iter()
11198                .enumerate()
11199                .rev()
11200                .find_map(|(i, entry)| {
11201                    if entry.diagnostic.group_id == active_group_id {
11202                        Some(i)
11203                    } else {
11204                        None
11205                    }
11206                })
11207        });
11208
11209        let next_primary_diagnostic = match direction {
11210            Direction::Prev => primary_diagnostics_before
11211                .iter()
11212                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11213                .rev()
11214                .next(),
11215            Direction::Next => primary_diagnostics_after
11216                .iter()
11217                .skip(
11218                    last_same_group_diagnostic_after
11219                        .map(|index| index + 1)
11220                        .unwrap_or(0),
11221                )
11222                .next(),
11223        };
11224
11225        // Cycle around to the start of the buffer, potentially moving back to the start of
11226        // the currently active diagnostic.
11227        let cycle_around = || match direction {
11228            Direction::Prev => primary_diagnostics_after
11229                .iter()
11230                .rev()
11231                .chain(primary_diagnostics_before.iter().rev())
11232                .next(),
11233            Direction::Next => primary_diagnostics_before
11234                .iter()
11235                .chain(primary_diagnostics_after.iter())
11236                .next(),
11237        };
11238
11239        if let Some((primary_range, group_id)) = next_primary_diagnostic
11240            .or_else(cycle_around)
11241            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11242        {
11243            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11244                return;
11245            };
11246            self.activate_diagnostics(buffer_id, group_id, window, cx);
11247            if self.active_diagnostics.is_some() {
11248                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11249                    s.select(vec![Selection {
11250                        id: selection.id,
11251                        start: primary_range.start,
11252                        end: primary_range.start,
11253                        reversed: false,
11254                        goal: SelectionGoal::None,
11255                    }]);
11256                });
11257                self.refresh_inline_completion(false, true, window, cx);
11258            }
11259        }
11260    }
11261
11262    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11263        let snapshot = self.snapshot(window, cx);
11264        let selection = self.selections.newest::<Point>(cx);
11265        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
11266    }
11267
11268    fn go_to_hunk_after_position(
11269        &mut self,
11270        snapshot: &EditorSnapshot,
11271        position: Point,
11272        window: &mut Window,
11273        cx: &mut Context<Editor>,
11274    ) -> Option<MultiBufferDiffHunk> {
11275        let mut hunk = snapshot
11276            .buffer_snapshot
11277            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11278            .find(|hunk| hunk.row_range.start.0 > position.row);
11279        if hunk.is_none() {
11280            hunk = snapshot
11281                .buffer_snapshot
11282                .diff_hunks_in_range(Point::zero()..position)
11283                .find(|hunk| hunk.row_range.end.0 < position.row)
11284        }
11285        if let Some(hunk) = &hunk {
11286            let destination = Point::new(hunk.row_range.start.0, 0);
11287            self.unfold_ranges(&[destination..destination], false, false, cx);
11288            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11289                s.select_ranges(vec![destination..destination]);
11290            });
11291        }
11292
11293        hunk
11294    }
11295
11296    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
11297        let snapshot = self.snapshot(window, cx);
11298        let selection = self.selections.newest::<Point>(cx);
11299        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
11300    }
11301
11302    fn go_to_hunk_before_position(
11303        &mut self,
11304        snapshot: &EditorSnapshot,
11305        position: Point,
11306        window: &mut Window,
11307        cx: &mut Context<Editor>,
11308    ) -> Option<MultiBufferDiffHunk> {
11309        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
11310        if hunk.is_none() {
11311            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
11312        }
11313        if let Some(hunk) = &hunk {
11314            let destination = Point::new(hunk.row_range.start.0, 0);
11315            self.unfold_ranges(&[destination..destination], false, false, cx);
11316            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11317                s.select_ranges(vec![destination..destination]);
11318            });
11319        }
11320
11321        hunk
11322    }
11323
11324    pub fn go_to_definition(
11325        &mut self,
11326        _: &GoToDefinition,
11327        window: &mut Window,
11328        cx: &mut Context<Self>,
11329    ) -> Task<Result<Navigated>> {
11330        let definition =
11331            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11332        cx.spawn_in(window, |editor, mut cx| async move {
11333            if definition.await? == Navigated::Yes {
11334                return Ok(Navigated::Yes);
11335            }
11336            match editor.update_in(&mut cx, |editor, window, cx| {
11337                editor.find_all_references(&FindAllReferences, window, cx)
11338            })? {
11339                Some(references) => references.await,
11340                None => Ok(Navigated::No),
11341            }
11342        })
11343    }
11344
11345    pub fn go_to_declaration(
11346        &mut self,
11347        _: &GoToDeclaration,
11348        window: &mut Window,
11349        cx: &mut Context<Self>,
11350    ) -> Task<Result<Navigated>> {
11351        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11352    }
11353
11354    pub fn go_to_declaration_split(
11355        &mut self,
11356        _: &GoToDeclaration,
11357        window: &mut Window,
11358        cx: &mut Context<Self>,
11359    ) -> Task<Result<Navigated>> {
11360        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11361    }
11362
11363    pub fn go_to_implementation(
11364        &mut self,
11365        _: &GoToImplementation,
11366        window: &mut Window,
11367        cx: &mut Context<Self>,
11368    ) -> Task<Result<Navigated>> {
11369        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11370    }
11371
11372    pub fn go_to_implementation_split(
11373        &mut self,
11374        _: &GoToImplementationSplit,
11375        window: &mut Window,
11376        cx: &mut Context<Self>,
11377    ) -> Task<Result<Navigated>> {
11378        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11379    }
11380
11381    pub fn go_to_type_definition(
11382        &mut self,
11383        _: &GoToTypeDefinition,
11384        window: &mut Window,
11385        cx: &mut Context<Self>,
11386    ) -> Task<Result<Navigated>> {
11387        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11388    }
11389
11390    pub fn go_to_definition_split(
11391        &mut self,
11392        _: &GoToDefinitionSplit,
11393        window: &mut Window,
11394        cx: &mut Context<Self>,
11395    ) -> Task<Result<Navigated>> {
11396        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11397    }
11398
11399    pub fn go_to_type_definition_split(
11400        &mut self,
11401        _: &GoToTypeDefinitionSplit,
11402        window: &mut Window,
11403        cx: &mut Context<Self>,
11404    ) -> Task<Result<Navigated>> {
11405        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11406    }
11407
11408    fn go_to_definition_of_kind(
11409        &mut self,
11410        kind: GotoDefinitionKind,
11411        split: bool,
11412        window: &mut Window,
11413        cx: &mut Context<Self>,
11414    ) -> Task<Result<Navigated>> {
11415        let Some(provider) = self.semantics_provider.clone() else {
11416            return Task::ready(Ok(Navigated::No));
11417        };
11418        let head = self.selections.newest::<usize>(cx).head();
11419        let buffer = self.buffer.read(cx);
11420        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11421            text_anchor
11422        } else {
11423            return Task::ready(Ok(Navigated::No));
11424        };
11425
11426        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11427            return Task::ready(Ok(Navigated::No));
11428        };
11429
11430        cx.spawn_in(window, |editor, mut cx| async move {
11431            let definitions = definitions.await?;
11432            let navigated = editor
11433                .update_in(&mut cx, |editor, window, cx| {
11434                    editor.navigate_to_hover_links(
11435                        Some(kind),
11436                        definitions
11437                            .into_iter()
11438                            .filter(|location| {
11439                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11440                            })
11441                            .map(HoverLink::Text)
11442                            .collect::<Vec<_>>(),
11443                        split,
11444                        window,
11445                        cx,
11446                    )
11447                })?
11448                .await?;
11449            anyhow::Ok(navigated)
11450        })
11451    }
11452
11453    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11454        let selection = self.selections.newest_anchor();
11455        let head = selection.head();
11456        let tail = selection.tail();
11457
11458        let Some((buffer, start_position)) =
11459            self.buffer.read(cx).text_anchor_for_position(head, cx)
11460        else {
11461            return;
11462        };
11463
11464        let end_position = if head != tail {
11465            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11466                return;
11467            };
11468            Some(pos)
11469        } else {
11470            None
11471        };
11472
11473        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11474            let url = if let Some(end_pos) = end_position {
11475                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11476            } else {
11477                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11478            };
11479
11480            if let Some(url) = url {
11481                editor.update(&mut cx, |_, cx| {
11482                    cx.open_url(&url);
11483                })
11484            } else {
11485                Ok(())
11486            }
11487        });
11488
11489        url_finder.detach();
11490    }
11491
11492    pub fn open_selected_filename(
11493        &mut self,
11494        _: &OpenSelectedFilename,
11495        window: &mut Window,
11496        cx: &mut Context<Self>,
11497    ) {
11498        let Some(workspace) = self.workspace() else {
11499            return;
11500        };
11501
11502        let position = self.selections.newest_anchor().head();
11503
11504        let Some((buffer, buffer_position)) =
11505            self.buffer.read(cx).text_anchor_for_position(position, cx)
11506        else {
11507            return;
11508        };
11509
11510        let project = self.project.clone();
11511
11512        cx.spawn_in(window, |_, mut cx| async move {
11513            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11514
11515            if let Some((_, path)) = result {
11516                workspace
11517                    .update_in(&mut cx, |workspace, window, cx| {
11518                        workspace.open_resolved_path(path, window, cx)
11519                    })?
11520                    .await?;
11521            }
11522            anyhow::Ok(())
11523        })
11524        .detach();
11525    }
11526
11527    pub(crate) fn navigate_to_hover_links(
11528        &mut self,
11529        kind: Option<GotoDefinitionKind>,
11530        mut definitions: Vec<HoverLink>,
11531        split: bool,
11532        window: &mut Window,
11533        cx: &mut Context<Editor>,
11534    ) -> Task<Result<Navigated>> {
11535        // If there is one definition, just open it directly
11536        if definitions.len() == 1 {
11537            let definition = definitions.pop().unwrap();
11538
11539            enum TargetTaskResult {
11540                Location(Option<Location>),
11541                AlreadyNavigated,
11542            }
11543
11544            let target_task = match definition {
11545                HoverLink::Text(link) => {
11546                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11547                }
11548                HoverLink::InlayHint(lsp_location, server_id) => {
11549                    let computation =
11550                        self.compute_target_location(lsp_location, server_id, window, cx);
11551                    cx.background_spawn(async move {
11552                        let location = computation.await?;
11553                        Ok(TargetTaskResult::Location(location))
11554                    })
11555                }
11556                HoverLink::Url(url) => {
11557                    cx.open_url(&url);
11558                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11559                }
11560                HoverLink::File(path) => {
11561                    if let Some(workspace) = self.workspace() {
11562                        cx.spawn_in(window, |_, mut cx| async move {
11563                            workspace
11564                                .update_in(&mut cx, |workspace, window, cx| {
11565                                    workspace.open_resolved_path(path, window, cx)
11566                                })?
11567                                .await
11568                                .map(|_| TargetTaskResult::AlreadyNavigated)
11569                        })
11570                    } else {
11571                        Task::ready(Ok(TargetTaskResult::Location(None)))
11572                    }
11573                }
11574            };
11575            cx.spawn_in(window, |editor, mut cx| async move {
11576                let target = match target_task.await.context("target resolution task")? {
11577                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11578                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11579                    TargetTaskResult::Location(Some(target)) => target,
11580                };
11581
11582                editor.update_in(&mut cx, |editor, window, cx| {
11583                    let Some(workspace) = editor.workspace() else {
11584                        return Navigated::No;
11585                    };
11586                    let pane = workspace.read(cx).active_pane().clone();
11587
11588                    let range = target.range.to_point(target.buffer.read(cx));
11589                    let range = editor.range_for_match(&range);
11590                    let range = collapse_multiline_range(range);
11591
11592                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11593                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11594                    } else {
11595                        window.defer(cx, move |window, cx| {
11596                            let target_editor: Entity<Self> =
11597                                workspace.update(cx, |workspace, cx| {
11598                                    let pane = if split {
11599                                        workspace.adjacent_pane(window, cx)
11600                                    } else {
11601                                        workspace.active_pane().clone()
11602                                    };
11603
11604                                    workspace.open_project_item(
11605                                        pane,
11606                                        target.buffer.clone(),
11607                                        true,
11608                                        true,
11609                                        window,
11610                                        cx,
11611                                    )
11612                                });
11613                            target_editor.update(cx, |target_editor, cx| {
11614                                // When selecting a definition in a different buffer, disable the nav history
11615                                // to avoid creating a history entry at the previous cursor location.
11616                                pane.update(cx, |pane, _| pane.disable_history());
11617                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11618                                pane.update(cx, |pane, _| pane.enable_history());
11619                            });
11620                        });
11621                    }
11622                    Navigated::Yes
11623                })
11624            })
11625        } else if !definitions.is_empty() {
11626            cx.spawn_in(window, |editor, mut cx| async move {
11627                let (title, location_tasks, workspace) = editor
11628                    .update_in(&mut cx, |editor, window, cx| {
11629                        let tab_kind = match kind {
11630                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11631                            _ => "Definitions",
11632                        };
11633                        let title = definitions
11634                            .iter()
11635                            .find_map(|definition| match definition {
11636                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11637                                    let buffer = origin.buffer.read(cx);
11638                                    format!(
11639                                        "{} for {}",
11640                                        tab_kind,
11641                                        buffer
11642                                            .text_for_range(origin.range.clone())
11643                                            .collect::<String>()
11644                                    )
11645                                }),
11646                                HoverLink::InlayHint(_, _) => None,
11647                                HoverLink::Url(_) => None,
11648                                HoverLink::File(_) => None,
11649                            })
11650                            .unwrap_or(tab_kind.to_string());
11651                        let location_tasks = definitions
11652                            .into_iter()
11653                            .map(|definition| match definition {
11654                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11655                                HoverLink::InlayHint(lsp_location, server_id) => editor
11656                                    .compute_target_location(lsp_location, server_id, window, cx),
11657                                HoverLink::Url(_) => Task::ready(Ok(None)),
11658                                HoverLink::File(_) => Task::ready(Ok(None)),
11659                            })
11660                            .collect::<Vec<_>>();
11661                        (title, location_tasks, editor.workspace().clone())
11662                    })
11663                    .context("location tasks preparation")?;
11664
11665                let locations = future::join_all(location_tasks)
11666                    .await
11667                    .into_iter()
11668                    .filter_map(|location| location.transpose())
11669                    .collect::<Result<_>>()
11670                    .context("location tasks")?;
11671
11672                let Some(workspace) = workspace else {
11673                    return Ok(Navigated::No);
11674                };
11675                let opened = workspace
11676                    .update_in(&mut cx, |workspace, window, cx| {
11677                        Self::open_locations_in_multibuffer(
11678                            workspace,
11679                            locations,
11680                            title,
11681                            split,
11682                            MultibufferSelectionMode::First,
11683                            window,
11684                            cx,
11685                        )
11686                    })
11687                    .ok();
11688
11689                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11690            })
11691        } else {
11692            Task::ready(Ok(Navigated::No))
11693        }
11694    }
11695
11696    fn compute_target_location(
11697        &self,
11698        lsp_location: lsp::Location,
11699        server_id: LanguageServerId,
11700        window: &mut Window,
11701        cx: &mut Context<Self>,
11702    ) -> Task<anyhow::Result<Option<Location>>> {
11703        let Some(project) = self.project.clone() else {
11704            return Task::ready(Ok(None));
11705        };
11706
11707        cx.spawn_in(window, move |editor, mut cx| async move {
11708            let location_task = editor.update(&mut cx, |_, cx| {
11709                project.update(cx, |project, cx| {
11710                    let language_server_name = project
11711                        .language_server_statuses(cx)
11712                        .find(|(id, _)| server_id == *id)
11713                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11714                    language_server_name.map(|language_server_name| {
11715                        project.open_local_buffer_via_lsp(
11716                            lsp_location.uri.clone(),
11717                            server_id,
11718                            language_server_name,
11719                            cx,
11720                        )
11721                    })
11722                })
11723            })?;
11724            let location = match location_task {
11725                Some(task) => Some({
11726                    let target_buffer_handle = task.await.context("open local buffer")?;
11727                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11728                        let target_start = target_buffer
11729                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11730                        let target_end = target_buffer
11731                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11732                        target_buffer.anchor_after(target_start)
11733                            ..target_buffer.anchor_before(target_end)
11734                    })?;
11735                    Location {
11736                        buffer: target_buffer_handle,
11737                        range,
11738                    }
11739                }),
11740                None => None,
11741            };
11742            Ok(location)
11743        })
11744    }
11745
11746    pub fn find_all_references(
11747        &mut self,
11748        _: &FindAllReferences,
11749        window: &mut Window,
11750        cx: &mut Context<Self>,
11751    ) -> Option<Task<Result<Navigated>>> {
11752        let selection = self.selections.newest::<usize>(cx);
11753        let multi_buffer = self.buffer.read(cx);
11754        let head = selection.head();
11755
11756        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11757        let head_anchor = multi_buffer_snapshot.anchor_at(
11758            head,
11759            if head < selection.tail() {
11760                Bias::Right
11761            } else {
11762                Bias::Left
11763            },
11764        );
11765
11766        match self
11767            .find_all_references_task_sources
11768            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11769        {
11770            Ok(_) => {
11771                log::info!(
11772                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11773                );
11774                return None;
11775            }
11776            Err(i) => {
11777                self.find_all_references_task_sources.insert(i, head_anchor);
11778            }
11779        }
11780
11781        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11782        let workspace = self.workspace()?;
11783        let project = workspace.read(cx).project().clone();
11784        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11785        Some(cx.spawn_in(window, |editor, mut cx| async move {
11786            let _cleanup = defer({
11787                let mut cx = cx.clone();
11788                move || {
11789                    let _ = editor.update(&mut cx, |editor, _| {
11790                        if let Ok(i) =
11791                            editor
11792                                .find_all_references_task_sources
11793                                .binary_search_by(|anchor| {
11794                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11795                                })
11796                        {
11797                            editor.find_all_references_task_sources.remove(i);
11798                        }
11799                    });
11800                }
11801            });
11802
11803            let locations = references.await?;
11804            if locations.is_empty() {
11805                return anyhow::Ok(Navigated::No);
11806            }
11807
11808            workspace.update_in(&mut cx, |workspace, window, cx| {
11809                let title = locations
11810                    .first()
11811                    .as_ref()
11812                    .map(|location| {
11813                        let buffer = location.buffer.read(cx);
11814                        format!(
11815                            "References to `{}`",
11816                            buffer
11817                                .text_for_range(location.range.clone())
11818                                .collect::<String>()
11819                        )
11820                    })
11821                    .unwrap();
11822                Self::open_locations_in_multibuffer(
11823                    workspace,
11824                    locations,
11825                    title,
11826                    false,
11827                    MultibufferSelectionMode::First,
11828                    window,
11829                    cx,
11830                );
11831                Navigated::Yes
11832            })
11833        }))
11834    }
11835
11836    /// Opens a multibuffer with the given project locations in it
11837    pub fn open_locations_in_multibuffer(
11838        workspace: &mut Workspace,
11839        mut locations: Vec<Location>,
11840        title: String,
11841        split: bool,
11842        multibuffer_selection_mode: MultibufferSelectionMode,
11843        window: &mut Window,
11844        cx: &mut Context<Workspace>,
11845    ) {
11846        // If there are multiple definitions, open them in a multibuffer
11847        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11848        let mut locations = locations.into_iter().peekable();
11849        let mut ranges = Vec::new();
11850        let capability = workspace.project().read(cx).capability();
11851
11852        let excerpt_buffer = cx.new(|cx| {
11853            let mut multibuffer = MultiBuffer::new(capability);
11854            while let Some(location) = locations.next() {
11855                let buffer = location.buffer.read(cx);
11856                let mut ranges_for_buffer = Vec::new();
11857                let range = location.range.to_offset(buffer);
11858                ranges_for_buffer.push(range.clone());
11859
11860                while let Some(next_location) = locations.peek() {
11861                    if next_location.buffer == location.buffer {
11862                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11863                        locations.next();
11864                    } else {
11865                        break;
11866                    }
11867                }
11868
11869                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11870                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11871                    location.buffer.clone(),
11872                    ranges_for_buffer,
11873                    DEFAULT_MULTIBUFFER_CONTEXT,
11874                    cx,
11875                ))
11876            }
11877
11878            multibuffer.with_title(title)
11879        });
11880
11881        let editor = cx.new(|cx| {
11882            Editor::for_multibuffer(
11883                excerpt_buffer,
11884                Some(workspace.project().clone()),
11885                true,
11886                window,
11887                cx,
11888            )
11889        });
11890        editor.update(cx, |editor, cx| {
11891            match multibuffer_selection_mode {
11892                MultibufferSelectionMode::First => {
11893                    if let Some(first_range) = ranges.first() {
11894                        editor.change_selections(None, window, cx, |selections| {
11895                            selections.clear_disjoint();
11896                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11897                        });
11898                    }
11899                    editor.highlight_background::<Self>(
11900                        &ranges,
11901                        |theme| theme.editor_highlighted_line_background,
11902                        cx,
11903                    );
11904                }
11905                MultibufferSelectionMode::All => {
11906                    editor.change_selections(None, window, cx, |selections| {
11907                        selections.clear_disjoint();
11908                        selections.select_anchor_ranges(ranges);
11909                    });
11910                }
11911            }
11912            editor.register_buffers_with_language_servers(cx);
11913        });
11914
11915        let item = Box::new(editor);
11916        let item_id = item.item_id();
11917
11918        if split {
11919            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11920        } else {
11921            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11922                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11923                    pane.close_current_preview_item(window, cx)
11924                } else {
11925                    None
11926                }
11927            });
11928            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11929        }
11930        workspace.active_pane().update(cx, |pane, cx| {
11931            pane.set_preview_item_id(Some(item_id), cx);
11932        });
11933    }
11934
11935    pub fn rename(
11936        &mut self,
11937        _: &Rename,
11938        window: &mut Window,
11939        cx: &mut Context<Self>,
11940    ) -> Option<Task<Result<()>>> {
11941        use language::ToOffset as _;
11942
11943        let provider = self.semantics_provider.clone()?;
11944        let selection = self.selections.newest_anchor().clone();
11945        let (cursor_buffer, cursor_buffer_position) = self
11946            .buffer
11947            .read(cx)
11948            .text_anchor_for_position(selection.head(), cx)?;
11949        let (tail_buffer, cursor_buffer_position_end) = self
11950            .buffer
11951            .read(cx)
11952            .text_anchor_for_position(selection.tail(), cx)?;
11953        if tail_buffer != cursor_buffer {
11954            return None;
11955        }
11956
11957        let snapshot = cursor_buffer.read(cx).snapshot();
11958        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11959        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11960        let prepare_rename = provider
11961            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11962            .unwrap_or_else(|| Task::ready(Ok(None)));
11963        drop(snapshot);
11964
11965        Some(cx.spawn_in(window, |this, mut cx| async move {
11966            let rename_range = if let Some(range) = prepare_rename.await? {
11967                Some(range)
11968            } else {
11969                this.update(&mut cx, |this, cx| {
11970                    let buffer = this.buffer.read(cx).snapshot(cx);
11971                    let mut buffer_highlights = this
11972                        .document_highlights_for_position(selection.head(), &buffer)
11973                        .filter(|highlight| {
11974                            highlight.start.excerpt_id == selection.head().excerpt_id
11975                                && highlight.end.excerpt_id == selection.head().excerpt_id
11976                        });
11977                    buffer_highlights
11978                        .next()
11979                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11980                })?
11981            };
11982            if let Some(rename_range) = rename_range {
11983                this.update_in(&mut cx, |this, window, cx| {
11984                    let snapshot = cursor_buffer.read(cx).snapshot();
11985                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11986                    let cursor_offset_in_rename_range =
11987                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11988                    let cursor_offset_in_rename_range_end =
11989                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11990
11991                    this.take_rename(false, window, cx);
11992                    let buffer = this.buffer.read(cx).read(cx);
11993                    let cursor_offset = selection.head().to_offset(&buffer);
11994                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11995                    let rename_end = rename_start + rename_buffer_range.len();
11996                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11997                    let mut old_highlight_id = None;
11998                    let old_name: Arc<str> = buffer
11999                        .chunks(rename_start..rename_end, true)
12000                        .map(|chunk| {
12001                            if old_highlight_id.is_none() {
12002                                old_highlight_id = chunk.syntax_highlight_id;
12003                            }
12004                            chunk.text
12005                        })
12006                        .collect::<String>()
12007                        .into();
12008
12009                    drop(buffer);
12010
12011                    // Position the selection in the rename editor so that it matches the current selection.
12012                    this.show_local_selections = false;
12013                    let rename_editor = cx.new(|cx| {
12014                        let mut editor = Editor::single_line(window, cx);
12015                        editor.buffer.update(cx, |buffer, cx| {
12016                            buffer.edit([(0..0, old_name.clone())], None, cx)
12017                        });
12018                        let rename_selection_range = match cursor_offset_in_rename_range
12019                            .cmp(&cursor_offset_in_rename_range_end)
12020                        {
12021                            Ordering::Equal => {
12022                                editor.select_all(&SelectAll, window, cx);
12023                                return editor;
12024                            }
12025                            Ordering::Less => {
12026                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12027                            }
12028                            Ordering::Greater => {
12029                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12030                            }
12031                        };
12032                        if rename_selection_range.end > old_name.len() {
12033                            editor.select_all(&SelectAll, window, cx);
12034                        } else {
12035                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12036                                s.select_ranges([rename_selection_range]);
12037                            });
12038                        }
12039                        editor
12040                    });
12041                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12042                        if e == &EditorEvent::Focused {
12043                            cx.emit(EditorEvent::FocusedIn)
12044                        }
12045                    })
12046                    .detach();
12047
12048                    let write_highlights =
12049                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12050                    let read_highlights =
12051                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12052                    let ranges = write_highlights
12053                        .iter()
12054                        .flat_map(|(_, ranges)| ranges.iter())
12055                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12056                        .cloned()
12057                        .collect();
12058
12059                    this.highlight_text::<Rename>(
12060                        ranges,
12061                        HighlightStyle {
12062                            fade_out: Some(0.6),
12063                            ..Default::default()
12064                        },
12065                        cx,
12066                    );
12067                    let rename_focus_handle = rename_editor.focus_handle(cx);
12068                    window.focus(&rename_focus_handle);
12069                    let block_id = this.insert_blocks(
12070                        [BlockProperties {
12071                            style: BlockStyle::Flex,
12072                            placement: BlockPlacement::Below(range.start),
12073                            height: 1,
12074                            render: Arc::new({
12075                                let rename_editor = rename_editor.clone();
12076                                move |cx: &mut BlockContext| {
12077                                    let mut text_style = cx.editor_style.text.clone();
12078                                    if let Some(highlight_style) = old_highlight_id
12079                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12080                                    {
12081                                        text_style = text_style.highlight(highlight_style);
12082                                    }
12083                                    div()
12084                                        .block_mouse_down()
12085                                        .pl(cx.anchor_x)
12086                                        .child(EditorElement::new(
12087                                            &rename_editor,
12088                                            EditorStyle {
12089                                                background: cx.theme().system().transparent,
12090                                                local_player: cx.editor_style.local_player,
12091                                                text: text_style,
12092                                                scrollbar_width: cx.editor_style.scrollbar_width,
12093                                                syntax: cx.editor_style.syntax.clone(),
12094                                                status: cx.editor_style.status.clone(),
12095                                                inlay_hints_style: HighlightStyle {
12096                                                    font_weight: Some(FontWeight::BOLD),
12097                                                    ..make_inlay_hints_style(cx.app)
12098                                                },
12099                                                inline_completion_styles: make_suggestion_styles(
12100                                                    cx.app,
12101                                                ),
12102                                                ..EditorStyle::default()
12103                                            },
12104                                        ))
12105                                        .into_any_element()
12106                                }
12107                            }),
12108                            priority: 0,
12109                        }],
12110                        Some(Autoscroll::fit()),
12111                        cx,
12112                    )[0];
12113                    this.pending_rename = Some(RenameState {
12114                        range,
12115                        old_name,
12116                        editor: rename_editor,
12117                        block_id,
12118                    });
12119                })?;
12120            }
12121
12122            Ok(())
12123        }))
12124    }
12125
12126    pub fn confirm_rename(
12127        &mut self,
12128        _: &ConfirmRename,
12129        window: &mut Window,
12130        cx: &mut Context<Self>,
12131    ) -> Option<Task<Result<()>>> {
12132        let rename = self.take_rename(false, window, cx)?;
12133        let workspace = self.workspace()?.downgrade();
12134        let (buffer, start) = self
12135            .buffer
12136            .read(cx)
12137            .text_anchor_for_position(rename.range.start, cx)?;
12138        let (end_buffer, _) = self
12139            .buffer
12140            .read(cx)
12141            .text_anchor_for_position(rename.range.end, cx)?;
12142        if buffer != end_buffer {
12143            return None;
12144        }
12145
12146        let old_name = rename.old_name;
12147        let new_name = rename.editor.read(cx).text(cx);
12148
12149        let rename = self.semantics_provider.as_ref()?.perform_rename(
12150            &buffer,
12151            start,
12152            new_name.clone(),
12153            cx,
12154        )?;
12155
12156        Some(cx.spawn_in(window, |editor, mut cx| async move {
12157            let project_transaction = rename.await?;
12158            Self::open_project_transaction(
12159                &editor,
12160                workspace,
12161                project_transaction,
12162                format!("Rename: {}{}", old_name, new_name),
12163                cx.clone(),
12164            )
12165            .await?;
12166
12167            editor.update(&mut cx, |editor, cx| {
12168                editor.refresh_document_highlights(cx);
12169            })?;
12170            Ok(())
12171        }))
12172    }
12173
12174    fn take_rename(
12175        &mut self,
12176        moving_cursor: bool,
12177        window: &mut Window,
12178        cx: &mut Context<Self>,
12179    ) -> Option<RenameState> {
12180        let rename = self.pending_rename.take()?;
12181        if rename.editor.focus_handle(cx).is_focused(window) {
12182            window.focus(&self.focus_handle);
12183        }
12184
12185        self.remove_blocks(
12186            [rename.block_id].into_iter().collect(),
12187            Some(Autoscroll::fit()),
12188            cx,
12189        );
12190        self.clear_highlights::<Rename>(cx);
12191        self.show_local_selections = true;
12192
12193        if moving_cursor {
12194            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12195                editor.selections.newest::<usize>(cx).head()
12196            });
12197
12198            // Update the selection to match the position of the selection inside
12199            // the rename editor.
12200            let snapshot = self.buffer.read(cx).read(cx);
12201            let rename_range = rename.range.to_offset(&snapshot);
12202            let cursor_in_editor = snapshot
12203                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12204                .min(rename_range.end);
12205            drop(snapshot);
12206
12207            self.change_selections(None, window, cx, |s| {
12208                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12209            });
12210        } else {
12211            self.refresh_document_highlights(cx);
12212        }
12213
12214        Some(rename)
12215    }
12216
12217    pub fn pending_rename(&self) -> Option<&RenameState> {
12218        self.pending_rename.as_ref()
12219    }
12220
12221    fn format(
12222        &mut self,
12223        _: &Format,
12224        window: &mut Window,
12225        cx: &mut Context<Self>,
12226    ) -> Option<Task<Result<()>>> {
12227        let project = match &self.project {
12228            Some(project) => project.clone(),
12229            None => return None,
12230        };
12231
12232        Some(self.perform_format(
12233            project,
12234            FormatTrigger::Manual,
12235            FormatTarget::Buffers,
12236            window,
12237            cx,
12238        ))
12239    }
12240
12241    fn format_selections(
12242        &mut self,
12243        _: &FormatSelections,
12244        window: &mut Window,
12245        cx: &mut Context<Self>,
12246    ) -> Option<Task<Result<()>>> {
12247        let project = match &self.project {
12248            Some(project) => project.clone(),
12249            None => return None,
12250        };
12251
12252        let ranges = self
12253            .selections
12254            .all_adjusted(cx)
12255            .into_iter()
12256            .map(|selection| selection.range())
12257            .collect_vec();
12258
12259        Some(self.perform_format(
12260            project,
12261            FormatTrigger::Manual,
12262            FormatTarget::Ranges(ranges),
12263            window,
12264            cx,
12265        ))
12266    }
12267
12268    fn perform_format(
12269        &mut self,
12270        project: Entity<Project>,
12271        trigger: FormatTrigger,
12272        target: FormatTarget,
12273        window: &mut Window,
12274        cx: &mut Context<Self>,
12275    ) -> Task<Result<()>> {
12276        let buffer = self.buffer.clone();
12277        let (buffers, target) = match target {
12278            FormatTarget::Buffers => {
12279                let mut buffers = buffer.read(cx).all_buffers();
12280                if trigger == FormatTrigger::Save {
12281                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12282                }
12283                (buffers, LspFormatTarget::Buffers)
12284            }
12285            FormatTarget::Ranges(selection_ranges) => {
12286                let multi_buffer = buffer.read(cx);
12287                let snapshot = multi_buffer.read(cx);
12288                let mut buffers = HashSet::default();
12289                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12290                    BTreeMap::new();
12291                for selection_range in selection_ranges {
12292                    for (buffer, buffer_range, _) in
12293                        snapshot.range_to_buffer_ranges(selection_range)
12294                    {
12295                        let buffer_id = buffer.remote_id();
12296                        let start = buffer.anchor_before(buffer_range.start);
12297                        let end = buffer.anchor_after(buffer_range.end);
12298                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12299                        buffer_id_to_ranges
12300                            .entry(buffer_id)
12301                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12302                            .or_insert_with(|| vec![start..end]);
12303                    }
12304                }
12305                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12306            }
12307        };
12308
12309        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12310        let format = project.update(cx, |project, cx| {
12311            project.format(buffers, target, true, trigger, cx)
12312        });
12313
12314        cx.spawn_in(window, |_, mut cx| async move {
12315            let transaction = futures::select_biased! {
12316                () = timeout => {
12317                    log::warn!("timed out waiting for formatting");
12318                    None
12319                }
12320                transaction = format.log_err().fuse() => transaction,
12321            };
12322
12323            buffer
12324                .update(&mut cx, |buffer, cx| {
12325                    if let Some(transaction) = transaction {
12326                        if !buffer.is_singleton() {
12327                            buffer.push_transaction(&transaction.0, cx);
12328                        }
12329                    }
12330
12331                    cx.notify();
12332                })
12333                .ok();
12334
12335            Ok(())
12336        })
12337    }
12338
12339    fn restart_language_server(
12340        &mut self,
12341        _: &RestartLanguageServer,
12342        _: &mut Window,
12343        cx: &mut Context<Self>,
12344    ) {
12345        if let Some(project) = self.project.clone() {
12346            self.buffer.update(cx, |multi_buffer, cx| {
12347                project.update(cx, |project, cx| {
12348                    project.restart_language_servers_for_buffers(
12349                        multi_buffer.all_buffers().into_iter().collect(),
12350                        cx,
12351                    );
12352                });
12353            })
12354        }
12355    }
12356
12357    fn cancel_language_server_work(
12358        workspace: &mut Workspace,
12359        _: &actions::CancelLanguageServerWork,
12360        _: &mut Window,
12361        cx: &mut Context<Workspace>,
12362    ) {
12363        let project = workspace.project();
12364        let buffers = workspace
12365            .active_item(cx)
12366            .and_then(|item| item.act_as::<Editor>(cx))
12367            .map_or(HashSet::default(), |editor| {
12368                editor.read(cx).buffer.read(cx).all_buffers()
12369            });
12370        project.update(cx, |project, cx| {
12371            project.cancel_language_server_work_for_buffers(buffers, cx);
12372        });
12373    }
12374
12375    fn show_character_palette(
12376        &mut self,
12377        _: &ShowCharacterPalette,
12378        window: &mut Window,
12379        _: &mut Context<Self>,
12380    ) {
12381        window.show_character_palette();
12382    }
12383
12384    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12385        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12386            let buffer = self.buffer.read(cx).snapshot(cx);
12387            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12388            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12389            let is_valid = buffer
12390                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12391                .any(|entry| {
12392                    entry.diagnostic.is_primary
12393                        && !entry.range.is_empty()
12394                        && entry.range.start == primary_range_start
12395                        && entry.diagnostic.message == active_diagnostics.primary_message
12396                });
12397
12398            if is_valid != active_diagnostics.is_valid {
12399                active_diagnostics.is_valid = is_valid;
12400                let mut new_styles = HashMap::default();
12401                for (block_id, diagnostic) in &active_diagnostics.blocks {
12402                    new_styles.insert(
12403                        *block_id,
12404                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
12405                    );
12406                }
12407                self.display_map.update(cx, |display_map, _cx| {
12408                    display_map.replace_blocks(new_styles)
12409                });
12410            }
12411        }
12412    }
12413
12414    fn activate_diagnostics(
12415        &mut self,
12416        buffer_id: BufferId,
12417        group_id: usize,
12418        window: &mut Window,
12419        cx: &mut Context<Self>,
12420    ) {
12421        self.dismiss_diagnostics(cx);
12422        let snapshot = self.snapshot(window, cx);
12423        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12424            let buffer = self.buffer.read(cx).snapshot(cx);
12425
12426            let mut primary_range = None;
12427            let mut primary_message = None;
12428            let diagnostic_group = buffer
12429                .diagnostic_group(buffer_id, group_id)
12430                .filter_map(|entry| {
12431                    let start = entry.range.start;
12432                    let end = entry.range.end;
12433                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12434                        && (start.row == end.row
12435                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12436                    {
12437                        return None;
12438                    }
12439                    if entry.diagnostic.is_primary {
12440                        primary_range = Some(entry.range.clone());
12441                        primary_message = Some(entry.diagnostic.message.clone());
12442                    }
12443                    Some(entry)
12444                })
12445                .collect::<Vec<_>>();
12446            let primary_range = primary_range?;
12447            let primary_message = primary_message?;
12448
12449            let blocks = display_map
12450                .insert_blocks(
12451                    diagnostic_group.iter().map(|entry| {
12452                        let diagnostic = entry.diagnostic.clone();
12453                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12454                        BlockProperties {
12455                            style: BlockStyle::Fixed,
12456                            placement: BlockPlacement::Below(
12457                                buffer.anchor_after(entry.range.start),
12458                            ),
12459                            height: message_height,
12460                            render: diagnostic_block_renderer(diagnostic, None, true, true),
12461                            priority: 0,
12462                        }
12463                    }),
12464                    cx,
12465                )
12466                .into_iter()
12467                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12468                .collect();
12469
12470            Some(ActiveDiagnosticGroup {
12471                primary_range: buffer.anchor_before(primary_range.start)
12472                    ..buffer.anchor_after(primary_range.end),
12473                primary_message,
12474                group_id,
12475                blocks,
12476                is_valid: true,
12477            })
12478        });
12479    }
12480
12481    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12482        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12483            self.display_map.update(cx, |display_map, cx| {
12484                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12485            });
12486            cx.notify();
12487        }
12488    }
12489
12490    /// Disable inline diagnostics rendering for this editor.
12491    pub fn disable_inline_diagnostics(&mut self) {
12492        self.inline_diagnostics_enabled = false;
12493        self.inline_diagnostics_update = Task::ready(());
12494        self.inline_diagnostics.clear();
12495    }
12496
12497    pub fn inline_diagnostics_enabled(&self) -> bool {
12498        self.inline_diagnostics_enabled
12499    }
12500
12501    pub fn show_inline_diagnostics(&self) -> bool {
12502        self.show_inline_diagnostics
12503    }
12504
12505    pub fn toggle_inline_diagnostics(
12506        &mut self,
12507        _: &ToggleInlineDiagnostics,
12508        window: &mut Window,
12509        cx: &mut Context<'_, Editor>,
12510    ) {
12511        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12512        self.refresh_inline_diagnostics(false, window, cx);
12513    }
12514
12515    fn refresh_inline_diagnostics(
12516        &mut self,
12517        debounce: bool,
12518        window: &mut Window,
12519        cx: &mut Context<Self>,
12520    ) {
12521        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12522            self.inline_diagnostics_update = Task::ready(());
12523            self.inline_diagnostics.clear();
12524            return;
12525        }
12526
12527        let debounce_ms = ProjectSettings::get_global(cx)
12528            .diagnostics
12529            .inline
12530            .update_debounce_ms;
12531        let debounce = if debounce && debounce_ms > 0 {
12532            Some(Duration::from_millis(debounce_ms))
12533        } else {
12534            None
12535        };
12536        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12537            if let Some(debounce) = debounce {
12538                cx.background_executor().timer(debounce).await;
12539            }
12540            let Some(snapshot) = editor
12541                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12542                .ok()
12543            else {
12544                return;
12545            };
12546
12547            let new_inline_diagnostics = cx
12548                .background_spawn(async move {
12549                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12550                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12551                        let message = diagnostic_entry
12552                            .diagnostic
12553                            .message
12554                            .split_once('\n')
12555                            .map(|(line, _)| line)
12556                            .map(SharedString::new)
12557                            .unwrap_or_else(|| {
12558                                SharedString::from(diagnostic_entry.diagnostic.message)
12559                            });
12560                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12561                        let (Ok(i) | Err(i)) = inline_diagnostics
12562                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12563                        inline_diagnostics.insert(
12564                            i,
12565                            (
12566                                start_anchor,
12567                                InlineDiagnostic {
12568                                    message,
12569                                    group_id: diagnostic_entry.diagnostic.group_id,
12570                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12571                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12572                                    severity: diagnostic_entry.diagnostic.severity,
12573                                },
12574                            ),
12575                        );
12576                    }
12577                    inline_diagnostics
12578                })
12579                .await;
12580
12581            editor
12582                .update(&mut cx, |editor, cx| {
12583                    editor.inline_diagnostics = new_inline_diagnostics;
12584                    cx.notify();
12585                })
12586                .ok();
12587        });
12588    }
12589
12590    pub fn set_selections_from_remote(
12591        &mut self,
12592        selections: Vec<Selection<Anchor>>,
12593        pending_selection: Option<Selection<Anchor>>,
12594        window: &mut Window,
12595        cx: &mut Context<Self>,
12596    ) {
12597        let old_cursor_position = self.selections.newest_anchor().head();
12598        self.selections.change_with(cx, |s| {
12599            s.select_anchors(selections);
12600            if let Some(pending_selection) = pending_selection {
12601                s.set_pending(pending_selection, SelectMode::Character);
12602            } else {
12603                s.clear_pending();
12604            }
12605        });
12606        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12607    }
12608
12609    fn push_to_selection_history(&mut self) {
12610        self.selection_history.push(SelectionHistoryEntry {
12611            selections: self.selections.disjoint_anchors(),
12612            select_next_state: self.select_next_state.clone(),
12613            select_prev_state: self.select_prev_state.clone(),
12614            add_selections_state: self.add_selections_state.clone(),
12615        });
12616    }
12617
12618    pub fn transact(
12619        &mut self,
12620        window: &mut Window,
12621        cx: &mut Context<Self>,
12622        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12623    ) -> Option<TransactionId> {
12624        self.start_transaction_at(Instant::now(), window, cx);
12625        update(self, window, cx);
12626        self.end_transaction_at(Instant::now(), cx)
12627    }
12628
12629    pub fn start_transaction_at(
12630        &mut self,
12631        now: Instant,
12632        window: &mut Window,
12633        cx: &mut Context<Self>,
12634    ) {
12635        self.end_selection(window, cx);
12636        if let Some(tx_id) = self
12637            .buffer
12638            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12639        {
12640            self.selection_history
12641                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12642            cx.emit(EditorEvent::TransactionBegun {
12643                transaction_id: tx_id,
12644            })
12645        }
12646    }
12647
12648    pub fn end_transaction_at(
12649        &mut self,
12650        now: Instant,
12651        cx: &mut Context<Self>,
12652    ) -> Option<TransactionId> {
12653        if let Some(transaction_id) = self
12654            .buffer
12655            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12656        {
12657            if let Some((_, end_selections)) =
12658                self.selection_history.transaction_mut(transaction_id)
12659            {
12660                *end_selections = Some(self.selections.disjoint_anchors());
12661            } else {
12662                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12663            }
12664
12665            cx.emit(EditorEvent::Edited { transaction_id });
12666            Some(transaction_id)
12667        } else {
12668            None
12669        }
12670    }
12671
12672    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12673        if self.selection_mark_mode {
12674            self.change_selections(None, window, cx, |s| {
12675                s.move_with(|_, sel| {
12676                    sel.collapse_to(sel.head(), SelectionGoal::None);
12677                });
12678            })
12679        }
12680        self.selection_mark_mode = true;
12681        cx.notify();
12682    }
12683
12684    pub fn swap_selection_ends(
12685        &mut self,
12686        _: &actions::SwapSelectionEnds,
12687        window: &mut Window,
12688        cx: &mut Context<Self>,
12689    ) {
12690        self.change_selections(None, window, cx, |s| {
12691            s.move_with(|_, sel| {
12692                if sel.start != sel.end {
12693                    sel.reversed = !sel.reversed
12694                }
12695            });
12696        });
12697        self.request_autoscroll(Autoscroll::newest(), cx);
12698        cx.notify();
12699    }
12700
12701    pub fn toggle_fold(
12702        &mut self,
12703        _: &actions::ToggleFold,
12704        window: &mut Window,
12705        cx: &mut Context<Self>,
12706    ) {
12707        if self.is_singleton(cx) {
12708            let selection = self.selections.newest::<Point>(cx);
12709
12710            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12711            let range = if selection.is_empty() {
12712                let point = selection.head().to_display_point(&display_map);
12713                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12714                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12715                    .to_point(&display_map);
12716                start..end
12717            } else {
12718                selection.range()
12719            };
12720            if display_map.folds_in_range(range).next().is_some() {
12721                self.unfold_lines(&Default::default(), window, cx)
12722            } else {
12723                self.fold(&Default::default(), window, cx)
12724            }
12725        } else {
12726            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12727            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12728                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12729                .map(|(snapshot, _, _)| snapshot.remote_id())
12730                .collect();
12731
12732            for buffer_id in buffer_ids {
12733                if self.is_buffer_folded(buffer_id, cx) {
12734                    self.unfold_buffer(buffer_id, cx);
12735                } else {
12736                    self.fold_buffer(buffer_id, cx);
12737                }
12738            }
12739        }
12740    }
12741
12742    pub fn toggle_fold_recursive(
12743        &mut self,
12744        _: &actions::ToggleFoldRecursive,
12745        window: &mut Window,
12746        cx: &mut Context<Self>,
12747    ) {
12748        let selection = self.selections.newest::<Point>(cx);
12749
12750        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12751        let range = if selection.is_empty() {
12752            let point = selection.head().to_display_point(&display_map);
12753            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12754            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12755                .to_point(&display_map);
12756            start..end
12757        } else {
12758            selection.range()
12759        };
12760        if display_map.folds_in_range(range).next().is_some() {
12761            self.unfold_recursive(&Default::default(), window, cx)
12762        } else {
12763            self.fold_recursive(&Default::default(), window, cx)
12764        }
12765    }
12766
12767    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12768        if self.is_singleton(cx) {
12769            let mut to_fold = Vec::new();
12770            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12771            let selections = self.selections.all_adjusted(cx);
12772
12773            for selection in selections {
12774                let range = selection.range().sorted();
12775                let buffer_start_row = range.start.row;
12776
12777                if range.start.row != range.end.row {
12778                    let mut found = false;
12779                    let mut row = range.start.row;
12780                    while row <= range.end.row {
12781                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12782                        {
12783                            found = true;
12784                            row = crease.range().end.row + 1;
12785                            to_fold.push(crease);
12786                        } else {
12787                            row += 1
12788                        }
12789                    }
12790                    if found {
12791                        continue;
12792                    }
12793                }
12794
12795                for row in (0..=range.start.row).rev() {
12796                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12797                        if crease.range().end.row >= buffer_start_row {
12798                            to_fold.push(crease);
12799                            if row <= range.start.row {
12800                                break;
12801                            }
12802                        }
12803                    }
12804                }
12805            }
12806
12807            self.fold_creases(to_fold, true, window, cx);
12808        } else {
12809            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12810
12811            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12812                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12813                .map(|(snapshot, _, _)| snapshot.remote_id())
12814                .collect();
12815            for buffer_id in buffer_ids {
12816                self.fold_buffer(buffer_id, cx);
12817            }
12818        }
12819    }
12820
12821    fn fold_at_level(
12822        &mut self,
12823        fold_at: &FoldAtLevel,
12824        window: &mut Window,
12825        cx: &mut Context<Self>,
12826    ) {
12827        if !self.buffer.read(cx).is_singleton() {
12828            return;
12829        }
12830
12831        let fold_at_level = fold_at.0;
12832        let snapshot = self.buffer.read(cx).snapshot(cx);
12833        let mut to_fold = Vec::new();
12834        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12835
12836        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12837            while start_row < end_row {
12838                match self
12839                    .snapshot(window, cx)
12840                    .crease_for_buffer_row(MultiBufferRow(start_row))
12841                {
12842                    Some(crease) => {
12843                        let nested_start_row = crease.range().start.row + 1;
12844                        let nested_end_row = crease.range().end.row;
12845
12846                        if current_level < fold_at_level {
12847                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12848                        } else if current_level == fold_at_level {
12849                            to_fold.push(crease);
12850                        }
12851
12852                        start_row = nested_end_row + 1;
12853                    }
12854                    None => start_row += 1,
12855                }
12856            }
12857        }
12858
12859        self.fold_creases(to_fold, true, window, cx);
12860    }
12861
12862    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12863        if self.buffer.read(cx).is_singleton() {
12864            let mut fold_ranges = Vec::new();
12865            let snapshot = self.buffer.read(cx).snapshot(cx);
12866
12867            for row in 0..snapshot.max_row().0 {
12868                if let Some(foldable_range) = self
12869                    .snapshot(window, cx)
12870                    .crease_for_buffer_row(MultiBufferRow(row))
12871                {
12872                    fold_ranges.push(foldable_range);
12873                }
12874            }
12875
12876            self.fold_creases(fold_ranges, true, window, cx);
12877        } else {
12878            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12879                editor
12880                    .update_in(&mut cx, |editor, _, cx| {
12881                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12882                            editor.fold_buffer(buffer_id, cx);
12883                        }
12884                    })
12885                    .ok();
12886            });
12887        }
12888    }
12889
12890    pub fn fold_function_bodies(
12891        &mut self,
12892        _: &actions::FoldFunctionBodies,
12893        window: &mut Window,
12894        cx: &mut Context<Self>,
12895    ) {
12896        let snapshot = self.buffer.read(cx).snapshot(cx);
12897
12898        let ranges = snapshot
12899            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12900            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12901            .collect::<Vec<_>>();
12902
12903        let creases = ranges
12904            .into_iter()
12905            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12906            .collect();
12907
12908        self.fold_creases(creases, true, window, cx);
12909    }
12910
12911    pub fn fold_recursive(
12912        &mut self,
12913        _: &actions::FoldRecursive,
12914        window: &mut Window,
12915        cx: &mut Context<Self>,
12916    ) {
12917        let mut to_fold = Vec::new();
12918        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12919        let selections = self.selections.all_adjusted(cx);
12920
12921        for selection in selections {
12922            let range = selection.range().sorted();
12923            let buffer_start_row = range.start.row;
12924
12925            if range.start.row != range.end.row {
12926                let mut found = false;
12927                for row in range.start.row..=range.end.row {
12928                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12929                        found = true;
12930                        to_fold.push(crease);
12931                    }
12932                }
12933                if found {
12934                    continue;
12935                }
12936            }
12937
12938            for row in (0..=range.start.row).rev() {
12939                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12940                    if crease.range().end.row >= buffer_start_row {
12941                        to_fold.push(crease);
12942                    } else {
12943                        break;
12944                    }
12945                }
12946            }
12947        }
12948
12949        self.fold_creases(to_fold, true, window, cx);
12950    }
12951
12952    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12953        let buffer_row = fold_at.buffer_row;
12954        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12955
12956        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12957            let autoscroll = self
12958                .selections
12959                .all::<Point>(cx)
12960                .iter()
12961                .any(|selection| crease.range().overlaps(&selection.range()));
12962
12963            self.fold_creases(vec![crease], autoscroll, window, cx);
12964        }
12965    }
12966
12967    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12968        if self.is_singleton(cx) {
12969            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12970            let buffer = &display_map.buffer_snapshot;
12971            let selections = self.selections.all::<Point>(cx);
12972            let ranges = selections
12973                .iter()
12974                .map(|s| {
12975                    let range = s.display_range(&display_map).sorted();
12976                    let mut start = range.start.to_point(&display_map);
12977                    let mut end = range.end.to_point(&display_map);
12978                    start.column = 0;
12979                    end.column = buffer.line_len(MultiBufferRow(end.row));
12980                    start..end
12981                })
12982                .collect::<Vec<_>>();
12983
12984            self.unfold_ranges(&ranges, true, true, cx);
12985        } else {
12986            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12987            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12988                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12989                .map(|(snapshot, _, _)| snapshot.remote_id())
12990                .collect();
12991            for buffer_id in buffer_ids {
12992                self.unfold_buffer(buffer_id, cx);
12993            }
12994        }
12995    }
12996
12997    pub fn unfold_recursive(
12998        &mut self,
12999        _: &UnfoldRecursive,
13000        _window: &mut Window,
13001        cx: &mut Context<Self>,
13002    ) {
13003        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13004        let selections = self.selections.all::<Point>(cx);
13005        let ranges = selections
13006            .iter()
13007            .map(|s| {
13008                let mut range = s.display_range(&display_map).sorted();
13009                *range.start.column_mut() = 0;
13010                *range.end.column_mut() = display_map.line_len(range.end.row());
13011                let start = range.start.to_point(&display_map);
13012                let end = range.end.to_point(&display_map);
13013                start..end
13014            })
13015            .collect::<Vec<_>>();
13016
13017        self.unfold_ranges(&ranges, true, true, cx);
13018    }
13019
13020    pub fn unfold_at(
13021        &mut self,
13022        unfold_at: &UnfoldAt,
13023        _window: &mut Window,
13024        cx: &mut Context<Self>,
13025    ) {
13026        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13027
13028        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13029            ..Point::new(
13030                unfold_at.buffer_row.0,
13031                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13032            );
13033
13034        let autoscroll = self
13035            .selections
13036            .all::<Point>(cx)
13037            .iter()
13038            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13039
13040        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13041    }
13042
13043    pub fn unfold_all(
13044        &mut self,
13045        _: &actions::UnfoldAll,
13046        _window: &mut Window,
13047        cx: &mut Context<Self>,
13048    ) {
13049        if self.buffer.read(cx).is_singleton() {
13050            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13051            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13052        } else {
13053            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13054                editor
13055                    .update(&mut cx, |editor, cx| {
13056                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13057                            editor.unfold_buffer(buffer_id, cx);
13058                        }
13059                    })
13060                    .ok();
13061            });
13062        }
13063    }
13064
13065    pub fn fold_selected_ranges(
13066        &mut self,
13067        _: &FoldSelectedRanges,
13068        window: &mut Window,
13069        cx: &mut Context<Self>,
13070    ) {
13071        let selections = self.selections.all::<Point>(cx);
13072        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13073        let line_mode = self.selections.line_mode;
13074        let ranges = selections
13075            .into_iter()
13076            .map(|s| {
13077                if line_mode {
13078                    let start = Point::new(s.start.row, 0);
13079                    let end = Point::new(
13080                        s.end.row,
13081                        display_map
13082                            .buffer_snapshot
13083                            .line_len(MultiBufferRow(s.end.row)),
13084                    );
13085                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13086                } else {
13087                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13088                }
13089            })
13090            .collect::<Vec<_>>();
13091        self.fold_creases(ranges, true, window, cx);
13092    }
13093
13094    pub fn fold_ranges<T: ToOffset + Clone>(
13095        &mut self,
13096        ranges: Vec<Range<T>>,
13097        auto_scroll: bool,
13098        window: &mut Window,
13099        cx: &mut Context<Self>,
13100    ) {
13101        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13102        let ranges = ranges
13103            .into_iter()
13104            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13105            .collect::<Vec<_>>();
13106        self.fold_creases(ranges, auto_scroll, window, cx);
13107    }
13108
13109    pub fn fold_creases<T: ToOffset + Clone>(
13110        &mut self,
13111        creases: Vec<Crease<T>>,
13112        auto_scroll: bool,
13113        window: &mut Window,
13114        cx: &mut Context<Self>,
13115    ) {
13116        if creases.is_empty() {
13117            return;
13118        }
13119
13120        let mut buffers_affected = HashSet::default();
13121        let multi_buffer = self.buffer().read(cx);
13122        for crease in &creases {
13123            if let Some((_, buffer, _)) =
13124                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13125            {
13126                buffers_affected.insert(buffer.read(cx).remote_id());
13127            };
13128        }
13129
13130        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13131
13132        if auto_scroll {
13133            self.request_autoscroll(Autoscroll::fit(), cx);
13134        }
13135
13136        cx.notify();
13137
13138        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13139            // Clear diagnostics block when folding a range that contains it.
13140            let snapshot = self.snapshot(window, cx);
13141            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13142                drop(snapshot);
13143                self.active_diagnostics = Some(active_diagnostics);
13144                self.dismiss_diagnostics(cx);
13145            } else {
13146                self.active_diagnostics = Some(active_diagnostics);
13147            }
13148        }
13149
13150        self.scrollbar_marker_state.dirty = true;
13151    }
13152
13153    /// Removes any folds whose ranges intersect any of the given ranges.
13154    pub fn unfold_ranges<T: ToOffset + Clone>(
13155        &mut self,
13156        ranges: &[Range<T>],
13157        inclusive: bool,
13158        auto_scroll: bool,
13159        cx: &mut Context<Self>,
13160    ) {
13161        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13162            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13163        });
13164    }
13165
13166    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13167        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13168            return;
13169        }
13170        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13171        self.display_map
13172            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13173        cx.emit(EditorEvent::BufferFoldToggled {
13174            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13175            folded: true,
13176        });
13177        cx.notify();
13178    }
13179
13180    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13181        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13182            return;
13183        }
13184        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13185        self.display_map.update(cx, |display_map, cx| {
13186            display_map.unfold_buffer(buffer_id, cx);
13187        });
13188        cx.emit(EditorEvent::BufferFoldToggled {
13189            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13190            folded: false,
13191        });
13192        cx.notify();
13193    }
13194
13195    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13196        self.display_map.read(cx).is_buffer_folded(buffer)
13197    }
13198
13199    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13200        self.display_map.read(cx).folded_buffers()
13201    }
13202
13203    /// Removes any folds with the given ranges.
13204    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13205        &mut self,
13206        ranges: &[Range<T>],
13207        type_id: TypeId,
13208        auto_scroll: bool,
13209        cx: &mut Context<Self>,
13210    ) {
13211        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13212            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13213        });
13214    }
13215
13216    fn remove_folds_with<T: ToOffset + Clone>(
13217        &mut self,
13218        ranges: &[Range<T>],
13219        auto_scroll: bool,
13220        cx: &mut Context<Self>,
13221        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13222    ) {
13223        if ranges.is_empty() {
13224            return;
13225        }
13226
13227        let mut buffers_affected = HashSet::default();
13228        let multi_buffer = self.buffer().read(cx);
13229        for range in ranges {
13230            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13231                buffers_affected.insert(buffer.read(cx).remote_id());
13232            };
13233        }
13234
13235        self.display_map.update(cx, update);
13236
13237        if auto_scroll {
13238            self.request_autoscroll(Autoscroll::fit(), cx);
13239        }
13240
13241        cx.notify();
13242        self.scrollbar_marker_state.dirty = true;
13243        self.active_indent_guides_state.dirty = true;
13244    }
13245
13246    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13247        self.display_map.read(cx).fold_placeholder.clone()
13248    }
13249
13250    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13251        self.buffer.update(cx, |buffer, cx| {
13252            buffer.set_all_diff_hunks_expanded(cx);
13253        });
13254    }
13255
13256    pub fn expand_all_diff_hunks(
13257        &mut self,
13258        _: &ExpandAllDiffHunks,
13259        _window: &mut Window,
13260        cx: &mut Context<Self>,
13261    ) {
13262        self.buffer.update(cx, |buffer, cx| {
13263            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13264        });
13265    }
13266
13267    pub fn toggle_selected_diff_hunks(
13268        &mut self,
13269        _: &ToggleSelectedDiffHunks,
13270        _window: &mut Window,
13271        cx: &mut Context<Self>,
13272    ) {
13273        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13274        self.toggle_diff_hunks_in_ranges(ranges, cx);
13275    }
13276
13277    pub fn diff_hunks_in_ranges<'a>(
13278        &'a self,
13279        ranges: &'a [Range<Anchor>],
13280        buffer: &'a MultiBufferSnapshot,
13281    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13282        ranges.iter().flat_map(move |range| {
13283            let end_excerpt_id = range.end.excerpt_id;
13284            let range = range.to_point(buffer);
13285            let mut peek_end = range.end;
13286            if range.end.row < buffer.max_row().0 {
13287                peek_end = Point::new(range.end.row + 1, 0);
13288            }
13289            buffer
13290                .diff_hunks_in_range(range.start..peek_end)
13291                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13292        })
13293    }
13294
13295    pub fn has_stageable_diff_hunks_in_ranges(
13296        &self,
13297        ranges: &[Range<Anchor>],
13298        snapshot: &MultiBufferSnapshot,
13299    ) -> bool {
13300        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13301        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
13302    }
13303
13304    pub fn toggle_staged_selected_diff_hunks(
13305        &mut self,
13306        _: &::git::ToggleStaged,
13307        _window: &mut Window,
13308        cx: &mut Context<Self>,
13309    ) {
13310        let snapshot = self.buffer.read(cx).snapshot(cx);
13311        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13312        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13313        self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
13314    }
13315
13316    pub fn stage_and_next(
13317        &mut self,
13318        _: &::git::StageAndNext,
13319        window: &mut Window,
13320        cx: &mut Context<Self>,
13321    ) {
13322        self.do_stage_or_unstage_and_next(true, window, cx);
13323    }
13324
13325    pub fn unstage_and_next(
13326        &mut self,
13327        _: &::git::UnstageAndNext,
13328        window: &mut Window,
13329        cx: &mut Context<Self>,
13330    ) {
13331        self.do_stage_or_unstage_and_next(false, window, cx);
13332    }
13333
13334    pub fn stage_or_unstage_diff_hunks(
13335        &mut self,
13336        stage: bool,
13337        ranges: &[Range<Anchor>],
13338        cx: &mut Context<Self>,
13339    ) {
13340        let snapshot = self.buffer.read(cx).snapshot(cx);
13341        let Some(project) = &self.project else {
13342            return;
13343        };
13344
13345        let chunk_by = self
13346            .diff_hunks_in_ranges(&ranges, &snapshot)
13347            .chunk_by(|hunk| hunk.buffer_id);
13348        for (buffer_id, hunks) in &chunk_by {
13349            Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
13350        }
13351    }
13352
13353    fn do_stage_or_unstage_and_next(
13354        &mut self,
13355        stage: bool,
13356        window: &mut Window,
13357        cx: &mut Context<Self>,
13358    ) {
13359        let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13360        if ranges.iter().any(|range| range.start != range.end) {
13361            self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13362            return;
13363        }
13364
13365        if !self.buffer().read(cx).is_singleton() {
13366            if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13367                if buffer.read(cx).is_empty() {
13368                    let buffer = buffer.read(cx);
13369                    let Some(file) = buffer.file() else {
13370                        return;
13371                    };
13372                    let project_path = project::ProjectPath {
13373                        worktree_id: file.worktree_id(cx),
13374                        path: file.path().clone(),
13375                    };
13376                    let Some(project) = self.project.as_ref() else {
13377                        return;
13378                    };
13379                    let project = project.read(cx);
13380
13381                    let Some(repo) = project.git_store().read(cx).active_repository() else {
13382                        return;
13383                    };
13384
13385                    repo.update(cx, |repo, cx| {
13386                        let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13387                            return;
13388                        };
13389                        let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13390                            return;
13391                        };
13392                        if stage && status.status == FileStatus::Untracked {
13393                            repo.stage_entries(vec![repo_path], cx)
13394                                .detach_and_log_err(cx);
13395                            return;
13396                        }
13397                    })
13398                }
13399                ranges = vec![multi_buffer::Anchor::range_in_buffer(
13400                    excerpt_id,
13401                    buffer.read(cx).remote_id(),
13402                    range,
13403                )];
13404                self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13405                let snapshot = self.buffer().read(cx).snapshot(cx);
13406                let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13407                if point.row < snapshot.max_row().0 {
13408                    point.row += 1;
13409                    point.column = 0;
13410                    point = snapshot.clip_point(point, Bias::Right);
13411                    self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13412                        s.select_ranges([point..point]);
13413                    })
13414                }
13415                return;
13416            }
13417        }
13418        self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13419        self.go_to_next_hunk(&Default::default(), window, cx);
13420    }
13421
13422    fn do_stage_or_unstage(
13423        project: &Entity<Project>,
13424        stage: bool,
13425        buffer_id: BufferId,
13426        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13427        snapshot: &MultiBufferSnapshot,
13428        cx: &mut Context<Self>,
13429    ) {
13430        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13431            log::debug!("no buffer for id");
13432            return;
13433        };
13434        let buffer_snapshot = buffer.read(cx).snapshot();
13435        let Some((repo, path)) = project
13436            .read(cx)
13437            .repository_and_path_for_buffer_id(buffer_id, cx)
13438        else {
13439            log::debug!("no git repo for buffer id");
13440            return;
13441        };
13442        let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13443            log::debug!("no diff for buffer id");
13444            return;
13445        };
13446        let Some(secondary_diff) = diff.secondary_diff() else {
13447            log::debug!("no secondary diff for buffer id");
13448            return;
13449        };
13450
13451        let edits = diff.secondary_edits_for_stage_or_unstage(
13452            stage,
13453            hunks.filter_map(|hunk| {
13454                if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13455                    return None;
13456                } else if !stage
13457                    && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13458                {
13459                    return None;
13460                }
13461                Some((
13462                    hunk.diff_base_byte_range.clone(),
13463                    hunk.secondary_diff_base_byte_range.clone(),
13464                    hunk.buffer_range.clone(),
13465                ))
13466            }),
13467            &buffer_snapshot,
13468        );
13469
13470        let Some(index_base) = secondary_diff
13471            .base_text()
13472            .map(|snapshot| snapshot.text.as_rope().clone())
13473        else {
13474            log::debug!("no index base");
13475            return;
13476        };
13477        let index_buffer = cx.new(|cx| {
13478            Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
13479        });
13480        let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
13481            index_buffer.edit(edits, None, cx);
13482            index_buffer.snapshot().as_rope().to_string()
13483        });
13484        let new_index_text = if new_index_text.is_empty()
13485            && !stage
13486            && (diff.is_single_insertion
13487                || buffer_snapshot
13488                    .file()
13489                    .map_or(false, |file| file.disk_state() == DiskState::New))
13490        {
13491            log::debug!("removing from index");
13492            None
13493        } else {
13494            Some(new_index_text)
13495        };
13496        let buffer_store = project.read(cx).buffer_store().clone();
13497        buffer_store
13498            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13499            .detach_and_log_err(cx);
13500
13501        cx.background_spawn(
13502            repo.read(cx)
13503                .set_index_text(&path, new_index_text)
13504                .log_err(),
13505        )
13506        .detach();
13507    }
13508
13509    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13510        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13511        self.buffer
13512            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13513    }
13514
13515    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13516        self.buffer.update(cx, |buffer, cx| {
13517            let ranges = vec![Anchor::min()..Anchor::max()];
13518            if !buffer.all_diff_hunks_expanded()
13519                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13520            {
13521                buffer.collapse_diff_hunks(ranges, cx);
13522                true
13523            } else {
13524                false
13525            }
13526        })
13527    }
13528
13529    fn toggle_diff_hunks_in_ranges(
13530        &mut self,
13531        ranges: Vec<Range<Anchor>>,
13532        cx: &mut Context<'_, Editor>,
13533    ) {
13534        self.buffer.update(cx, |buffer, cx| {
13535            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13536            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13537        })
13538    }
13539
13540    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13541        self.buffer.update(cx, |buffer, cx| {
13542            let snapshot = buffer.snapshot(cx);
13543            let excerpt_id = range.end.excerpt_id;
13544            let point_range = range.to_point(&snapshot);
13545            let expand = !buffer.single_hunk_is_expanded(range, cx);
13546            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13547        })
13548    }
13549
13550    pub(crate) fn apply_all_diff_hunks(
13551        &mut self,
13552        _: &ApplyAllDiffHunks,
13553        window: &mut Window,
13554        cx: &mut Context<Self>,
13555    ) {
13556        let buffers = self.buffer.read(cx).all_buffers();
13557        for branch_buffer in buffers {
13558            branch_buffer.update(cx, |branch_buffer, cx| {
13559                branch_buffer.merge_into_base(Vec::new(), cx);
13560            });
13561        }
13562
13563        if let Some(project) = self.project.clone() {
13564            self.save(true, project, window, cx).detach_and_log_err(cx);
13565        }
13566    }
13567
13568    pub(crate) fn apply_selected_diff_hunks(
13569        &mut self,
13570        _: &ApplyDiffHunk,
13571        window: &mut Window,
13572        cx: &mut Context<Self>,
13573    ) {
13574        let snapshot = self.snapshot(window, cx);
13575        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13576        let mut ranges_by_buffer = HashMap::default();
13577        self.transact(window, cx, |editor, _window, cx| {
13578            for hunk in hunks {
13579                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13580                    ranges_by_buffer
13581                        .entry(buffer.clone())
13582                        .or_insert_with(Vec::new)
13583                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13584                }
13585            }
13586
13587            for (buffer, ranges) in ranges_by_buffer {
13588                buffer.update(cx, |buffer, cx| {
13589                    buffer.merge_into_base(ranges, cx);
13590                });
13591            }
13592        });
13593
13594        if let Some(project) = self.project.clone() {
13595            self.save(true, project, window, cx).detach_and_log_err(cx);
13596        }
13597    }
13598
13599    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13600        if hovered != self.gutter_hovered {
13601            self.gutter_hovered = hovered;
13602            cx.notify();
13603        }
13604    }
13605
13606    pub fn insert_blocks(
13607        &mut self,
13608        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13609        autoscroll: Option<Autoscroll>,
13610        cx: &mut Context<Self>,
13611    ) -> Vec<CustomBlockId> {
13612        let blocks = self
13613            .display_map
13614            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13615        if let Some(autoscroll) = autoscroll {
13616            self.request_autoscroll(autoscroll, cx);
13617        }
13618        cx.notify();
13619        blocks
13620    }
13621
13622    pub fn resize_blocks(
13623        &mut self,
13624        heights: HashMap<CustomBlockId, u32>,
13625        autoscroll: Option<Autoscroll>,
13626        cx: &mut Context<Self>,
13627    ) {
13628        self.display_map
13629            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13630        if let Some(autoscroll) = autoscroll {
13631            self.request_autoscroll(autoscroll, cx);
13632        }
13633        cx.notify();
13634    }
13635
13636    pub fn replace_blocks(
13637        &mut self,
13638        renderers: HashMap<CustomBlockId, RenderBlock>,
13639        autoscroll: Option<Autoscroll>,
13640        cx: &mut Context<Self>,
13641    ) {
13642        self.display_map
13643            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13644        if let Some(autoscroll) = autoscroll {
13645            self.request_autoscroll(autoscroll, cx);
13646        }
13647        cx.notify();
13648    }
13649
13650    pub fn remove_blocks(
13651        &mut self,
13652        block_ids: HashSet<CustomBlockId>,
13653        autoscroll: Option<Autoscroll>,
13654        cx: &mut Context<Self>,
13655    ) {
13656        self.display_map.update(cx, |display_map, cx| {
13657            display_map.remove_blocks(block_ids, cx)
13658        });
13659        if let Some(autoscroll) = autoscroll {
13660            self.request_autoscroll(autoscroll, cx);
13661        }
13662        cx.notify();
13663    }
13664
13665    pub fn row_for_block(
13666        &self,
13667        block_id: CustomBlockId,
13668        cx: &mut Context<Self>,
13669    ) -> Option<DisplayRow> {
13670        self.display_map
13671            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13672    }
13673
13674    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13675        self.focused_block = Some(focused_block);
13676    }
13677
13678    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13679        self.focused_block.take()
13680    }
13681
13682    pub fn insert_creases(
13683        &mut self,
13684        creases: impl IntoIterator<Item = Crease<Anchor>>,
13685        cx: &mut Context<Self>,
13686    ) -> Vec<CreaseId> {
13687        self.display_map
13688            .update(cx, |map, cx| map.insert_creases(creases, cx))
13689    }
13690
13691    pub fn remove_creases(
13692        &mut self,
13693        ids: impl IntoIterator<Item = CreaseId>,
13694        cx: &mut Context<Self>,
13695    ) {
13696        self.display_map
13697            .update(cx, |map, cx| map.remove_creases(ids, cx));
13698    }
13699
13700    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13701        self.display_map
13702            .update(cx, |map, cx| map.snapshot(cx))
13703            .longest_row()
13704    }
13705
13706    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13707        self.display_map
13708            .update(cx, |map, cx| map.snapshot(cx))
13709            .max_point()
13710    }
13711
13712    pub fn text(&self, cx: &App) -> String {
13713        self.buffer.read(cx).read(cx).text()
13714    }
13715
13716    pub fn is_empty(&self, cx: &App) -> bool {
13717        self.buffer.read(cx).read(cx).is_empty()
13718    }
13719
13720    pub fn text_option(&self, cx: &App) -> Option<String> {
13721        let text = self.text(cx);
13722        let text = text.trim();
13723
13724        if text.is_empty() {
13725            return None;
13726        }
13727
13728        Some(text.to_string())
13729    }
13730
13731    pub fn set_text(
13732        &mut self,
13733        text: impl Into<Arc<str>>,
13734        window: &mut Window,
13735        cx: &mut Context<Self>,
13736    ) {
13737        self.transact(window, cx, |this, _, cx| {
13738            this.buffer
13739                .read(cx)
13740                .as_singleton()
13741                .expect("you can only call set_text on editors for singleton buffers")
13742                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13743        });
13744    }
13745
13746    pub fn display_text(&self, cx: &mut App) -> String {
13747        self.display_map
13748            .update(cx, |map, cx| map.snapshot(cx))
13749            .text()
13750    }
13751
13752    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13753        let mut wrap_guides = smallvec::smallvec![];
13754
13755        if self.show_wrap_guides == Some(false) {
13756            return wrap_guides;
13757        }
13758
13759        let settings = self.buffer.read(cx).settings_at(0, cx);
13760        if settings.show_wrap_guides {
13761            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13762                wrap_guides.push((soft_wrap as usize, true));
13763            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13764                wrap_guides.push((soft_wrap as usize, true));
13765            }
13766            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13767        }
13768
13769        wrap_guides
13770    }
13771
13772    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13773        let settings = self.buffer.read(cx).settings_at(0, cx);
13774        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13775        match mode {
13776            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13777                SoftWrap::None
13778            }
13779            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13780            language_settings::SoftWrap::PreferredLineLength => {
13781                SoftWrap::Column(settings.preferred_line_length)
13782            }
13783            language_settings::SoftWrap::Bounded => {
13784                SoftWrap::Bounded(settings.preferred_line_length)
13785            }
13786        }
13787    }
13788
13789    pub fn set_soft_wrap_mode(
13790        &mut self,
13791        mode: language_settings::SoftWrap,
13792
13793        cx: &mut Context<Self>,
13794    ) {
13795        self.soft_wrap_mode_override = Some(mode);
13796        cx.notify();
13797    }
13798
13799    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13800        self.text_style_refinement = Some(style);
13801    }
13802
13803    /// called by the Element so we know what style we were most recently rendered with.
13804    pub(crate) fn set_style(
13805        &mut self,
13806        style: EditorStyle,
13807        window: &mut Window,
13808        cx: &mut Context<Self>,
13809    ) {
13810        let rem_size = window.rem_size();
13811        self.display_map.update(cx, |map, cx| {
13812            map.set_font(
13813                style.text.font(),
13814                style.text.font_size.to_pixels(rem_size),
13815                cx,
13816            )
13817        });
13818        self.style = Some(style);
13819    }
13820
13821    pub fn style(&self) -> Option<&EditorStyle> {
13822        self.style.as_ref()
13823    }
13824
13825    // Called by the element. This method is not designed to be called outside of the editor
13826    // element's layout code because it does not notify when rewrapping is computed synchronously.
13827    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13828        self.display_map
13829            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13830    }
13831
13832    pub fn set_soft_wrap(&mut self) {
13833        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13834    }
13835
13836    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13837        if self.soft_wrap_mode_override.is_some() {
13838            self.soft_wrap_mode_override.take();
13839        } else {
13840            let soft_wrap = match self.soft_wrap_mode(cx) {
13841                SoftWrap::GitDiff => return,
13842                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13843                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13844                    language_settings::SoftWrap::None
13845                }
13846            };
13847            self.soft_wrap_mode_override = Some(soft_wrap);
13848        }
13849        cx.notify();
13850    }
13851
13852    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13853        let Some(workspace) = self.workspace() else {
13854            return;
13855        };
13856        let fs = workspace.read(cx).app_state().fs.clone();
13857        let current_show = TabBarSettings::get_global(cx).show;
13858        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13859            setting.show = Some(!current_show);
13860        });
13861    }
13862
13863    pub fn toggle_indent_guides(
13864        &mut self,
13865        _: &ToggleIndentGuides,
13866        _: &mut Window,
13867        cx: &mut Context<Self>,
13868    ) {
13869        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13870            self.buffer
13871                .read(cx)
13872                .settings_at(0, cx)
13873                .indent_guides
13874                .enabled
13875        });
13876        self.show_indent_guides = Some(!currently_enabled);
13877        cx.notify();
13878    }
13879
13880    fn should_show_indent_guides(&self) -> Option<bool> {
13881        self.show_indent_guides
13882    }
13883
13884    pub fn toggle_line_numbers(
13885        &mut self,
13886        _: &ToggleLineNumbers,
13887        _: &mut Window,
13888        cx: &mut Context<Self>,
13889    ) {
13890        let mut editor_settings = EditorSettings::get_global(cx).clone();
13891        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13892        EditorSettings::override_global(editor_settings, cx);
13893    }
13894
13895    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13896        self.use_relative_line_numbers
13897            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13898    }
13899
13900    pub fn toggle_relative_line_numbers(
13901        &mut self,
13902        _: &ToggleRelativeLineNumbers,
13903        _: &mut Window,
13904        cx: &mut Context<Self>,
13905    ) {
13906        let is_relative = self.should_use_relative_line_numbers(cx);
13907        self.set_relative_line_number(Some(!is_relative), cx)
13908    }
13909
13910    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13911        self.use_relative_line_numbers = is_relative;
13912        cx.notify();
13913    }
13914
13915    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13916        self.show_gutter = show_gutter;
13917        cx.notify();
13918    }
13919
13920    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13921        self.show_scrollbars = show_scrollbars;
13922        cx.notify();
13923    }
13924
13925    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13926        self.show_line_numbers = Some(show_line_numbers);
13927        cx.notify();
13928    }
13929
13930    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13931        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13932        cx.notify();
13933    }
13934
13935    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13936        self.show_code_actions = Some(show_code_actions);
13937        cx.notify();
13938    }
13939
13940    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13941        self.show_runnables = Some(show_runnables);
13942        cx.notify();
13943    }
13944
13945    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13946        if self.display_map.read(cx).masked != masked {
13947            self.display_map.update(cx, |map, _| map.masked = masked);
13948        }
13949        cx.notify()
13950    }
13951
13952    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13953        self.show_wrap_guides = Some(show_wrap_guides);
13954        cx.notify();
13955    }
13956
13957    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13958        self.show_indent_guides = Some(show_indent_guides);
13959        cx.notify();
13960    }
13961
13962    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13963        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13964            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13965                if let Some(dir) = file.abs_path(cx).parent() {
13966                    return Some(dir.to_owned());
13967                }
13968            }
13969
13970            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13971                return Some(project_path.path.to_path_buf());
13972            }
13973        }
13974
13975        None
13976    }
13977
13978    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13979        self.active_excerpt(cx)?
13980            .1
13981            .read(cx)
13982            .file()
13983            .and_then(|f| f.as_local())
13984    }
13985
13986    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13987        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13988            let buffer = buffer.read(cx);
13989            if let Some(project_path) = buffer.project_path(cx) {
13990                let project = self.project.as_ref()?.read(cx);
13991                project.absolute_path(&project_path, cx)
13992            } else {
13993                buffer
13994                    .file()
13995                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13996            }
13997        })
13998    }
13999
14000    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14001        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14002            let project_path = buffer.read(cx).project_path(cx)?;
14003            let project = self.project.as_ref()?.read(cx);
14004            let entry = project.entry_for_path(&project_path, cx)?;
14005            let path = entry.path.to_path_buf();
14006            Some(path)
14007        })
14008    }
14009
14010    pub fn reveal_in_finder(
14011        &mut self,
14012        _: &RevealInFileManager,
14013        _window: &mut Window,
14014        cx: &mut Context<Self>,
14015    ) {
14016        if let Some(target) = self.target_file(cx) {
14017            cx.reveal_path(&target.abs_path(cx));
14018        }
14019    }
14020
14021    pub fn copy_path(
14022        &mut self,
14023        _: &zed_actions::workspace::CopyPath,
14024        _window: &mut Window,
14025        cx: &mut Context<Self>,
14026    ) {
14027        if let Some(path) = self.target_file_abs_path(cx) {
14028            if let Some(path) = path.to_str() {
14029                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14030            }
14031        }
14032    }
14033
14034    pub fn copy_relative_path(
14035        &mut self,
14036        _: &zed_actions::workspace::CopyRelativePath,
14037        _window: &mut Window,
14038        cx: &mut Context<Self>,
14039    ) {
14040        if let Some(path) = self.target_file_path(cx) {
14041            if let Some(path) = path.to_str() {
14042                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14043            }
14044        }
14045    }
14046
14047    pub fn copy_file_name_without_extension(
14048        &mut self,
14049        _: &CopyFileNameWithoutExtension,
14050        _: &mut Window,
14051        cx: &mut Context<Self>,
14052    ) {
14053        if let Some(file) = self.target_file(cx) {
14054            if let Some(file_stem) = file.path().file_stem() {
14055                if let Some(name) = file_stem.to_str() {
14056                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14057                }
14058            }
14059        }
14060    }
14061
14062    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14063        if let Some(file) = self.target_file(cx) {
14064            if let Some(file_name) = file.path().file_name() {
14065                if let Some(name) = file_name.to_str() {
14066                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14067                }
14068            }
14069        }
14070    }
14071
14072    pub fn toggle_git_blame(
14073        &mut self,
14074        _: &ToggleGitBlame,
14075        window: &mut Window,
14076        cx: &mut Context<Self>,
14077    ) {
14078        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14079
14080        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14081            self.start_git_blame(true, window, cx);
14082        }
14083
14084        cx.notify();
14085    }
14086
14087    pub fn toggle_git_blame_inline(
14088        &mut self,
14089        _: &ToggleGitBlameInline,
14090        window: &mut Window,
14091        cx: &mut Context<Self>,
14092    ) {
14093        self.toggle_git_blame_inline_internal(true, window, cx);
14094        cx.notify();
14095    }
14096
14097    pub fn git_blame_inline_enabled(&self) -> bool {
14098        self.git_blame_inline_enabled
14099    }
14100
14101    pub fn toggle_selection_menu(
14102        &mut self,
14103        _: &ToggleSelectionMenu,
14104        _: &mut Window,
14105        cx: &mut Context<Self>,
14106    ) {
14107        self.show_selection_menu = self
14108            .show_selection_menu
14109            .map(|show_selections_menu| !show_selections_menu)
14110            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14111
14112        cx.notify();
14113    }
14114
14115    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14116        self.show_selection_menu
14117            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14118    }
14119
14120    fn start_git_blame(
14121        &mut self,
14122        user_triggered: bool,
14123        window: &mut Window,
14124        cx: &mut Context<Self>,
14125    ) {
14126        if let Some(project) = self.project.as_ref() {
14127            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14128                return;
14129            };
14130
14131            if buffer.read(cx).file().is_none() {
14132                return;
14133            }
14134
14135            let focused = self.focus_handle(cx).contains_focused(window, cx);
14136
14137            let project = project.clone();
14138            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14139            self.blame_subscription =
14140                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14141            self.blame = Some(blame);
14142        }
14143    }
14144
14145    fn toggle_git_blame_inline_internal(
14146        &mut self,
14147        user_triggered: bool,
14148        window: &mut Window,
14149        cx: &mut Context<Self>,
14150    ) {
14151        if self.git_blame_inline_enabled {
14152            self.git_blame_inline_enabled = false;
14153            self.show_git_blame_inline = false;
14154            self.show_git_blame_inline_delay_task.take();
14155        } else {
14156            self.git_blame_inline_enabled = true;
14157            self.start_git_blame_inline(user_triggered, window, cx);
14158        }
14159
14160        cx.notify();
14161    }
14162
14163    fn start_git_blame_inline(
14164        &mut self,
14165        user_triggered: bool,
14166        window: &mut Window,
14167        cx: &mut Context<Self>,
14168    ) {
14169        self.start_git_blame(user_triggered, window, cx);
14170
14171        if ProjectSettings::get_global(cx)
14172            .git
14173            .inline_blame_delay()
14174            .is_some()
14175        {
14176            self.start_inline_blame_timer(window, cx);
14177        } else {
14178            self.show_git_blame_inline = true
14179        }
14180    }
14181
14182    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14183        self.blame.as_ref()
14184    }
14185
14186    pub fn show_git_blame_gutter(&self) -> bool {
14187        self.show_git_blame_gutter
14188    }
14189
14190    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14191        self.show_git_blame_gutter && self.has_blame_entries(cx)
14192    }
14193
14194    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14195        self.show_git_blame_inline
14196            && (self.focus_handle.is_focused(window)
14197                || self
14198                    .git_blame_inline_tooltip
14199                    .as_ref()
14200                    .and_then(|t| t.upgrade())
14201                    .is_some())
14202            && !self.newest_selection_head_on_empty_line(cx)
14203            && self.has_blame_entries(cx)
14204    }
14205
14206    fn has_blame_entries(&self, cx: &App) -> bool {
14207        self.blame()
14208            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14209    }
14210
14211    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14212        let cursor_anchor = self.selections.newest_anchor().head();
14213
14214        let snapshot = self.buffer.read(cx).snapshot(cx);
14215        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14216
14217        snapshot.line_len(buffer_row) == 0
14218    }
14219
14220    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14221        let buffer_and_selection = maybe!({
14222            let selection = self.selections.newest::<Point>(cx);
14223            let selection_range = selection.range();
14224
14225            let multi_buffer = self.buffer().read(cx);
14226            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14227            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14228
14229            let (buffer, range, _) = if selection.reversed {
14230                buffer_ranges.first()
14231            } else {
14232                buffer_ranges.last()
14233            }?;
14234
14235            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14236                ..text::ToPoint::to_point(&range.end, &buffer).row;
14237            Some((
14238                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14239                selection,
14240            ))
14241        });
14242
14243        let Some((buffer, selection)) = buffer_and_selection else {
14244            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14245        };
14246
14247        let Some(project) = self.project.as_ref() else {
14248            return Task::ready(Err(anyhow!("editor does not have project")));
14249        };
14250
14251        project.update(cx, |project, cx| {
14252            project.get_permalink_to_line(&buffer, selection, cx)
14253        })
14254    }
14255
14256    pub fn copy_permalink_to_line(
14257        &mut self,
14258        _: &CopyPermalinkToLine,
14259        window: &mut Window,
14260        cx: &mut Context<Self>,
14261    ) {
14262        let permalink_task = self.get_permalink_to_line(cx);
14263        let workspace = self.workspace();
14264
14265        cx.spawn_in(window, |_, mut cx| async move {
14266            match permalink_task.await {
14267                Ok(permalink) => {
14268                    cx.update(|_, cx| {
14269                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14270                    })
14271                    .ok();
14272                }
14273                Err(err) => {
14274                    let message = format!("Failed to copy permalink: {err}");
14275
14276                    Err::<(), anyhow::Error>(err).log_err();
14277
14278                    if let Some(workspace) = workspace {
14279                        workspace
14280                            .update_in(&mut cx, |workspace, _, cx| {
14281                                struct CopyPermalinkToLine;
14282
14283                                workspace.show_toast(
14284                                    Toast::new(
14285                                        NotificationId::unique::<CopyPermalinkToLine>(),
14286                                        message,
14287                                    ),
14288                                    cx,
14289                                )
14290                            })
14291                            .ok();
14292                    }
14293                }
14294            }
14295        })
14296        .detach();
14297    }
14298
14299    pub fn copy_file_location(
14300        &mut self,
14301        _: &CopyFileLocation,
14302        _: &mut Window,
14303        cx: &mut Context<Self>,
14304    ) {
14305        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14306        if let Some(file) = self.target_file(cx) {
14307            if let Some(path) = file.path().to_str() {
14308                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14309            }
14310        }
14311    }
14312
14313    pub fn open_permalink_to_line(
14314        &mut self,
14315        _: &OpenPermalinkToLine,
14316        window: &mut Window,
14317        cx: &mut Context<Self>,
14318    ) {
14319        let permalink_task = self.get_permalink_to_line(cx);
14320        let workspace = self.workspace();
14321
14322        cx.spawn_in(window, |_, mut cx| async move {
14323            match permalink_task.await {
14324                Ok(permalink) => {
14325                    cx.update(|_, cx| {
14326                        cx.open_url(permalink.as_ref());
14327                    })
14328                    .ok();
14329                }
14330                Err(err) => {
14331                    let message = format!("Failed to open permalink: {err}");
14332
14333                    Err::<(), anyhow::Error>(err).log_err();
14334
14335                    if let Some(workspace) = workspace {
14336                        workspace
14337                            .update(&mut cx, |workspace, cx| {
14338                                struct OpenPermalinkToLine;
14339
14340                                workspace.show_toast(
14341                                    Toast::new(
14342                                        NotificationId::unique::<OpenPermalinkToLine>(),
14343                                        message,
14344                                    ),
14345                                    cx,
14346                                )
14347                            })
14348                            .ok();
14349                    }
14350                }
14351            }
14352        })
14353        .detach();
14354    }
14355
14356    pub fn insert_uuid_v4(
14357        &mut self,
14358        _: &InsertUuidV4,
14359        window: &mut Window,
14360        cx: &mut Context<Self>,
14361    ) {
14362        self.insert_uuid(UuidVersion::V4, window, cx);
14363    }
14364
14365    pub fn insert_uuid_v7(
14366        &mut self,
14367        _: &InsertUuidV7,
14368        window: &mut Window,
14369        cx: &mut Context<Self>,
14370    ) {
14371        self.insert_uuid(UuidVersion::V7, window, cx);
14372    }
14373
14374    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14375        self.transact(window, cx, |this, window, cx| {
14376            let edits = this
14377                .selections
14378                .all::<Point>(cx)
14379                .into_iter()
14380                .map(|selection| {
14381                    let uuid = match version {
14382                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14383                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14384                    };
14385
14386                    (selection.range(), uuid.to_string())
14387                });
14388            this.edit(edits, cx);
14389            this.refresh_inline_completion(true, false, window, cx);
14390        });
14391    }
14392
14393    pub fn open_selections_in_multibuffer(
14394        &mut self,
14395        _: &OpenSelectionsInMultibuffer,
14396        window: &mut Window,
14397        cx: &mut Context<Self>,
14398    ) {
14399        let multibuffer = self.buffer.read(cx);
14400
14401        let Some(buffer) = multibuffer.as_singleton() else {
14402            return;
14403        };
14404
14405        let Some(workspace) = self.workspace() else {
14406            return;
14407        };
14408
14409        let locations = self
14410            .selections
14411            .disjoint_anchors()
14412            .iter()
14413            .map(|range| Location {
14414                buffer: buffer.clone(),
14415                range: range.start.text_anchor..range.end.text_anchor,
14416            })
14417            .collect::<Vec<_>>();
14418
14419        let title = multibuffer.title(cx).to_string();
14420
14421        cx.spawn_in(window, |_, mut cx| async move {
14422            workspace.update_in(&mut cx, |workspace, window, cx| {
14423                Self::open_locations_in_multibuffer(
14424                    workspace,
14425                    locations,
14426                    format!("Selections for '{title}'"),
14427                    false,
14428                    MultibufferSelectionMode::All,
14429                    window,
14430                    cx,
14431                );
14432            })
14433        })
14434        .detach();
14435    }
14436
14437    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14438    /// last highlight added will be used.
14439    ///
14440    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14441    pub fn highlight_rows<T: 'static>(
14442        &mut self,
14443        range: Range<Anchor>,
14444        color: Hsla,
14445        should_autoscroll: bool,
14446        cx: &mut Context<Self>,
14447    ) {
14448        let snapshot = self.buffer().read(cx).snapshot(cx);
14449        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14450        let ix = row_highlights.binary_search_by(|highlight| {
14451            Ordering::Equal
14452                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14453                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14454        });
14455
14456        if let Err(mut ix) = ix {
14457            let index = post_inc(&mut self.highlight_order);
14458
14459            // If this range intersects with the preceding highlight, then merge it with
14460            // the preceding highlight. Otherwise insert a new highlight.
14461            let mut merged = false;
14462            if ix > 0 {
14463                let prev_highlight = &mut row_highlights[ix - 1];
14464                if prev_highlight
14465                    .range
14466                    .end
14467                    .cmp(&range.start, &snapshot)
14468                    .is_ge()
14469                {
14470                    ix -= 1;
14471                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14472                        prev_highlight.range.end = range.end;
14473                    }
14474                    merged = true;
14475                    prev_highlight.index = index;
14476                    prev_highlight.color = color;
14477                    prev_highlight.should_autoscroll = should_autoscroll;
14478                }
14479            }
14480
14481            if !merged {
14482                row_highlights.insert(
14483                    ix,
14484                    RowHighlight {
14485                        range: range.clone(),
14486                        index,
14487                        color,
14488                        should_autoscroll,
14489                    },
14490                );
14491            }
14492
14493            // If any of the following highlights intersect with this one, merge them.
14494            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14495                let highlight = &row_highlights[ix];
14496                if next_highlight
14497                    .range
14498                    .start
14499                    .cmp(&highlight.range.end, &snapshot)
14500                    .is_le()
14501                {
14502                    if next_highlight
14503                        .range
14504                        .end
14505                        .cmp(&highlight.range.end, &snapshot)
14506                        .is_gt()
14507                    {
14508                        row_highlights[ix].range.end = next_highlight.range.end;
14509                    }
14510                    row_highlights.remove(ix + 1);
14511                } else {
14512                    break;
14513                }
14514            }
14515        }
14516    }
14517
14518    /// Remove any highlighted row ranges of the given type that intersect the
14519    /// given ranges.
14520    pub fn remove_highlighted_rows<T: 'static>(
14521        &mut self,
14522        ranges_to_remove: Vec<Range<Anchor>>,
14523        cx: &mut Context<Self>,
14524    ) {
14525        let snapshot = self.buffer().read(cx).snapshot(cx);
14526        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14527        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14528        row_highlights.retain(|highlight| {
14529            while let Some(range_to_remove) = ranges_to_remove.peek() {
14530                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14531                    Ordering::Less | Ordering::Equal => {
14532                        ranges_to_remove.next();
14533                    }
14534                    Ordering::Greater => {
14535                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14536                            Ordering::Less | Ordering::Equal => {
14537                                return false;
14538                            }
14539                            Ordering::Greater => break,
14540                        }
14541                    }
14542                }
14543            }
14544
14545            true
14546        })
14547    }
14548
14549    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14550    pub fn clear_row_highlights<T: 'static>(&mut self) {
14551        self.highlighted_rows.remove(&TypeId::of::<T>());
14552    }
14553
14554    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14555    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14556        self.highlighted_rows
14557            .get(&TypeId::of::<T>())
14558            .map_or(&[] as &[_], |vec| vec.as_slice())
14559            .iter()
14560            .map(|highlight| (highlight.range.clone(), highlight.color))
14561    }
14562
14563    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14564    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14565    /// Allows to ignore certain kinds of highlights.
14566    pub fn highlighted_display_rows(
14567        &self,
14568        window: &mut Window,
14569        cx: &mut App,
14570    ) -> BTreeMap<DisplayRow, Background> {
14571        let snapshot = self.snapshot(window, cx);
14572        let mut used_highlight_orders = HashMap::default();
14573        self.highlighted_rows
14574            .iter()
14575            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14576            .fold(
14577                BTreeMap::<DisplayRow, Background>::new(),
14578                |mut unique_rows, highlight| {
14579                    let start = highlight.range.start.to_display_point(&snapshot);
14580                    let end = highlight.range.end.to_display_point(&snapshot);
14581                    let start_row = start.row().0;
14582                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14583                        && end.column() == 0
14584                    {
14585                        end.row().0.saturating_sub(1)
14586                    } else {
14587                        end.row().0
14588                    };
14589                    for row in start_row..=end_row {
14590                        let used_index =
14591                            used_highlight_orders.entry(row).or_insert(highlight.index);
14592                        if highlight.index >= *used_index {
14593                            *used_index = highlight.index;
14594                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14595                        }
14596                    }
14597                    unique_rows
14598                },
14599            )
14600    }
14601
14602    pub fn highlighted_display_row_for_autoscroll(
14603        &self,
14604        snapshot: &DisplaySnapshot,
14605    ) -> Option<DisplayRow> {
14606        self.highlighted_rows
14607            .values()
14608            .flat_map(|highlighted_rows| highlighted_rows.iter())
14609            .filter_map(|highlight| {
14610                if highlight.should_autoscroll {
14611                    Some(highlight.range.start.to_display_point(snapshot).row())
14612                } else {
14613                    None
14614                }
14615            })
14616            .min()
14617    }
14618
14619    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14620        self.highlight_background::<SearchWithinRange>(
14621            ranges,
14622            |colors| colors.editor_document_highlight_read_background,
14623            cx,
14624        )
14625    }
14626
14627    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14628        self.breadcrumb_header = Some(new_header);
14629    }
14630
14631    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14632        self.clear_background_highlights::<SearchWithinRange>(cx);
14633    }
14634
14635    pub fn highlight_background<T: 'static>(
14636        &mut self,
14637        ranges: &[Range<Anchor>],
14638        color_fetcher: fn(&ThemeColors) -> Hsla,
14639        cx: &mut Context<Self>,
14640    ) {
14641        self.background_highlights
14642            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14643        self.scrollbar_marker_state.dirty = true;
14644        cx.notify();
14645    }
14646
14647    pub fn clear_background_highlights<T: 'static>(
14648        &mut self,
14649        cx: &mut Context<Self>,
14650    ) -> Option<BackgroundHighlight> {
14651        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14652        if !text_highlights.1.is_empty() {
14653            self.scrollbar_marker_state.dirty = true;
14654            cx.notify();
14655        }
14656        Some(text_highlights)
14657    }
14658
14659    pub fn highlight_gutter<T: 'static>(
14660        &mut self,
14661        ranges: &[Range<Anchor>],
14662        color_fetcher: fn(&App) -> Hsla,
14663        cx: &mut Context<Self>,
14664    ) {
14665        self.gutter_highlights
14666            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14667        cx.notify();
14668    }
14669
14670    pub fn clear_gutter_highlights<T: 'static>(
14671        &mut self,
14672        cx: &mut Context<Self>,
14673    ) -> Option<GutterHighlight> {
14674        cx.notify();
14675        self.gutter_highlights.remove(&TypeId::of::<T>())
14676    }
14677
14678    #[cfg(feature = "test-support")]
14679    pub fn all_text_background_highlights(
14680        &self,
14681        window: &mut Window,
14682        cx: &mut Context<Self>,
14683    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14684        let snapshot = self.snapshot(window, cx);
14685        let buffer = &snapshot.buffer_snapshot;
14686        let start = buffer.anchor_before(0);
14687        let end = buffer.anchor_after(buffer.len());
14688        let theme = cx.theme().colors();
14689        self.background_highlights_in_range(start..end, &snapshot, theme)
14690    }
14691
14692    #[cfg(feature = "test-support")]
14693    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14694        let snapshot = self.buffer().read(cx).snapshot(cx);
14695
14696        let highlights = self
14697            .background_highlights
14698            .get(&TypeId::of::<items::BufferSearchHighlights>());
14699
14700        if let Some((_color, ranges)) = highlights {
14701            ranges
14702                .iter()
14703                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14704                .collect_vec()
14705        } else {
14706            vec![]
14707        }
14708    }
14709
14710    fn document_highlights_for_position<'a>(
14711        &'a self,
14712        position: Anchor,
14713        buffer: &'a MultiBufferSnapshot,
14714    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14715        let read_highlights = self
14716            .background_highlights
14717            .get(&TypeId::of::<DocumentHighlightRead>())
14718            .map(|h| &h.1);
14719        let write_highlights = self
14720            .background_highlights
14721            .get(&TypeId::of::<DocumentHighlightWrite>())
14722            .map(|h| &h.1);
14723        let left_position = position.bias_left(buffer);
14724        let right_position = position.bias_right(buffer);
14725        read_highlights
14726            .into_iter()
14727            .chain(write_highlights)
14728            .flat_map(move |ranges| {
14729                let start_ix = match ranges.binary_search_by(|probe| {
14730                    let cmp = probe.end.cmp(&left_position, buffer);
14731                    if cmp.is_ge() {
14732                        Ordering::Greater
14733                    } else {
14734                        Ordering::Less
14735                    }
14736                }) {
14737                    Ok(i) | Err(i) => i,
14738                };
14739
14740                ranges[start_ix..]
14741                    .iter()
14742                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14743            })
14744    }
14745
14746    pub fn has_background_highlights<T: 'static>(&self) -> bool {
14747        self.background_highlights
14748            .get(&TypeId::of::<T>())
14749            .map_or(false, |(_, highlights)| !highlights.is_empty())
14750    }
14751
14752    pub fn background_highlights_in_range(
14753        &self,
14754        search_range: Range<Anchor>,
14755        display_snapshot: &DisplaySnapshot,
14756        theme: &ThemeColors,
14757    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14758        let mut results = Vec::new();
14759        for (color_fetcher, ranges) in self.background_highlights.values() {
14760            let color = color_fetcher(theme);
14761            let start_ix = match ranges.binary_search_by(|probe| {
14762                let cmp = probe
14763                    .end
14764                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14765                if cmp.is_gt() {
14766                    Ordering::Greater
14767                } else {
14768                    Ordering::Less
14769                }
14770            }) {
14771                Ok(i) | Err(i) => i,
14772            };
14773            for range in &ranges[start_ix..] {
14774                if range
14775                    .start
14776                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14777                    .is_ge()
14778                {
14779                    break;
14780                }
14781
14782                let start = range.start.to_display_point(display_snapshot);
14783                let end = range.end.to_display_point(display_snapshot);
14784                results.push((start..end, color))
14785            }
14786        }
14787        results
14788    }
14789
14790    pub fn background_highlight_row_ranges<T: 'static>(
14791        &self,
14792        search_range: Range<Anchor>,
14793        display_snapshot: &DisplaySnapshot,
14794        count: usize,
14795    ) -> Vec<RangeInclusive<DisplayPoint>> {
14796        let mut results = Vec::new();
14797        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14798            return vec![];
14799        };
14800
14801        let start_ix = match ranges.binary_search_by(|probe| {
14802            let cmp = probe
14803                .end
14804                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14805            if cmp.is_gt() {
14806                Ordering::Greater
14807            } else {
14808                Ordering::Less
14809            }
14810        }) {
14811            Ok(i) | Err(i) => i,
14812        };
14813        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14814            if let (Some(start_display), Some(end_display)) = (start, end) {
14815                results.push(
14816                    start_display.to_display_point(display_snapshot)
14817                        ..=end_display.to_display_point(display_snapshot),
14818                );
14819            }
14820        };
14821        let mut start_row: Option<Point> = None;
14822        let mut end_row: Option<Point> = None;
14823        if ranges.len() > count {
14824            return Vec::new();
14825        }
14826        for range in &ranges[start_ix..] {
14827            if range
14828                .start
14829                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14830                .is_ge()
14831            {
14832                break;
14833            }
14834            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14835            if let Some(current_row) = &end_row {
14836                if end.row == current_row.row {
14837                    continue;
14838                }
14839            }
14840            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14841            if start_row.is_none() {
14842                assert_eq!(end_row, None);
14843                start_row = Some(start);
14844                end_row = Some(end);
14845                continue;
14846            }
14847            if let Some(current_end) = end_row.as_mut() {
14848                if start.row > current_end.row + 1 {
14849                    push_region(start_row, end_row);
14850                    start_row = Some(start);
14851                    end_row = Some(end);
14852                } else {
14853                    // Merge two hunks.
14854                    *current_end = end;
14855                }
14856            } else {
14857                unreachable!();
14858            }
14859        }
14860        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14861        push_region(start_row, end_row);
14862        results
14863    }
14864
14865    pub fn gutter_highlights_in_range(
14866        &self,
14867        search_range: Range<Anchor>,
14868        display_snapshot: &DisplaySnapshot,
14869        cx: &App,
14870    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14871        let mut results = Vec::new();
14872        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14873            let color = color_fetcher(cx);
14874            let start_ix = match ranges.binary_search_by(|probe| {
14875                let cmp = probe
14876                    .end
14877                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14878                if cmp.is_gt() {
14879                    Ordering::Greater
14880                } else {
14881                    Ordering::Less
14882                }
14883            }) {
14884                Ok(i) | Err(i) => i,
14885            };
14886            for range in &ranges[start_ix..] {
14887                if range
14888                    .start
14889                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14890                    .is_ge()
14891                {
14892                    break;
14893                }
14894
14895                let start = range.start.to_display_point(display_snapshot);
14896                let end = range.end.to_display_point(display_snapshot);
14897                results.push((start..end, color))
14898            }
14899        }
14900        results
14901    }
14902
14903    /// Get the text ranges corresponding to the redaction query
14904    pub fn redacted_ranges(
14905        &self,
14906        search_range: Range<Anchor>,
14907        display_snapshot: &DisplaySnapshot,
14908        cx: &App,
14909    ) -> Vec<Range<DisplayPoint>> {
14910        display_snapshot
14911            .buffer_snapshot
14912            .redacted_ranges(search_range, |file| {
14913                if let Some(file) = file {
14914                    file.is_private()
14915                        && EditorSettings::get(
14916                            Some(SettingsLocation {
14917                                worktree_id: file.worktree_id(cx),
14918                                path: file.path().as_ref(),
14919                            }),
14920                            cx,
14921                        )
14922                        .redact_private_values
14923                } else {
14924                    false
14925                }
14926            })
14927            .map(|range| {
14928                range.start.to_display_point(display_snapshot)
14929                    ..range.end.to_display_point(display_snapshot)
14930            })
14931            .collect()
14932    }
14933
14934    pub fn highlight_text<T: 'static>(
14935        &mut self,
14936        ranges: Vec<Range<Anchor>>,
14937        style: HighlightStyle,
14938        cx: &mut Context<Self>,
14939    ) {
14940        self.display_map.update(cx, |map, _| {
14941            map.highlight_text(TypeId::of::<T>(), ranges, style)
14942        });
14943        cx.notify();
14944    }
14945
14946    pub(crate) fn highlight_inlays<T: 'static>(
14947        &mut self,
14948        highlights: Vec<InlayHighlight>,
14949        style: HighlightStyle,
14950        cx: &mut Context<Self>,
14951    ) {
14952        self.display_map.update(cx, |map, _| {
14953            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14954        });
14955        cx.notify();
14956    }
14957
14958    pub fn text_highlights<'a, T: 'static>(
14959        &'a self,
14960        cx: &'a App,
14961    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14962        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14963    }
14964
14965    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14966        let cleared = self
14967            .display_map
14968            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14969        if cleared {
14970            cx.notify();
14971        }
14972    }
14973
14974    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14975        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14976            && self.focus_handle.is_focused(window)
14977    }
14978
14979    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14980        self.show_cursor_when_unfocused = is_enabled;
14981        cx.notify();
14982    }
14983
14984    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14985        cx.notify();
14986    }
14987
14988    fn on_buffer_event(
14989        &mut self,
14990        multibuffer: &Entity<MultiBuffer>,
14991        event: &multi_buffer::Event,
14992        window: &mut Window,
14993        cx: &mut Context<Self>,
14994    ) {
14995        match event {
14996            multi_buffer::Event::Edited {
14997                singleton_buffer_edited,
14998                edited_buffer: buffer_edited,
14999            } => {
15000                self.scrollbar_marker_state.dirty = true;
15001                self.active_indent_guides_state.dirty = true;
15002                self.refresh_active_diagnostics(cx);
15003                self.refresh_code_actions(window, cx);
15004                if self.has_active_inline_completion() {
15005                    self.update_visible_inline_completion(window, cx);
15006                }
15007                if let Some(buffer) = buffer_edited {
15008                    let buffer_id = buffer.read(cx).remote_id();
15009                    if !self.registered_buffers.contains_key(&buffer_id) {
15010                        if let Some(project) = self.project.as_ref() {
15011                            project.update(cx, |project, cx| {
15012                                self.registered_buffers.insert(
15013                                    buffer_id,
15014                                    project.register_buffer_with_language_servers(&buffer, cx),
15015                                );
15016                            })
15017                        }
15018                    }
15019                }
15020                cx.emit(EditorEvent::BufferEdited);
15021                cx.emit(SearchEvent::MatchesInvalidated);
15022                if *singleton_buffer_edited {
15023                    if let Some(project) = &self.project {
15024                        #[allow(clippy::mutable_key_type)]
15025                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15026                            multibuffer
15027                                .all_buffers()
15028                                .into_iter()
15029                                .filter_map(|buffer| {
15030                                    buffer.update(cx, |buffer, cx| {
15031                                        let language = buffer.language()?;
15032                                        let should_discard = project.update(cx, |project, cx| {
15033                                            project.is_local()
15034                                                && !project.has_language_servers_for(buffer, cx)
15035                                        });
15036                                        should_discard.not().then_some(language.clone())
15037                                    })
15038                                })
15039                                .collect::<HashSet<_>>()
15040                        });
15041                        if !languages_affected.is_empty() {
15042                            self.refresh_inlay_hints(
15043                                InlayHintRefreshReason::BufferEdited(languages_affected),
15044                                cx,
15045                            );
15046                        }
15047                    }
15048                }
15049
15050                let Some(project) = &self.project else { return };
15051                let (telemetry, is_via_ssh) = {
15052                    let project = project.read(cx);
15053                    let telemetry = project.client().telemetry().clone();
15054                    let is_via_ssh = project.is_via_ssh();
15055                    (telemetry, is_via_ssh)
15056                };
15057                refresh_linked_ranges(self, window, cx);
15058                telemetry.log_edit_event("editor", is_via_ssh);
15059            }
15060            multi_buffer::Event::ExcerptsAdded {
15061                buffer,
15062                predecessor,
15063                excerpts,
15064            } => {
15065                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15066                let buffer_id = buffer.read(cx).remote_id();
15067                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15068                    if let Some(project) = &self.project {
15069                        get_uncommitted_diff_for_buffer(
15070                            project,
15071                            [buffer.clone()],
15072                            self.buffer.clone(),
15073                            cx,
15074                        )
15075                        .detach();
15076                    }
15077                }
15078                cx.emit(EditorEvent::ExcerptsAdded {
15079                    buffer: buffer.clone(),
15080                    predecessor: *predecessor,
15081                    excerpts: excerpts.clone(),
15082                });
15083                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15084            }
15085            multi_buffer::Event::ExcerptsRemoved { ids } => {
15086                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15087                let buffer = self.buffer.read(cx);
15088                self.registered_buffers
15089                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15090                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15091            }
15092            multi_buffer::Event::ExcerptsEdited { ids } => {
15093                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15094            }
15095            multi_buffer::Event::ExcerptsExpanded { ids } => {
15096                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15097                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15098            }
15099            multi_buffer::Event::Reparsed(buffer_id) => {
15100                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15101
15102                cx.emit(EditorEvent::Reparsed(*buffer_id));
15103            }
15104            multi_buffer::Event::DiffHunksToggled => {
15105                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15106            }
15107            multi_buffer::Event::LanguageChanged(buffer_id) => {
15108                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15109                cx.emit(EditorEvent::Reparsed(*buffer_id));
15110                cx.notify();
15111            }
15112            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15113            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15114            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15115                cx.emit(EditorEvent::TitleChanged)
15116            }
15117            // multi_buffer::Event::DiffBaseChanged => {
15118            //     self.scrollbar_marker_state.dirty = true;
15119            //     cx.emit(EditorEvent::DiffBaseChanged);
15120            //     cx.notify();
15121            // }
15122            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15123            multi_buffer::Event::DiagnosticsUpdated => {
15124                self.refresh_active_diagnostics(cx);
15125                self.refresh_inline_diagnostics(true, window, cx);
15126                self.scrollbar_marker_state.dirty = true;
15127                cx.notify();
15128            }
15129            _ => {}
15130        };
15131    }
15132
15133    fn on_display_map_changed(
15134        &mut self,
15135        _: Entity<DisplayMap>,
15136        _: &mut Window,
15137        cx: &mut Context<Self>,
15138    ) {
15139        cx.notify();
15140    }
15141
15142    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15143        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15144        self.refresh_inline_completion(true, false, window, cx);
15145        self.refresh_inlay_hints(
15146            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15147                self.selections.newest_anchor().head(),
15148                &self.buffer.read(cx).snapshot(cx),
15149                cx,
15150            )),
15151            cx,
15152        );
15153
15154        let old_cursor_shape = self.cursor_shape;
15155
15156        {
15157            let editor_settings = EditorSettings::get_global(cx);
15158            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15159            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15160            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15161        }
15162
15163        if old_cursor_shape != self.cursor_shape {
15164            cx.emit(EditorEvent::CursorShapeChanged);
15165        }
15166
15167        let project_settings = ProjectSettings::get_global(cx);
15168        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15169
15170        if self.mode == EditorMode::Full {
15171            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15172            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15173            if self.show_inline_diagnostics != show_inline_diagnostics {
15174                self.show_inline_diagnostics = show_inline_diagnostics;
15175                self.refresh_inline_diagnostics(false, window, cx);
15176            }
15177
15178            if self.git_blame_inline_enabled != inline_blame_enabled {
15179                self.toggle_git_blame_inline_internal(false, window, cx);
15180            }
15181        }
15182
15183        cx.notify();
15184    }
15185
15186    pub fn set_searchable(&mut self, searchable: bool) {
15187        self.searchable = searchable;
15188    }
15189
15190    pub fn searchable(&self) -> bool {
15191        self.searchable
15192    }
15193
15194    fn open_proposed_changes_editor(
15195        &mut self,
15196        _: &OpenProposedChangesEditor,
15197        window: &mut Window,
15198        cx: &mut Context<Self>,
15199    ) {
15200        let Some(workspace) = self.workspace() else {
15201            cx.propagate();
15202            return;
15203        };
15204
15205        let selections = self.selections.all::<usize>(cx);
15206        let multi_buffer = self.buffer.read(cx);
15207        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15208        let mut new_selections_by_buffer = HashMap::default();
15209        for selection in selections {
15210            for (buffer, range, _) in
15211                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15212            {
15213                let mut range = range.to_point(buffer);
15214                range.start.column = 0;
15215                range.end.column = buffer.line_len(range.end.row);
15216                new_selections_by_buffer
15217                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15218                    .or_insert(Vec::new())
15219                    .push(range)
15220            }
15221        }
15222
15223        let proposed_changes_buffers = new_selections_by_buffer
15224            .into_iter()
15225            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15226            .collect::<Vec<_>>();
15227        let proposed_changes_editor = cx.new(|cx| {
15228            ProposedChangesEditor::new(
15229                "Proposed changes",
15230                proposed_changes_buffers,
15231                self.project.clone(),
15232                window,
15233                cx,
15234            )
15235        });
15236
15237        window.defer(cx, move |window, cx| {
15238            workspace.update(cx, |workspace, cx| {
15239                workspace.active_pane().update(cx, |pane, cx| {
15240                    pane.add_item(
15241                        Box::new(proposed_changes_editor),
15242                        true,
15243                        true,
15244                        None,
15245                        window,
15246                        cx,
15247                    );
15248                });
15249            });
15250        });
15251    }
15252
15253    pub fn open_excerpts_in_split(
15254        &mut self,
15255        _: &OpenExcerptsSplit,
15256        window: &mut Window,
15257        cx: &mut Context<Self>,
15258    ) {
15259        self.open_excerpts_common(None, true, window, cx)
15260    }
15261
15262    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15263        self.open_excerpts_common(None, false, window, cx)
15264    }
15265
15266    fn open_excerpts_common(
15267        &mut self,
15268        jump_data: Option<JumpData>,
15269        split: bool,
15270        window: &mut Window,
15271        cx: &mut Context<Self>,
15272    ) {
15273        let Some(workspace) = self.workspace() else {
15274            cx.propagate();
15275            return;
15276        };
15277
15278        if self.buffer.read(cx).is_singleton() {
15279            cx.propagate();
15280            return;
15281        }
15282
15283        let mut new_selections_by_buffer = HashMap::default();
15284        match &jump_data {
15285            Some(JumpData::MultiBufferPoint {
15286                excerpt_id,
15287                position,
15288                anchor,
15289                line_offset_from_top,
15290            }) => {
15291                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15292                if let Some(buffer) = multi_buffer_snapshot
15293                    .buffer_id_for_excerpt(*excerpt_id)
15294                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15295                {
15296                    let buffer_snapshot = buffer.read(cx).snapshot();
15297                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15298                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15299                    } else {
15300                        buffer_snapshot.clip_point(*position, Bias::Left)
15301                    };
15302                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15303                    new_selections_by_buffer.insert(
15304                        buffer,
15305                        (
15306                            vec![jump_to_offset..jump_to_offset],
15307                            Some(*line_offset_from_top),
15308                        ),
15309                    );
15310                }
15311            }
15312            Some(JumpData::MultiBufferRow {
15313                row,
15314                line_offset_from_top,
15315            }) => {
15316                let point = MultiBufferPoint::new(row.0, 0);
15317                if let Some((buffer, buffer_point, _)) =
15318                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15319                {
15320                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15321                    new_selections_by_buffer
15322                        .entry(buffer)
15323                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15324                        .0
15325                        .push(buffer_offset..buffer_offset)
15326                }
15327            }
15328            None => {
15329                let selections = self.selections.all::<usize>(cx);
15330                let multi_buffer = self.buffer.read(cx);
15331                for selection in selections {
15332                    for (buffer, mut range, _) in multi_buffer
15333                        .snapshot(cx)
15334                        .range_to_buffer_ranges(selection.range())
15335                    {
15336                        // When editing branch buffers, jump to the corresponding location
15337                        // in their base buffer.
15338                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
15339                        let buffer = buffer_handle.read(cx);
15340                        if let Some(base_buffer) = buffer.base_buffer() {
15341                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
15342                            buffer_handle = base_buffer;
15343                        }
15344
15345                        if selection.reversed {
15346                            mem::swap(&mut range.start, &mut range.end);
15347                        }
15348                        new_selections_by_buffer
15349                            .entry(buffer_handle)
15350                            .or_insert((Vec::new(), None))
15351                            .0
15352                            .push(range)
15353                    }
15354                }
15355            }
15356        }
15357
15358        if new_selections_by_buffer.is_empty() {
15359            return;
15360        }
15361
15362        // We defer the pane interaction because we ourselves are a workspace item
15363        // and activating a new item causes the pane to call a method on us reentrantly,
15364        // which panics if we're on the stack.
15365        window.defer(cx, move |window, cx| {
15366            workspace.update(cx, |workspace, cx| {
15367                let pane = if split {
15368                    workspace.adjacent_pane(window, cx)
15369                } else {
15370                    workspace.active_pane().clone()
15371                };
15372
15373                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15374                    let editor = buffer
15375                        .read(cx)
15376                        .file()
15377                        .is_none()
15378                        .then(|| {
15379                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15380                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15381                            // Instead, we try to activate the existing editor in the pane first.
15382                            let (editor, pane_item_index) =
15383                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15384                                    let editor = item.downcast::<Editor>()?;
15385                                    let singleton_buffer =
15386                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15387                                    if singleton_buffer == buffer {
15388                                        Some((editor, i))
15389                                    } else {
15390                                        None
15391                                    }
15392                                })?;
15393                            pane.update(cx, |pane, cx| {
15394                                pane.activate_item(pane_item_index, true, true, window, cx)
15395                            });
15396                            Some(editor)
15397                        })
15398                        .flatten()
15399                        .unwrap_or_else(|| {
15400                            workspace.open_project_item::<Self>(
15401                                pane.clone(),
15402                                buffer,
15403                                true,
15404                                true,
15405                                window,
15406                                cx,
15407                            )
15408                        });
15409
15410                    editor.update(cx, |editor, cx| {
15411                        let autoscroll = match scroll_offset {
15412                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15413                            None => Autoscroll::newest(),
15414                        };
15415                        let nav_history = editor.nav_history.take();
15416                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15417                            s.select_ranges(ranges);
15418                        });
15419                        editor.nav_history = nav_history;
15420                    });
15421                }
15422            })
15423        });
15424    }
15425
15426    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15427        let snapshot = self.buffer.read(cx).read(cx);
15428        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15429        Some(
15430            ranges
15431                .iter()
15432                .map(move |range| {
15433                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15434                })
15435                .collect(),
15436        )
15437    }
15438
15439    fn selection_replacement_ranges(
15440        &self,
15441        range: Range<OffsetUtf16>,
15442        cx: &mut App,
15443    ) -> Vec<Range<OffsetUtf16>> {
15444        let selections = self.selections.all::<OffsetUtf16>(cx);
15445        let newest_selection = selections
15446            .iter()
15447            .max_by_key(|selection| selection.id)
15448            .unwrap();
15449        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15450        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15451        let snapshot = self.buffer.read(cx).read(cx);
15452        selections
15453            .into_iter()
15454            .map(|mut selection| {
15455                selection.start.0 =
15456                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15457                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15458                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15459                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15460            })
15461            .collect()
15462    }
15463
15464    fn report_editor_event(
15465        &self,
15466        event_type: &'static str,
15467        file_extension: Option<String>,
15468        cx: &App,
15469    ) {
15470        if cfg!(any(test, feature = "test-support")) {
15471            return;
15472        }
15473
15474        let Some(project) = &self.project else { return };
15475
15476        // If None, we are in a file without an extension
15477        let file = self
15478            .buffer
15479            .read(cx)
15480            .as_singleton()
15481            .and_then(|b| b.read(cx).file());
15482        let file_extension = file_extension.or(file
15483            .as_ref()
15484            .and_then(|file| Path::new(file.file_name(cx)).extension())
15485            .and_then(|e| e.to_str())
15486            .map(|a| a.to_string()));
15487
15488        let vim_mode = cx
15489            .global::<SettingsStore>()
15490            .raw_user_settings()
15491            .get("vim_mode")
15492            == Some(&serde_json::Value::Bool(true));
15493
15494        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15495        let copilot_enabled = edit_predictions_provider
15496            == language::language_settings::EditPredictionProvider::Copilot;
15497        let copilot_enabled_for_language = self
15498            .buffer
15499            .read(cx)
15500            .settings_at(0, cx)
15501            .show_edit_predictions;
15502
15503        let project = project.read(cx);
15504        telemetry::event!(
15505            event_type,
15506            file_extension,
15507            vim_mode,
15508            copilot_enabled,
15509            copilot_enabled_for_language,
15510            edit_predictions_provider,
15511            is_via_ssh = project.is_via_ssh(),
15512        );
15513    }
15514
15515    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15516    /// with each line being an array of {text, highlight} objects.
15517    fn copy_highlight_json(
15518        &mut self,
15519        _: &CopyHighlightJson,
15520        window: &mut Window,
15521        cx: &mut Context<Self>,
15522    ) {
15523        #[derive(Serialize)]
15524        struct Chunk<'a> {
15525            text: String,
15526            highlight: Option<&'a str>,
15527        }
15528
15529        let snapshot = self.buffer.read(cx).snapshot(cx);
15530        let range = self
15531            .selected_text_range(false, window, cx)
15532            .and_then(|selection| {
15533                if selection.range.is_empty() {
15534                    None
15535                } else {
15536                    Some(selection.range)
15537                }
15538            })
15539            .unwrap_or_else(|| 0..snapshot.len());
15540
15541        let chunks = snapshot.chunks(range, true);
15542        let mut lines = Vec::new();
15543        let mut line: VecDeque<Chunk> = VecDeque::new();
15544
15545        let Some(style) = self.style.as_ref() else {
15546            return;
15547        };
15548
15549        for chunk in chunks {
15550            let highlight = chunk
15551                .syntax_highlight_id
15552                .and_then(|id| id.name(&style.syntax));
15553            let mut chunk_lines = chunk.text.split('\n').peekable();
15554            while let Some(text) = chunk_lines.next() {
15555                let mut merged_with_last_token = false;
15556                if let Some(last_token) = line.back_mut() {
15557                    if last_token.highlight == highlight {
15558                        last_token.text.push_str(text);
15559                        merged_with_last_token = true;
15560                    }
15561                }
15562
15563                if !merged_with_last_token {
15564                    line.push_back(Chunk {
15565                        text: text.into(),
15566                        highlight,
15567                    });
15568                }
15569
15570                if chunk_lines.peek().is_some() {
15571                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15572                        line.pop_front();
15573                    }
15574                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15575                        line.pop_back();
15576                    }
15577
15578                    lines.push(mem::take(&mut line));
15579                }
15580            }
15581        }
15582
15583        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15584            return;
15585        };
15586        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15587    }
15588
15589    pub fn open_context_menu(
15590        &mut self,
15591        _: &OpenContextMenu,
15592        window: &mut Window,
15593        cx: &mut Context<Self>,
15594    ) {
15595        self.request_autoscroll(Autoscroll::newest(), cx);
15596        let position = self.selections.newest_display(cx).start;
15597        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15598    }
15599
15600    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15601        &self.inlay_hint_cache
15602    }
15603
15604    pub fn replay_insert_event(
15605        &mut self,
15606        text: &str,
15607        relative_utf16_range: Option<Range<isize>>,
15608        window: &mut Window,
15609        cx: &mut Context<Self>,
15610    ) {
15611        if !self.input_enabled {
15612            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15613            return;
15614        }
15615        if let Some(relative_utf16_range) = relative_utf16_range {
15616            let selections = self.selections.all::<OffsetUtf16>(cx);
15617            self.change_selections(None, window, cx, |s| {
15618                let new_ranges = selections.into_iter().map(|range| {
15619                    let start = OffsetUtf16(
15620                        range
15621                            .head()
15622                            .0
15623                            .saturating_add_signed(relative_utf16_range.start),
15624                    );
15625                    let end = OffsetUtf16(
15626                        range
15627                            .head()
15628                            .0
15629                            .saturating_add_signed(relative_utf16_range.end),
15630                    );
15631                    start..end
15632                });
15633                s.select_ranges(new_ranges);
15634            });
15635        }
15636
15637        self.handle_input(text, window, cx);
15638    }
15639
15640    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15641        let Some(provider) = self.semantics_provider.as_ref() else {
15642            return false;
15643        };
15644
15645        let mut supports = false;
15646        self.buffer().update(cx, |this, cx| {
15647            this.for_each_buffer(|buffer| {
15648                supports |= provider.supports_inlay_hints(buffer, cx);
15649            });
15650        });
15651
15652        supports
15653    }
15654
15655    pub fn is_focused(&self, window: &Window) -> bool {
15656        self.focus_handle.is_focused(window)
15657    }
15658
15659    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15660        cx.emit(EditorEvent::Focused);
15661
15662        if let Some(descendant) = self
15663            .last_focused_descendant
15664            .take()
15665            .and_then(|descendant| descendant.upgrade())
15666        {
15667            window.focus(&descendant);
15668        } else {
15669            if let Some(blame) = self.blame.as_ref() {
15670                blame.update(cx, GitBlame::focus)
15671            }
15672
15673            self.blink_manager.update(cx, BlinkManager::enable);
15674            self.show_cursor_names(window, cx);
15675            self.buffer.update(cx, |buffer, cx| {
15676                buffer.finalize_last_transaction(cx);
15677                if self.leader_peer_id.is_none() {
15678                    buffer.set_active_selections(
15679                        &self.selections.disjoint_anchors(),
15680                        self.selections.line_mode,
15681                        self.cursor_shape,
15682                        cx,
15683                    );
15684                }
15685            });
15686        }
15687    }
15688
15689    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15690        cx.emit(EditorEvent::FocusedIn)
15691    }
15692
15693    fn handle_focus_out(
15694        &mut self,
15695        event: FocusOutEvent,
15696        _window: &mut Window,
15697        _cx: &mut Context<Self>,
15698    ) {
15699        if event.blurred != self.focus_handle {
15700            self.last_focused_descendant = Some(event.blurred);
15701        }
15702    }
15703
15704    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15705        self.blink_manager.update(cx, BlinkManager::disable);
15706        self.buffer
15707            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15708
15709        if let Some(blame) = self.blame.as_ref() {
15710            blame.update(cx, GitBlame::blur)
15711        }
15712        if !self.hover_state.focused(window, cx) {
15713            hide_hover(self, cx);
15714        }
15715        if !self
15716            .context_menu
15717            .borrow()
15718            .as_ref()
15719            .is_some_and(|context_menu| context_menu.focused(window, cx))
15720        {
15721            self.hide_context_menu(window, cx);
15722        }
15723        self.discard_inline_completion(false, cx);
15724        cx.emit(EditorEvent::Blurred);
15725        cx.notify();
15726    }
15727
15728    pub fn register_action<A: Action>(
15729        &mut self,
15730        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15731    ) -> Subscription {
15732        let id = self.next_editor_action_id.post_inc();
15733        let listener = Arc::new(listener);
15734        self.editor_actions.borrow_mut().insert(
15735            id,
15736            Box::new(move |window, _| {
15737                let listener = listener.clone();
15738                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15739                    let action = action.downcast_ref().unwrap();
15740                    if phase == DispatchPhase::Bubble {
15741                        listener(action, window, cx)
15742                    }
15743                })
15744            }),
15745        );
15746
15747        let editor_actions = self.editor_actions.clone();
15748        Subscription::new(move || {
15749            editor_actions.borrow_mut().remove(&id);
15750        })
15751    }
15752
15753    pub fn file_header_size(&self) -> u32 {
15754        FILE_HEADER_HEIGHT
15755    }
15756
15757    pub fn revert(
15758        &mut self,
15759        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15760        window: &mut Window,
15761        cx: &mut Context<Self>,
15762    ) {
15763        self.buffer().update(cx, |multi_buffer, cx| {
15764            for (buffer_id, changes) in revert_changes {
15765                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15766                    buffer.update(cx, |buffer, cx| {
15767                        buffer.edit(
15768                            changes.into_iter().map(|(range, text)| {
15769                                (range, text.to_string().map(Arc::<str>::from))
15770                            }),
15771                            None,
15772                            cx,
15773                        );
15774                    });
15775                }
15776            }
15777        });
15778        self.change_selections(None, window, cx, |selections| selections.refresh());
15779    }
15780
15781    pub fn to_pixel_point(
15782        &self,
15783        source: multi_buffer::Anchor,
15784        editor_snapshot: &EditorSnapshot,
15785        window: &mut Window,
15786    ) -> Option<gpui::Point<Pixels>> {
15787        let source_point = source.to_display_point(editor_snapshot);
15788        self.display_to_pixel_point(source_point, editor_snapshot, window)
15789    }
15790
15791    pub fn display_to_pixel_point(
15792        &self,
15793        source: DisplayPoint,
15794        editor_snapshot: &EditorSnapshot,
15795        window: &mut Window,
15796    ) -> Option<gpui::Point<Pixels>> {
15797        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15798        let text_layout_details = self.text_layout_details(window);
15799        let scroll_top = text_layout_details
15800            .scroll_anchor
15801            .scroll_position(editor_snapshot)
15802            .y;
15803
15804        if source.row().as_f32() < scroll_top.floor() {
15805            return None;
15806        }
15807        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15808        let source_y = line_height * (source.row().as_f32() - scroll_top);
15809        Some(gpui::Point::new(source_x, source_y))
15810    }
15811
15812    pub fn has_visible_completions_menu(&self) -> bool {
15813        !self.edit_prediction_preview_is_active()
15814            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15815                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15816            })
15817    }
15818
15819    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15820        self.addons
15821            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15822    }
15823
15824    pub fn unregister_addon<T: Addon>(&mut self) {
15825        self.addons.remove(&std::any::TypeId::of::<T>());
15826    }
15827
15828    pub fn addon<T: Addon>(&self) -> Option<&T> {
15829        let type_id = std::any::TypeId::of::<T>();
15830        self.addons
15831            .get(&type_id)
15832            .and_then(|item| item.to_any().downcast_ref::<T>())
15833    }
15834
15835    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15836        let text_layout_details = self.text_layout_details(window);
15837        let style = &text_layout_details.editor_style;
15838        let font_id = window.text_system().resolve_font(&style.text.font());
15839        let font_size = style.text.font_size.to_pixels(window.rem_size());
15840        let line_height = style.text.line_height_in_pixels(window.rem_size());
15841        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15842
15843        gpui::Size::new(em_width, line_height)
15844    }
15845
15846    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15847        self.load_diff_task.clone()
15848    }
15849
15850    fn read_selections_from_db(
15851        &mut self,
15852        item_id: u64,
15853        workspace_id: WorkspaceId,
15854        window: &mut Window,
15855        cx: &mut Context<Editor>,
15856    ) {
15857        if !self.is_singleton(cx)
15858            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15859        {
15860            return;
15861        }
15862        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15863            return;
15864        };
15865        if selections.is_empty() {
15866            return;
15867        }
15868
15869        let snapshot = self.buffer.read(cx).snapshot(cx);
15870        self.change_selections(None, window, cx, |s| {
15871            s.select_ranges(selections.into_iter().map(|(start, end)| {
15872                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15873            }));
15874        });
15875    }
15876}
15877
15878fn insert_extra_newline_brackets(
15879    buffer: &MultiBufferSnapshot,
15880    range: Range<usize>,
15881    language: &language::LanguageScope,
15882) -> bool {
15883    let leading_whitespace_len = buffer
15884        .reversed_chars_at(range.start)
15885        .take_while(|c| c.is_whitespace() && *c != '\n')
15886        .map(|c| c.len_utf8())
15887        .sum::<usize>();
15888    let trailing_whitespace_len = buffer
15889        .chars_at(range.end)
15890        .take_while(|c| c.is_whitespace() && *c != '\n')
15891        .map(|c| c.len_utf8())
15892        .sum::<usize>();
15893    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15894
15895    language.brackets().any(|(pair, enabled)| {
15896        let pair_start = pair.start.trim_end();
15897        let pair_end = pair.end.trim_start();
15898
15899        enabled
15900            && pair.newline
15901            && buffer.contains_str_at(range.end, pair_end)
15902            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15903    })
15904}
15905
15906fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15907    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15908        [(buffer, range, _)] => (*buffer, range.clone()),
15909        _ => return false,
15910    };
15911    let pair = {
15912        let mut result: Option<BracketMatch> = None;
15913
15914        for pair in buffer
15915            .all_bracket_ranges(range.clone())
15916            .filter(move |pair| {
15917                pair.open_range.start <= range.start && pair.close_range.end >= range.end
15918            })
15919        {
15920            let len = pair.close_range.end - pair.open_range.start;
15921
15922            if let Some(existing) = &result {
15923                let existing_len = existing.close_range.end - existing.open_range.start;
15924                if len > existing_len {
15925                    continue;
15926                }
15927            }
15928
15929            result = Some(pair);
15930        }
15931
15932        result
15933    };
15934    let Some(pair) = pair else {
15935        return false;
15936    };
15937    pair.newline_only
15938        && buffer
15939            .chars_for_range(pair.open_range.end..range.start)
15940            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15941            .all(|c| c.is_whitespace() && c != '\n')
15942}
15943
15944fn get_uncommitted_diff_for_buffer(
15945    project: &Entity<Project>,
15946    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15947    buffer: Entity<MultiBuffer>,
15948    cx: &mut App,
15949) -> Task<()> {
15950    let mut tasks = Vec::new();
15951    project.update(cx, |project, cx| {
15952        for buffer in buffers {
15953            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15954        }
15955    });
15956    cx.spawn(|mut cx| async move {
15957        let diffs = futures::future::join_all(tasks).await;
15958        buffer
15959            .update(&mut cx, |buffer, cx| {
15960                for diff in diffs.into_iter().flatten() {
15961                    buffer.add_diff(diff, cx);
15962                }
15963            })
15964            .ok();
15965    })
15966}
15967
15968fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15969    let tab_size = tab_size.get() as usize;
15970    let mut width = offset;
15971
15972    for ch in text.chars() {
15973        width += if ch == '\t' {
15974            tab_size - (width % tab_size)
15975        } else {
15976            1
15977        };
15978    }
15979
15980    width - offset
15981}
15982
15983#[cfg(test)]
15984mod tests {
15985    use super::*;
15986
15987    #[test]
15988    fn test_string_size_with_expanded_tabs() {
15989        let nz = |val| NonZeroU32::new(val).unwrap();
15990        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15991        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15992        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15993        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15994        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15995        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15996        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15997        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15998    }
15999}
16000
16001/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16002struct WordBreakingTokenizer<'a> {
16003    input: &'a str,
16004}
16005
16006impl<'a> WordBreakingTokenizer<'a> {
16007    fn new(input: &'a str) -> Self {
16008        Self { input }
16009    }
16010}
16011
16012fn is_char_ideographic(ch: char) -> bool {
16013    use unicode_script::Script::*;
16014    use unicode_script::UnicodeScript;
16015    matches!(ch.script(), Han | Tangut | Yi)
16016}
16017
16018fn is_grapheme_ideographic(text: &str) -> bool {
16019    text.chars().any(is_char_ideographic)
16020}
16021
16022fn is_grapheme_whitespace(text: &str) -> bool {
16023    text.chars().any(|x| x.is_whitespace())
16024}
16025
16026fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16027    text.chars().next().map_or(false, |ch| {
16028        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16029    })
16030}
16031
16032#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16033struct WordBreakToken<'a> {
16034    token: &'a str,
16035    grapheme_len: usize,
16036    is_whitespace: bool,
16037}
16038
16039impl<'a> Iterator for WordBreakingTokenizer<'a> {
16040    /// Yields a span, the count of graphemes in the token, and whether it was
16041    /// whitespace. Note that it also breaks at word boundaries.
16042    type Item = WordBreakToken<'a>;
16043
16044    fn next(&mut self) -> Option<Self::Item> {
16045        use unicode_segmentation::UnicodeSegmentation;
16046        if self.input.is_empty() {
16047            return None;
16048        }
16049
16050        let mut iter = self.input.graphemes(true).peekable();
16051        let mut offset = 0;
16052        let mut graphemes = 0;
16053        if let Some(first_grapheme) = iter.next() {
16054            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16055            offset += first_grapheme.len();
16056            graphemes += 1;
16057            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16058                if let Some(grapheme) = iter.peek().copied() {
16059                    if should_stay_with_preceding_ideograph(grapheme) {
16060                        offset += grapheme.len();
16061                        graphemes += 1;
16062                    }
16063                }
16064            } else {
16065                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16066                let mut next_word_bound = words.peek().copied();
16067                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16068                    next_word_bound = words.next();
16069                }
16070                while let Some(grapheme) = iter.peek().copied() {
16071                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16072                        break;
16073                    };
16074                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16075                        break;
16076                    };
16077                    offset += grapheme.len();
16078                    graphemes += 1;
16079                    iter.next();
16080                }
16081            }
16082            let token = &self.input[..offset];
16083            self.input = &self.input[offset..];
16084            if is_whitespace {
16085                Some(WordBreakToken {
16086                    token: " ",
16087                    grapheme_len: 1,
16088                    is_whitespace: true,
16089                })
16090            } else {
16091                Some(WordBreakToken {
16092                    token,
16093                    grapheme_len: graphemes,
16094                    is_whitespace: false,
16095                })
16096            }
16097        } else {
16098            None
16099        }
16100    }
16101}
16102
16103#[test]
16104fn test_word_breaking_tokenizer() {
16105    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16106        ("", &[]),
16107        ("  ", &[(" ", 1, true)]),
16108        ("Ʒ", &[("Ʒ", 1, false)]),
16109        ("Ǽ", &[("Ǽ", 1, false)]),
16110        ("", &[("", 1, false)]),
16111        ("⋑⋑", &[("⋑⋑", 2, false)]),
16112        (
16113            "原理,进而",
16114            &[
16115                ("", 1, false),
16116                ("理,", 2, false),
16117                ("", 1, false),
16118                ("", 1, false),
16119            ],
16120        ),
16121        (
16122            "hello world",
16123            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16124        ),
16125        (
16126            "hello, world",
16127            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16128        ),
16129        (
16130            "  hello world",
16131            &[
16132                (" ", 1, true),
16133                ("hello", 5, false),
16134                (" ", 1, true),
16135                ("world", 5, false),
16136            ],
16137        ),
16138        (
16139            "这是什么 \n 钢笔",
16140            &[
16141                ("", 1, false),
16142                ("", 1, false),
16143                ("", 1, false),
16144                ("", 1, false),
16145                (" ", 1, true),
16146                ("", 1, false),
16147                ("", 1, false),
16148            ],
16149        ),
16150        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16151    ];
16152
16153    for (input, result) in tests {
16154        assert_eq!(
16155            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16156            result
16157                .iter()
16158                .copied()
16159                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16160                    token,
16161                    grapheme_len,
16162                    is_whitespace,
16163                })
16164                .collect::<Vec<_>>()
16165        );
16166    }
16167}
16168
16169fn wrap_with_prefix(
16170    line_prefix: String,
16171    unwrapped_text: String,
16172    wrap_column: usize,
16173    tab_size: NonZeroU32,
16174) -> String {
16175    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16176    let mut wrapped_text = String::new();
16177    let mut current_line = line_prefix.clone();
16178
16179    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16180    let mut current_line_len = line_prefix_len;
16181    for WordBreakToken {
16182        token,
16183        grapheme_len,
16184        is_whitespace,
16185    } in tokenizer
16186    {
16187        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16188            wrapped_text.push_str(current_line.trim_end());
16189            wrapped_text.push('\n');
16190            current_line.truncate(line_prefix.len());
16191            current_line_len = line_prefix_len;
16192            if !is_whitespace {
16193                current_line.push_str(token);
16194                current_line_len += grapheme_len;
16195            }
16196        } else if !is_whitespace {
16197            current_line.push_str(token);
16198            current_line_len += grapheme_len;
16199        } else if current_line_len != line_prefix_len {
16200            current_line.push(' ');
16201            current_line_len += 1;
16202        }
16203    }
16204
16205    if !current_line.is_empty() {
16206        wrapped_text.push_str(&current_line);
16207    }
16208    wrapped_text
16209}
16210
16211#[test]
16212fn test_wrap_with_prefix() {
16213    assert_eq!(
16214        wrap_with_prefix(
16215            "# ".to_string(),
16216            "abcdefg".to_string(),
16217            4,
16218            NonZeroU32::new(4).unwrap()
16219        ),
16220        "# abcdefg"
16221    );
16222    assert_eq!(
16223        wrap_with_prefix(
16224            "".to_string(),
16225            "\thello world".to_string(),
16226            8,
16227            NonZeroU32::new(4).unwrap()
16228        ),
16229        "hello\nworld"
16230    );
16231    assert_eq!(
16232        wrap_with_prefix(
16233            "// ".to_string(),
16234            "xx \nyy zz aa bb cc".to_string(),
16235            12,
16236            NonZeroU32::new(4).unwrap()
16237        ),
16238        "// xx yy zz\n// aa bb cc"
16239    );
16240    assert_eq!(
16241        wrap_with_prefix(
16242            String::new(),
16243            "这是什么 \n 钢笔".to_string(),
16244            3,
16245            NonZeroU32::new(4).unwrap()
16246        ),
16247        "这是什\n么 钢\n"
16248    );
16249}
16250
16251pub trait CollaborationHub {
16252    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16253    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16254    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16255}
16256
16257impl CollaborationHub for Entity<Project> {
16258    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16259        self.read(cx).collaborators()
16260    }
16261
16262    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16263        self.read(cx).user_store().read(cx).participant_indices()
16264    }
16265
16266    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16267        let this = self.read(cx);
16268        let user_ids = this.collaborators().values().map(|c| c.user_id);
16269        this.user_store().read_with(cx, |user_store, cx| {
16270            user_store.participant_names(user_ids, cx)
16271        })
16272    }
16273}
16274
16275pub trait SemanticsProvider {
16276    fn hover(
16277        &self,
16278        buffer: &Entity<Buffer>,
16279        position: text::Anchor,
16280        cx: &mut App,
16281    ) -> Option<Task<Vec<project::Hover>>>;
16282
16283    fn inlay_hints(
16284        &self,
16285        buffer_handle: Entity<Buffer>,
16286        range: Range<text::Anchor>,
16287        cx: &mut App,
16288    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16289
16290    fn resolve_inlay_hint(
16291        &self,
16292        hint: InlayHint,
16293        buffer_handle: Entity<Buffer>,
16294        server_id: LanguageServerId,
16295        cx: &mut App,
16296    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16297
16298    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16299
16300    fn document_highlights(
16301        &self,
16302        buffer: &Entity<Buffer>,
16303        position: text::Anchor,
16304        cx: &mut App,
16305    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16306
16307    fn definitions(
16308        &self,
16309        buffer: &Entity<Buffer>,
16310        position: text::Anchor,
16311        kind: GotoDefinitionKind,
16312        cx: &mut App,
16313    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16314
16315    fn range_for_rename(
16316        &self,
16317        buffer: &Entity<Buffer>,
16318        position: text::Anchor,
16319        cx: &mut App,
16320    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16321
16322    fn perform_rename(
16323        &self,
16324        buffer: &Entity<Buffer>,
16325        position: text::Anchor,
16326        new_name: String,
16327        cx: &mut App,
16328    ) -> Option<Task<Result<ProjectTransaction>>>;
16329}
16330
16331pub trait CompletionProvider {
16332    fn completions(
16333        &self,
16334        buffer: &Entity<Buffer>,
16335        buffer_position: text::Anchor,
16336        trigger: CompletionContext,
16337        window: &mut Window,
16338        cx: &mut Context<Editor>,
16339    ) -> Task<Result<Vec<Completion>>>;
16340
16341    fn resolve_completions(
16342        &self,
16343        buffer: Entity<Buffer>,
16344        completion_indices: Vec<usize>,
16345        completions: Rc<RefCell<Box<[Completion]>>>,
16346        cx: &mut Context<Editor>,
16347    ) -> Task<Result<bool>>;
16348
16349    fn apply_additional_edits_for_completion(
16350        &self,
16351        _buffer: Entity<Buffer>,
16352        _completions: Rc<RefCell<Box<[Completion]>>>,
16353        _completion_index: usize,
16354        _push_to_history: bool,
16355        _cx: &mut Context<Editor>,
16356    ) -> Task<Result<Option<language::Transaction>>> {
16357        Task::ready(Ok(None))
16358    }
16359
16360    fn is_completion_trigger(
16361        &self,
16362        buffer: &Entity<Buffer>,
16363        position: language::Anchor,
16364        text: &str,
16365        trigger_in_words: bool,
16366        cx: &mut Context<Editor>,
16367    ) -> bool;
16368
16369    fn sort_completions(&self) -> bool {
16370        true
16371    }
16372}
16373
16374pub trait CodeActionProvider {
16375    fn id(&self) -> Arc<str>;
16376
16377    fn code_actions(
16378        &self,
16379        buffer: &Entity<Buffer>,
16380        range: Range<text::Anchor>,
16381        window: &mut Window,
16382        cx: &mut App,
16383    ) -> Task<Result<Vec<CodeAction>>>;
16384
16385    fn apply_code_action(
16386        &self,
16387        buffer_handle: Entity<Buffer>,
16388        action: CodeAction,
16389        excerpt_id: ExcerptId,
16390        push_to_history: bool,
16391        window: &mut Window,
16392        cx: &mut App,
16393    ) -> Task<Result<ProjectTransaction>>;
16394}
16395
16396impl CodeActionProvider for Entity<Project> {
16397    fn id(&self) -> Arc<str> {
16398        "project".into()
16399    }
16400
16401    fn code_actions(
16402        &self,
16403        buffer: &Entity<Buffer>,
16404        range: Range<text::Anchor>,
16405        _window: &mut Window,
16406        cx: &mut App,
16407    ) -> Task<Result<Vec<CodeAction>>> {
16408        self.update(cx, |project, cx| {
16409            project.code_actions(buffer, range, None, cx)
16410        })
16411    }
16412
16413    fn apply_code_action(
16414        &self,
16415        buffer_handle: Entity<Buffer>,
16416        action: CodeAction,
16417        _excerpt_id: ExcerptId,
16418        push_to_history: bool,
16419        _window: &mut Window,
16420        cx: &mut App,
16421    ) -> Task<Result<ProjectTransaction>> {
16422        self.update(cx, |project, cx| {
16423            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16424        })
16425    }
16426}
16427
16428fn snippet_completions(
16429    project: &Project,
16430    buffer: &Entity<Buffer>,
16431    buffer_position: text::Anchor,
16432    cx: &mut App,
16433) -> Task<Result<Vec<Completion>>> {
16434    let language = buffer.read(cx).language_at(buffer_position);
16435    let language_name = language.as_ref().map(|language| language.lsp_id());
16436    let snippet_store = project.snippets().read(cx);
16437    let snippets = snippet_store.snippets_for(language_name, cx);
16438
16439    if snippets.is_empty() {
16440        return Task::ready(Ok(vec![]));
16441    }
16442    let snapshot = buffer.read(cx).text_snapshot();
16443    let chars: String = snapshot
16444        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16445        .collect();
16446
16447    let scope = language.map(|language| language.default_scope());
16448    let executor = cx.background_executor().clone();
16449
16450    cx.background_spawn(async move {
16451        let classifier = CharClassifier::new(scope).for_completion(true);
16452        let mut last_word = chars
16453            .chars()
16454            .take_while(|c| classifier.is_word(*c))
16455            .collect::<String>();
16456        last_word = last_word.chars().rev().collect();
16457
16458        if last_word.is_empty() {
16459            return Ok(vec![]);
16460        }
16461
16462        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16463        let to_lsp = |point: &text::Anchor| {
16464            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16465            point_to_lsp(end)
16466        };
16467        let lsp_end = to_lsp(&buffer_position);
16468
16469        let candidates = snippets
16470            .iter()
16471            .enumerate()
16472            .flat_map(|(ix, snippet)| {
16473                snippet
16474                    .prefix
16475                    .iter()
16476                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16477            })
16478            .collect::<Vec<StringMatchCandidate>>();
16479
16480        let mut matches = fuzzy::match_strings(
16481            &candidates,
16482            &last_word,
16483            last_word.chars().any(|c| c.is_uppercase()),
16484            100,
16485            &Default::default(),
16486            executor,
16487        )
16488        .await;
16489
16490        // Remove all candidates where the query's start does not match the start of any word in the candidate
16491        if let Some(query_start) = last_word.chars().next() {
16492            matches.retain(|string_match| {
16493                split_words(&string_match.string).any(|word| {
16494                    // Check that the first codepoint of the word as lowercase matches the first
16495                    // codepoint of the query as lowercase
16496                    word.chars()
16497                        .flat_map(|codepoint| codepoint.to_lowercase())
16498                        .zip(query_start.to_lowercase())
16499                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16500                })
16501            });
16502        }
16503
16504        let matched_strings = matches
16505            .into_iter()
16506            .map(|m| m.string)
16507            .collect::<HashSet<_>>();
16508
16509        let result: Vec<Completion> = snippets
16510            .into_iter()
16511            .filter_map(|snippet| {
16512                let matching_prefix = snippet
16513                    .prefix
16514                    .iter()
16515                    .find(|prefix| matched_strings.contains(*prefix))?;
16516                let start = as_offset - last_word.len();
16517                let start = snapshot.anchor_before(start);
16518                let range = start..buffer_position;
16519                let lsp_start = to_lsp(&start);
16520                let lsp_range = lsp::Range {
16521                    start: lsp_start,
16522                    end: lsp_end,
16523                };
16524                Some(Completion {
16525                    old_range: range,
16526                    new_text: snippet.body.clone(),
16527                    resolved: false,
16528                    label: CodeLabel {
16529                        text: matching_prefix.clone(),
16530                        runs: vec![],
16531                        filter_range: 0..matching_prefix.len(),
16532                    },
16533                    server_id: LanguageServerId(usize::MAX),
16534                    documentation: snippet
16535                        .description
16536                        .clone()
16537                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16538                    lsp_completion: lsp::CompletionItem {
16539                        label: snippet.prefix.first().unwrap().clone(),
16540                        kind: Some(CompletionItemKind::SNIPPET),
16541                        label_details: snippet.description.as_ref().map(|description| {
16542                            lsp::CompletionItemLabelDetails {
16543                                detail: Some(description.clone()),
16544                                description: None,
16545                            }
16546                        }),
16547                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16548                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16549                            lsp::InsertReplaceEdit {
16550                                new_text: snippet.body.clone(),
16551                                insert: lsp_range,
16552                                replace: lsp_range,
16553                            },
16554                        )),
16555                        filter_text: Some(snippet.body.clone()),
16556                        sort_text: Some(char::MAX.to_string()),
16557                        ..Default::default()
16558                    },
16559                    confirm: None,
16560                })
16561            })
16562            .collect();
16563
16564        Ok(result)
16565    })
16566}
16567
16568impl CompletionProvider for Entity<Project> {
16569    fn completions(
16570        &self,
16571        buffer: &Entity<Buffer>,
16572        buffer_position: text::Anchor,
16573        options: CompletionContext,
16574        _window: &mut Window,
16575        cx: &mut Context<Editor>,
16576    ) -> Task<Result<Vec<Completion>>> {
16577        self.update(cx, |project, cx| {
16578            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16579            let project_completions = project.completions(buffer, buffer_position, options, cx);
16580            cx.background_spawn(async move {
16581                let mut completions = project_completions.await?;
16582                let snippets_completions = snippets.await?;
16583                completions.extend(snippets_completions);
16584                Ok(completions)
16585            })
16586        })
16587    }
16588
16589    fn resolve_completions(
16590        &self,
16591        buffer: Entity<Buffer>,
16592        completion_indices: Vec<usize>,
16593        completions: Rc<RefCell<Box<[Completion]>>>,
16594        cx: &mut Context<Editor>,
16595    ) -> Task<Result<bool>> {
16596        self.update(cx, |project, cx| {
16597            project.lsp_store().update(cx, |lsp_store, cx| {
16598                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16599            })
16600        })
16601    }
16602
16603    fn apply_additional_edits_for_completion(
16604        &self,
16605        buffer: Entity<Buffer>,
16606        completions: Rc<RefCell<Box<[Completion]>>>,
16607        completion_index: usize,
16608        push_to_history: bool,
16609        cx: &mut Context<Editor>,
16610    ) -> Task<Result<Option<language::Transaction>>> {
16611        self.update(cx, |project, cx| {
16612            project.lsp_store().update(cx, |lsp_store, cx| {
16613                lsp_store.apply_additional_edits_for_completion(
16614                    buffer,
16615                    completions,
16616                    completion_index,
16617                    push_to_history,
16618                    cx,
16619                )
16620            })
16621        })
16622    }
16623
16624    fn is_completion_trigger(
16625        &self,
16626        buffer: &Entity<Buffer>,
16627        position: language::Anchor,
16628        text: &str,
16629        trigger_in_words: bool,
16630        cx: &mut Context<Editor>,
16631    ) -> bool {
16632        let mut chars = text.chars();
16633        let char = if let Some(char) = chars.next() {
16634            char
16635        } else {
16636            return false;
16637        };
16638        if chars.next().is_some() {
16639            return false;
16640        }
16641
16642        let buffer = buffer.read(cx);
16643        let snapshot = buffer.snapshot();
16644        if !snapshot.settings_at(position, cx).show_completions_on_input {
16645            return false;
16646        }
16647        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16648        if trigger_in_words && classifier.is_word(char) {
16649            return true;
16650        }
16651
16652        buffer.completion_triggers().contains(text)
16653    }
16654}
16655
16656impl SemanticsProvider for Entity<Project> {
16657    fn hover(
16658        &self,
16659        buffer: &Entity<Buffer>,
16660        position: text::Anchor,
16661        cx: &mut App,
16662    ) -> Option<Task<Vec<project::Hover>>> {
16663        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16664    }
16665
16666    fn document_highlights(
16667        &self,
16668        buffer: &Entity<Buffer>,
16669        position: text::Anchor,
16670        cx: &mut App,
16671    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16672        Some(self.update(cx, |project, cx| {
16673            project.document_highlights(buffer, position, cx)
16674        }))
16675    }
16676
16677    fn definitions(
16678        &self,
16679        buffer: &Entity<Buffer>,
16680        position: text::Anchor,
16681        kind: GotoDefinitionKind,
16682        cx: &mut App,
16683    ) -> Option<Task<Result<Vec<LocationLink>>>> {
16684        Some(self.update(cx, |project, cx| match kind {
16685            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16686            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16687            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16688            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16689        }))
16690    }
16691
16692    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16693        // TODO: make this work for remote projects
16694        self.update(cx, |this, cx| {
16695            buffer.update(cx, |buffer, cx| {
16696                this.any_language_server_supports_inlay_hints(buffer, cx)
16697            })
16698        })
16699    }
16700
16701    fn inlay_hints(
16702        &self,
16703        buffer_handle: Entity<Buffer>,
16704        range: Range<text::Anchor>,
16705        cx: &mut App,
16706    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16707        Some(self.update(cx, |project, cx| {
16708            project.inlay_hints(buffer_handle, range, cx)
16709        }))
16710    }
16711
16712    fn resolve_inlay_hint(
16713        &self,
16714        hint: InlayHint,
16715        buffer_handle: Entity<Buffer>,
16716        server_id: LanguageServerId,
16717        cx: &mut App,
16718    ) -> Option<Task<anyhow::Result<InlayHint>>> {
16719        Some(self.update(cx, |project, cx| {
16720            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16721        }))
16722    }
16723
16724    fn range_for_rename(
16725        &self,
16726        buffer: &Entity<Buffer>,
16727        position: text::Anchor,
16728        cx: &mut App,
16729    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16730        Some(self.update(cx, |project, cx| {
16731            let buffer = buffer.clone();
16732            let task = project.prepare_rename(buffer.clone(), position, cx);
16733            cx.spawn(|_, mut cx| async move {
16734                Ok(match task.await? {
16735                    PrepareRenameResponse::Success(range) => Some(range),
16736                    PrepareRenameResponse::InvalidPosition => None,
16737                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16738                        // Fallback on using TreeSitter info to determine identifier range
16739                        buffer.update(&mut cx, |buffer, _| {
16740                            let snapshot = buffer.snapshot();
16741                            let (range, kind) = snapshot.surrounding_word(position);
16742                            if kind != Some(CharKind::Word) {
16743                                return None;
16744                            }
16745                            Some(
16746                                snapshot.anchor_before(range.start)
16747                                    ..snapshot.anchor_after(range.end),
16748                            )
16749                        })?
16750                    }
16751                })
16752            })
16753        }))
16754    }
16755
16756    fn perform_rename(
16757        &self,
16758        buffer: &Entity<Buffer>,
16759        position: text::Anchor,
16760        new_name: String,
16761        cx: &mut App,
16762    ) -> Option<Task<Result<ProjectTransaction>>> {
16763        Some(self.update(cx, |project, cx| {
16764            project.perform_rename(buffer.clone(), position, new_name, cx)
16765        }))
16766    }
16767}
16768
16769fn inlay_hint_settings(
16770    location: Anchor,
16771    snapshot: &MultiBufferSnapshot,
16772    cx: &mut Context<Editor>,
16773) -> InlayHintSettings {
16774    let file = snapshot.file_at(location);
16775    let language = snapshot.language_at(location).map(|l| l.name());
16776    language_settings(language, file, cx).inlay_hints
16777}
16778
16779fn consume_contiguous_rows(
16780    contiguous_row_selections: &mut Vec<Selection<Point>>,
16781    selection: &Selection<Point>,
16782    display_map: &DisplaySnapshot,
16783    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16784) -> (MultiBufferRow, MultiBufferRow) {
16785    contiguous_row_selections.push(selection.clone());
16786    let start_row = MultiBufferRow(selection.start.row);
16787    let mut end_row = ending_row(selection, display_map);
16788
16789    while let Some(next_selection) = selections.peek() {
16790        if next_selection.start.row <= end_row.0 {
16791            end_row = ending_row(next_selection, display_map);
16792            contiguous_row_selections.push(selections.next().unwrap().clone());
16793        } else {
16794            break;
16795        }
16796    }
16797    (start_row, end_row)
16798}
16799
16800fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16801    if next_selection.end.column > 0 || next_selection.is_empty() {
16802        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16803    } else {
16804        MultiBufferRow(next_selection.end.row)
16805    }
16806}
16807
16808impl EditorSnapshot {
16809    pub fn remote_selections_in_range<'a>(
16810        &'a self,
16811        range: &'a Range<Anchor>,
16812        collaboration_hub: &dyn CollaborationHub,
16813        cx: &'a App,
16814    ) -> impl 'a + Iterator<Item = RemoteSelection> {
16815        let participant_names = collaboration_hub.user_names(cx);
16816        let participant_indices = collaboration_hub.user_participant_indices(cx);
16817        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16818        let collaborators_by_replica_id = collaborators_by_peer_id
16819            .iter()
16820            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16821            .collect::<HashMap<_, _>>();
16822        self.buffer_snapshot
16823            .selections_in_range(range, false)
16824            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16825                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16826                let participant_index = participant_indices.get(&collaborator.user_id).copied();
16827                let user_name = participant_names.get(&collaborator.user_id).cloned();
16828                Some(RemoteSelection {
16829                    replica_id,
16830                    selection,
16831                    cursor_shape,
16832                    line_mode,
16833                    participant_index,
16834                    peer_id: collaborator.peer_id,
16835                    user_name,
16836                })
16837            })
16838    }
16839
16840    pub fn hunks_for_ranges(
16841        &self,
16842        ranges: impl Iterator<Item = Range<Point>>,
16843    ) -> Vec<MultiBufferDiffHunk> {
16844        let mut hunks = Vec::new();
16845        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16846            HashMap::default();
16847        for query_range in ranges {
16848            let query_rows =
16849                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16850            for hunk in self.buffer_snapshot.diff_hunks_in_range(
16851                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16852            ) {
16853                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16854                // when the caret is just above or just below the deleted hunk.
16855                let allow_adjacent = hunk.status().is_deleted();
16856                let related_to_selection = if allow_adjacent {
16857                    hunk.row_range.overlaps(&query_rows)
16858                        || hunk.row_range.start == query_rows.end
16859                        || hunk.row_range.end == query_rows.start
16860                } else {
16861                    hunk.row_range.overlaps(&query_rows)
16862                };
16863                if related_to_selection {
16864                    if !processed_buffer_rows
16865                        .entry(hunk.buffer_id)
16866                        .or_default()
16867                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16868                    {
16869                        continue;
16870                    }
16871                    hunks.push(hunk);
16872                }
16873            }
16874        }
16875
16876        hunks
16877    }
16878
16879    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16880        self.display_snapshot.buffer_snapshot.language_at(position)
16881    }
16882
16883    pub fn is_focused(&self) -> bool {
16884        self.is_focused
16885    }
16886
16887    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16888        self.placeholder_text.as_ref()
16889    }
16890
16891    pub fn scroll_position(&self) -> gpui::Point<f32> {
16892        self.scroll_anchor.scroll_position(&self.display_snapshot)
16893    }
16894
16895    fn gutter_dimensions(
16896        &self,
16897        font_id: FontId,
16898        font_size: Pixels,
16899        max_line_number_width: Pixels,
16900        cx: &App,
16901    ) -> Option<GutterDimensions> {
16902        if !self.show_gutter {
16903            return None;
16904        }
16905
16906        let descent = cx.text_system().descent(font_id, font_size);
16907        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16908        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16909
16910        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16911            matches!(
16912                ProjectSettings::get_global(cx).git.git_gutter,
16913                Some(GitGutterSetting::TrackedFiles)
16914            )
16915        });
16916        let gutter_settings = EditorSettings::get_global(cx).gutter;
16917        let show_line_numbers = self
16918            .show_line_numbers
16919            .unwrap_or(gutter_settings.line_numbers);
16920        let line_gutter_width = if show_line_numbers {
16921            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16922            let min_width_for_number_on_gutter = em_advance * 4.0;
16923            max_line_number_width.max(min_width_for_number_on_gutter)
16924        } else {
16925            0.0.into()
16926        };
16927
16928        let show_code_actions = self
16929            .show_code_actions
16930            .unwrap_or(gutter_settings.code_actions);
16931
16932        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16933
16934        let git_blame_entries_width =
16935            self.git_blame_gutter_max_author_length
16936                .map(|max_author_length| {
16937                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16938
16939                    /// The number of characters to dedicate to gaps and margins.
16940                    const SPACING_WIDTH: usize = 4;
16941
16942                    let max_char_count = max_author_length
16943                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16944                        + ::git::SHORT_SHA_LENGTH
16945                        + MAX_RELATIVE_TIMESTAMP.len()
16946                        + SPACING_WIDTH;
16947
16948                    em_advance * max_char_count
16949                });
16950
16951        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16952        left_padding += if show_code_actions || show_runnables {
16953            em_width * 3.0
16954        } else if show_git_gutter && show_line_numbers {
16955            em_width * 2.0
16956        } else if show_git_gutter || show_line_numbers {
16957            em_width
16958        } else {
16959            px(0.)
16960        };
16961
16962        let right_padding = if gutter_settings.folds && show_line_numbers {
16963            em_width * 4.0
16964        } else if gutter_settings.folds {
16965            em_width * 3.0
16966        } else if show_line_numbers {
16967            em_width
16968        } else {
16969            px(0.)
16970        };
16971
16972        Some(GutterDimensions {
16973            left_padding,
16974            right_padding,
16975            width: line_gutter_width + left_padding + right_padding,
16976            margin: -descent,
16977            git_blame_entries_width,
16978        })
16979    }
16980
16981    pub fn render_crease_toggle(
16982        &self,
16983        buffer_row: MultiBufferRow,
16984        row_contains_cursor: bool,
16985        editor: Entity<Editor>,
16986        window: &mut Window,
16987        cx: &mut App,
16988    ) -> Option<AnyElement> {
16989        let folded = self.is_line_folded(buffer_row);
16990        let mut is_foldable = false;
16991
16992        if let Some(crease) = self
16993            .crease_snapshot
16994            .query_row(buffer_row, &self.buffer_snapshot)
16995        {
16996            is_foldable = true;
16997            match crease {
16998                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16999                    if let Some(render_toggle) = render_toggle {
17000                        let toggle_callback =
17001                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17002                                if folded {
17003                                    editor.update(cx, |editor, cx| {
17004                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17005                                    });
17006                                } else {
17007                                    editor.update(cx, |editor, cx| {
17008                                        editor.unfold_at(
17009                                            &crate::UnfoldAt { buffer_row },
17010                                            window,
17011                                            cx,
17012                                        )
17013                                    });
17014                                }
17015                            });
17016                        return Some((render_toggle)(
17017                            buffer_row,
17018                            folded,
17019                            toggle_callback,
17020                            window,
17021                            cx,
17022                        ));
17023                    }
17024                }
17025            }
17026        }
17027
17028        is_foldable |= self.starts_indent(buffer_row);
17029
17030        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17031            Some(
17032                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17033                    .toggle_state(folded)
17034                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17035                        if folded {
17036                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17037                        } else {
17038                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17039                        }
17040                    }))
17041                    .into_any_element(),
17042            )
17043        } else {
17044            None
17045        }
17046    }
17047
17048    pub fn render_crease_trailer(
17049        &self,
17050        buffer_row: MultiBufferRow,
17051        window: &mut Window,
17052        cx: &mut App,
17053    ) -> Option<AnyElement> {
17054        let folded = self.is_line_folded(buffer_row);
17055        if let Crease::Inline { render_trailer, .. } = self
17056            .crease_snapshot
17057            .query_row(buffer_row, &self.buffer_snapshot)?
17058        {
17059            let render_trailer = render_trailer.as_ref()?;
17060            Some(render_trailer(buffer_row, folded, window, cx))
17061        } else {
17062            None
17063        }
17064    }
17065}
17066
17067impl Deref for EditorSnapshot {
17068    type Target = DisplaySnapshot;
17069
17070    fn deref(&self) -> &Self::Target {
17071        &self.display_snapshot
17072    }
17073}
17074
17075#[derive(Clone, Debug, PartialEq, Eq)]
17076pub enum EditorEvent {
17077    InputIgnored {
17078        text: Arc<str>,
17079    },
17080    InputHandled {
17081        utf16_range_to_replace: Option<Range<isize>>,
17082        text: Arc<str>,
17083    },
17084    ExcerptsAdded {
17085        buffer: Entity<Buffer>,
17086        predecessor: ExcerptId,
17087        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17088    },
17089    ExcerptsRemoved {
17090        ids: Vec<ExcerptId>,
17091    },
17092    BufferFoldToggled {
17093        ids: Vec<ExcerptId>,
17094        folded: bool,
17095    },
17096    ExcerptsEdited {
17097        ids: Vec<ExcerptId>,
17098    },
17099    ExcerptsExpanded {
17100        ids: Vec<ExcerptId>,
17101    },
17102    BufferEdited,
17103    Edited {
17104        transaction_id: clock::Lamport,
17105    },
17106    Reparsed(BufferId),
17107    Focused,
17108    FocusedIn,
17109    Blurred,
17110    DirtyChanged,
17111    Saved,
17112    TitleChanged,
17113    DiffBaseChanged,
17114    SelectionsChanged {
17115        local: bool,
17116    },
17117    ScrollPositionChanged {
17118        local: bool,
17119        autoscroll: bool,
17120    },
17121    Closed,
17122    TransactionUndone {
17123        transaction_id: clock::Lamport,
17124    },
17125    TransactionBegun {
17126        transaction_id: clock::Lamport,
17127    },
17128    Reloaded,
17129    CursorShapeChanged,
17130}
17131
17132impl EventEmitter<EditorEvent> for Editor {}
17133
17134impl Focusable for Editor {
17135    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17136        self.focus_handle.clone()
17137    }
17138}
17139
17140impl Render for Editor {
17141    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17142        let settings = ThemeSettings::get_global(cx);
17143
17144        let mut text_style = match self.mode {
17145            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17146                color: cx.theme().colors().editor_foreground,
17147                font_family: settings.ui_font.family.clone(),
17148                font_features: settings.ui_font.features.clone(),
17149                font_fallbacks: settings.ui_font.fallbacks.clone(),
17150                font_size: rems(0.875).into(),
17151                font_weight: settings.ui_font.weight,
17152                line_height: relative(settings.buffer_line_height.value()),
17153                ..Default::default()
17154            },
17155            EditorMode::Full => TextStyle {
17156                color: cx.theme().colors().editor_foreground,
17157                font_family: settings.buffer_font.family.clone(),
17158                font_features: settings.buffer_font.features.clone(),
17159                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17160                font_size: settings.buffer_font_size(cx).into(),
17161                font_weight: settings.buffer_font.weight,
17162                line_height: relative(settings.buffer_line_height.value()),
17163                ..Default::default()
17164            },
17165        };
17166        if let Some(text_style_refinement) = &self.text_style_refinement {
17167            text_style.refine(text_style_refinement)
17168        }
17169
17170        let background = match self.mode {
17171            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17172            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17173            EditorMode::Full => cx.theme().colors().editor_background,
17174        };
17175
17176        EditorElement::new(
17177            &cx.entity(),
17178            EditorStyle {
17179                background,
17180                local_player: cx.theme().players().local(),
17181                text: text_style,
17182                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17183                syntax: cx.theme().syntax().clone(),
17184                status: cx.theme().status().clone(),
17185                inlay_hints_style: make_inlay_hints_style(cx),
17186                inline_completion_styles: make_suggestion_styles(cx),
17187                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17188            },
17189        )
17190    }
17191}
17192
17193impl EntityInputHandler for Editor {
17194    fn text_for_range(
17195        &mut self,
17196        range_utf16: Range<usize>,
17197        adjusted_range: &mut Option<Range<usize>>,
17198        _: &mut Window,
17199        cx: &mut Context<Self>,
17200    ) -> Option<String> {
17201        let snapshot = self.buffer.read(cx).read(cx);
17202        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17203        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17204        if (start.0..end.0) != range_utf16 {
17205            adjusted_range.replace(start.0..end.0);
17206        }
17207        Some(snapshot.text_for_range(start..end).collect())
17208    }
17209
17210    fn selected_text_range(
17211        &mut self,
17212        ignore_disabled_input: bool,
17213        _: &mut Window,
17214        cx: &mut Context<Self>,
17215    ) -> Option<UTF16Selection> {
17216        // Prevent the IME menu from appearing when holding down an alphabetic key
17217        // while input is disabled.
17218        if !ignore_disabled_input && !self.input_enabled {
17219            return None;
17220        }
17221
17222        let selection = self.selections.newest::<OffsetUtf16>(cx);
17223        let range = selection.range();
17224
17225        Some(UTF16Selection {
17226            range: range.start.0..range.end.0,
17227            reversed: selection.reversed,
17228        })
17229    }
17230
17231    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17232        let snapshot = self.buffer.read(cx).read(cx);
17233        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17234        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17235    }
17236
17237    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17238        self.clear_highlights::<InputComposition>(cx);
17239        self.ime_transaction.take();
17240    }
17241
17242    fn replace_text_in_range(
17243        &mut self,
17244        range_utf16: Option<Range<usize>>,
17245        text: &str,
17246        window: &mut Window,
17247        cx: &mut Context<Self>,
17248    ) {
17249        if !self.input_enabled {
17250            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17251            return;
17252        }
17253
17254        self.transact(window, cx, |this, window, cx| {
17255            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17256                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17257                Some(this.selection_replacement_ranges(range_utf16, cx))
17258            } else {
17259                this.marked_text_ranges(cx)
17260            };
17261
17262            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17263                let newest_selection_id = this.selections.newest_anchor().id;
17264                this.selections
17265                    .all::<OffsetUtf16>(cx)
17266                    .iter()
17267                    .zip(ranges_to_replace.iter())
17268                    .find_map(|(selection, range)| {
17269                        if selection.id == newest_selection_id {
17270                            Some(
17271                                (range.start.0 as isize - selection.head().0 as isize)
17272                                    ..(range.end.0 as isize - selection.head().0 as isize),
17273                            )
17274                        } else {
17275                            None
17276                        }
17277                    })
17278            });
17279
17280            cx.emit(EditorEvent::InputHandled {
17281                utf16_range_to_replace: range_to_replace,
17282                text: text.into(),
17283            });
17284
17285            if let Some(new_selected_ranges) = new_selected_ranges {
17286                this.change_selections(None, window, cx, |selections| {
17287                    selections.select_ranges(new_selected_ranges)
17288                });
17289                this.backspace(&Default::default(), window, cx);
17290            }
17291
17292            this.handle_input(text, window, cx);
17293        });
17294
17295        if let Some(transaction) = self.ime_transaction {
17296            self.buffer.update(cx, |buffer, cx| {
17297                buffer.group_until_transaction(transaction, cx);
17298            });
17299        }
17300
17301        self.unmark_text(window, cx);
17302    }
17303
17304    fn replace_and_mark_text_in_range(
17305        &mut self,
17306        range_utf16: Option<Range<usize>>,
17307        text: &str,
17308        new_selected_range_utf16: Option<Range<usize>>,
17309        window: &mut Window,
17310        cx: &mut Context<Self>,
17311    ) {
17312        if !self.input_enabled {
17313            return;
17314        }
17315
17316        let transaction = self.transact(window, cx, |this, window, cx| {
17317            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17318                let snapshot = this.buffer.read(cx).read(cx);
17319                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17320                    for marked_range in &mut marked_ranges {
17321                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17322                        marked_range.start.0 += relative_range_utf16.start;
17323                        marked_range.start =
17324                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17325                        marked_range.end =
17326                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17327                    }
17328                }
17329                Some(marked_ranges)
17330            } else if let Some(range_utf16) = range_utf16 {
17331                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17332                Some(this.selection_replacement_ranges(range_utf16, cx))
17333            } else {
17334                None
17335            };
17336
17337            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17338                let newest_selection_id = this.selections.newest_anchor().id;
17339                this.selections
17340                    .all::<OffsetUtf16>(cx)
17341                    .iter()
17342                    .zip(ranges_to_replace.iter())
17343                    .find_map(|(selection, range)| {
17344                        if selection.id == newest_selection_id {
17345                            Some(
17346                                (range.start.0 as isize - selection.head().0 as isize)
17347                                    ..(range.end.0 as isize - selection.head().0 as isize),
17348                            )
17349                        } else {
17350                            None
17351                        }
17352                    })
17353            });
17354
17355            cx.emit(EditorEvent::InputHandled {
17356                utf16_range_to_replace: range_to_replace,
17357                text: text.into(),
17358            });
17359
17360            if let Some(ranges) = ranges_to_replace {
17361                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17362            }
17363
17364            let marked_ranges = {
17365                let snapshot = this.buffer.read(cx).read(cx);
17366                this.selections
17367                    .disjoint_anchors()
17368                    .iter()
17369                    .map(|selection| {
17370                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17371                    })
17372                    .collect::<Vec<_>>()
17373            };
17374
17375            if text.is_empty() {
17376                this.unmark_text(window, cx);
17377            } else {
17378                this.highlight_text::<InputComposition>(
17379                    marked_ranges.clone(),
17380                    HighlightStyle {
17381                        underline: Some(UnderlineStyle {
17382                            thickness: px(1.),
17383                            color: None,
17384                            wavy: false,
17385                        }),
17386                        ..Default::default()
17387                    },
17388                    cx,
17389                );
17390            }
17391
17392            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17393            let use_autoclose = this.use_autoclose;
17394            let use_auto_surround = this.use_auto_surround;
17395            this.set_use_autoclose(false);
17396            this.set_use_auto_surround(false);
17397            this.handle_input(text, window, cx);
17398            this.set_use_autoclose(use_autoclose);
17399            this.set_use_auto_surround(use_auto_surround);
17400
17401            if let Some(new_selected_range) = new_selected_range_utf16 {
17402                let snapshot = this.buffer.read(cx).read(cx);
17403                let new_selected_ranges = marked_ranges
17404                    .into_iter()
17405                    .map(|marked_range| {
17406                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17407                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17408                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17409                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17410                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17411                    })
17412                    .collect::<Vec<_>>();
17413
17414                drop(snapshot);
17415                this.change_selections(None, window, cx, |selections| {
17416                    selections.select_ranges(new_selected_ranges)
17417                });
17418            }
17419        });
17420
17421        self.ime_transaction = self.ime_transaction.or(transaction);
17422        if let Some(transaction) = self.ime_transaction {
17423            self.buffer.update(cx, |buffer, cx| {
17424                buffer.group_until_transaction(transaction, cx);
17425            });
17426        }
17427
17428        if self.text_highlights::<InputComposition>(cx).is_none() {
17429            self.ime_transaction.take();
17430        }
17431    }
17432
17433    fn bounds_for_range(
17434        &mut self,
17435        range_utf16: Range<usize>,
17436        element_bounds: gpui::Bounds<Pixels>,
17437        window: &mut Window,
17438        cx: &mut Context<Self>,
17439    ) -> Option<gpui::Bounds<Pixels>> {
17440        let text_layout_details = self.text_layout_details(window);
17441        let gpui::Size {
17442            width: em_width,
17443            height: line_height,
17444        } = self.character_size(window);
17445
17446        let snapshot = self.snapshot(window, cx);
17447        let scroll_position = snapshot.scroll_position();
17448        let scroll_left = scroll_position.x * em_width;
17449
17450        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17451        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17452            + self.gutter_dimensions.width
17453            + self.gutter_dimensions.margin;
17454        let y = line_height * (start.row().as_f32() - scroll_position.y);
17455
17456        Some(Bounds {
17457            origin: element_bounds.origin + point(x, y),
17458            size: size(em_width, line_height),
17459        })
17460    }
17461
17462    fn character_index_for_point(
17463        &mut self,
17464        point: gpui::Point<Pixels>,
17465        _window: &mut Window,
17466        _cx: &mut Context<Self>,
17467    ) -> Option<usize> {
17468        let position_map = self.last_position_map.as_ref()?;
17469        if !position_map.text_hitbox.contains(&point) {
17470            return None;
17471        }
17472        let display_point = position_map.point_for_position(point).previous_valid;
17473        let anchor = position_map
17474            .snapshot
17475            .display_point_to_anchor(display_point, Bias::Left);
17476        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17477        Some(utf16_offset.0)
17478    }
17479}
17480
17481trait SelectionExt {
17482    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17483    fn spanned_rows(
17484        &self,
17485        include_end_if_at_line_start: bool,
17486        map: &DisplaySnapshot,
17487    ) -> Range<MultiBufferRow>;
17488}
17489
17490impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17491    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17492        let start = self
17493            .start
17494            .to_point(&map.buffer_snapshot)
17495            .to_display_point(map);
17496        let end = self
17497            .end
17498            .to_point(&map.buffer_snapshot)
17499            .to_display_point(map);
17500        if self.reversed {
17501            end..start
17502        } else {
17503            start..end
17504        }
17505    }
17506
17507    fn spanned_rows(
17508        &self,
17509        include_end_if_at_line_start: bool,
17510        map: &DisplaySnapshot,
17511    ) -> Range<MultiBufferRow> {
17512        let start = self.start.to_point(&map.buffer_snapshot);
17513        let mut end = self.end.to_point(&map.buffer_snapshot);
17514        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17515            end.row -= 1;
17516        }
17517
17518        let buffer_start = map.prev_line_boundary(start).0;
17519        let buffer_end = map.next_line_boundary(end).0;
17520        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17521    }
17522}
17523
17524impl<T: InvalidationRegion> InvalidationStack<T> {
17525    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17526    where
17527        S: Clone + ToOffset,
17528    {
17529        while let Some(region) = self.last() {
17530            let all_selections_inside_invalidation_ranges =
17531                if selections.len() == region.ranges().len() {
17532                    selections
17533                        .iter()
17534                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17535                        .all(|(selection, invalidation_range)| {
17536                            let head = selection.head().to_offset(buffer);
17537                            invalidation_range.start <= head && invalidation_range.end >= head
17538                        })
17539                } else {
17540                    false
17541                };
17542
17543            if all_selections_inside_invalidation_ranges {
17544                break;
17545            } else {
17546                self.pop();
17547            }
17548        }
17549    }
17550}
17551
17552impl<T> Default for InvalidationStack<T> {
17553    fn default() -> Self {
17554        Self(Default::default())
17555    }
17556}
17557
17558impl<T> Deref for InvalidationStack<T> {
17559    type Target = Vec<T>;
17560
17561    fn deref(&self) -> &Self::Target {
17562        &self.0
17563    }
17564}
17565
17566impl<T> DerefMut for InvalidationStack<T> {
17567    fn deref_mut(&mut self) -> &mut Self::Target {
17568        &mut self.0
17569    }
17570}
17571
17572impl InvalidationRegion for SnippetState {
17573    fn ranges(&self) -> &[Range<Anchor>] {
17574        &self.ranges[self.active_index]
17575    }
17576}
17577
17578pub fn diagnostic_block_renderer(
17579    diagnostic: Diagnostic,
17580    max_message_rows: Option<u8>,
17581    allow_closing: bool,
17582    _is_valid: bool,
17583) -> RenderBlock {
17584    let (text_without_backticks, code_ranges) =
17585        highlight_diagnostic_message(&diagnostic, max_message_rows);
17586
17587    Arc::new(move |cx: &mut BlockContext| {
17588        let group_id: SharedString = cx.block_id.to_string().into();
17589
17590        let mut text_style = cx.window.text_style().clone();
17591        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17592        let theme_settings = ThemeSettings::get_global(cx);
17593        text_style.font_family = theme_settings.buffer_font.family.clone();
17594        text_style.font_style = theme_settings.buffer_font.style;
17595        text_style.font_features = theme_settings.buffer_font.features.clone();
17596        text_style.font_weight = theme_settings.buffer_font.weight;
17597
17598        let multi_line_diagnostic = diagnostic.message.contains('\n');
17599
17600        let buttons = |diagnostic: &Diagnostic| {
17601            if multi_line_diagnostic {
17602                v_flex()
17603            } else {
17604                h_flex()
17605            }
17606            .when(allow_closing, |div| {
17607                div.children(diagnostic.is_primary.then(|| {
17608                    IconButton::new("close-block", IconName::XCircle)
17609                        .icon_color(Color::Muted)
17610                        .size(ButtonSize::Compact)
17611                        .style(ButtonStyle::Transparent)
17612                        .visible_on_hover(group_id.clone())
17613                        .on_click(move |_click, window, cx| {
17614                            window.dispatch_action(Box::new(Cancel), cx)
17615                        })
17616                        .tooltip(|window, cx| {
17617                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17618                        })
17619                }))
17620            })
17621            .child(
17622                IconButton::new("copy-block", IconName::Copy)
17623                    .icon_color(Color::Muted)
17624                    .size(ButtonSize::Compact)
17625                    .style(ButtonStyle::Transparent)
17626                    .visible_on_hover(group_id.clone())
17627                    .on_click({
17628                        let message = diagnostic.message.clone();
17629                        move |_click, _, cx| {
17630                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17631                        }
17632                    })
17633                    .tooltip(Tooltip::text("Copy diagnostic message")),
17634            )
17635        };
17636
17637        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17638            AvailableSpace::min_size(),
17639            cx.window,
17640            cx.app,
17641        );
17642
17643        h_flex()
17644            .id(cx.block_id)
17645            .group(group_id.clone())
17646            .relative()
17647            .size_full()
17648            .block_mouse_down()
17649            .pl(cx.gutter_dimensions.width)
17650            .w(cx.max_width - cx.gutter_dimensions.full_width())
17651            .child(
17652                div()
17653                    .flex()
17654                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17655                    .flex_shrink(),
17656            )
17657            .child(buttons(&diagnostic))
17658            .child(div().flex().flex_shrink_0().child(
17659                StyledText::new(text_without_backticks.clone()).with_highlights(
17660                    &text_style,
17661                    code_ranges.iter().map(|range| {
17662                        (
17663                            range.clone(),
17664                            HighlightStyle {
17665                                font_weight: Some(FontWeight::BOLD),
17666                                ..Default::default()
17667                            },
17668                        )
17669                    }),
17670                ),
17671            ))
17672            .into_any_element()
17673    })
17674}
17675
17676fn inline_completion_edit_text(
17677    current_snapshot: &BufferSnapshot,
17678    edits: &[(Range<Anchor>, String)],
17679    edit_preview: &EditPreview,
17680    include_deletions: bool,
17681    cx: &App,
17682) -> HighlightedText {
17683    let edits = edits
17684        .iter()
17685        .map(|(anchor, text)| {
17686            (
17687                anchor.start.text_anchor..anchor.end.text_anchor,
17688                text.clone(),
17689            )
17690        })
17691        .collect::<Vec<_>>();
17692
17693    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17694}
17695
17696pub fn highlight_diagnostic_message(
17697    diagnostic: &Diagnostic,
17698    mut max_message_rows: Option<u8>,
17699) -> (SharedString, Vec<Range<usize>>) {
17700    let mut text_without_backticks = String::new();
17701    let mut code_ranges = Vec::new();
17702
17703    if let Some(source) = &diagnostic.source {
17704        text_without_backticks.push_str(source);
17705        code_ranges.push(0..source.len());
17706        text_without_backticks.push_str(": ");
17707    }
17708
17709    let mut prev_offset = 0;
17710    let mut in_code_block = false;
17711    let has_row_limit = max_message_rows.is_some();
17712    let mut newline_indices = diagnostic
17713        .message
17714        .match_indices('\n')
17715        .filter(|_| has_row_limit)
17716        .map(|(ix, _)| ix)
17717        .fuse()
17718        .peekable();
17719
17720    for (quote_ix, _) in diagnostic
17721        .message
17722        .match_indices('`')
17723        .chain([(diagnostic.message.len(), "")])
17724    {
17725        let mut first_newline_ix = None;
17726        let mut last_newline_ix = None;
17727        while let Some(newline_ix) = newline_indices.peek() {
17728            if *newline_ix < quote_ix {
17729                if first_newline_ix.is_none() {
17730                    first_newline_ix = Some(*newline_ix);
17731                }
17732                last_newline_ix = Some(*newline_ix);
17733
17734                if let Some(rows_left) = &mut max_message_rows {
17735                    if *rows_left == 0 {
17736                        break;
17737                    } else {
17738                        *rows_left -= 1;
17739                    }
17740                }
17741                let _ = newline_indices.next();
17742            } else {
17743                break;
17744            }
17745        }
17746        let prev_len = text_without_backticks.len();
17747        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17748        text_without_backticks.push_str(new_text);
17749        if in_code_block {
17750            code_ranges.push(prev_len..text_without_backticks.len());
17751        }
17752        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17753        in_code_block = !in_code_block;
17754        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17755            text_without_backticks.push_str("...");
17756            break;
17757        }
17758    }
17759
17760    (text_without_backticks.into(), code_ranges)
17761}
17762
17763fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17764    match severity {
17765        DiagnosticSeverity::ERROR => colors.error,
17766        DiagnosticSeverity::WARNING => colors.warning,
17767        DiagnosticSeverity::INFORMATION => colors.info,
17768        DiagnosticSeverity::HINT => colors.info,
17769        _ => colors.ignored,
17770    }
17771}
17772
17773pub fn styled_runs_for_code_label<'a>(
17774    label: &'a CodeLabel,
17775    syntax_theme: &'a theme::SyntaxTheme,
17776) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17777    let fade_out = HighlightStyle {
17778        fade_out: Some(0.35),
17779        ..Default::default()
17780    };
17781
17782    let mut prev_end = label.filter_range.end;
17783    label
17784        .runs
17785        .iter()
17786        .enumerate()
17787        .flat_map(move |(ix, (range, highlight_id))| {
17788            let style = if let Some(style) = highlight_id.style(syntax_theme) {
17789                style
17790            } else {
17791                return Default::default();
17792            };
17793            let mut muted_style = style;
17794            muted_style.highlight(fade_out);
17795
17796            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17797            if range.start >= label.filter_range.end {
17798                if range.start > prev_end {
17799                    runs.push((prev_end..range.start, fade_out));
17800                }
17801                runs.push((range.clone(), muted_style));
17802            } else if range.end <= label.filter_range.end {
17803                runs.push((range.clone(), style));
17804            } else {
17805                runs.push((range.start..label.filter_range.end, style));
17806                runs.push((label.filter_range.end..range.end, muted_style));
17807            }
17808            prev_end = cmp::max(prev_end, range.end);
17809
17810            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17811                runs.push((prev_end..label.text.len(), fade_out));
17812            }
17813
17814            runs
17815        })
17816}
17817
17818pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17819    let mut prev_index = 0;
17820    let mut prev_codepoint: Option<char> = None;
17821    text.char_indices()
17822        .chain([(text.len(), '\0')])
17823        .filter_map(move |(index, codepoint)| {
17824            let prev_codepoint = prev_codepoint.replace(codepoint)?;
17825            let is_boundary = index == text.len()
17826                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17827                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17828            if is_boundary {
17829                let chunk = &text[prev_index..index];
17830                prev_index = index;
17831                Some(chunk)
17832            } else {
17833                None
17834            }
17835        })
17836}
17837
17838pub trait RangeToAnchorExt: Sized {
17839    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17840
17841    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17842        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17843        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17844    }
17845}
17846
17847impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17848    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17849        let start_offset = self.start.to_offset(snapshot);
17850        let end_offset = self.end.to_offset(snapshot);
17851        if start_offset == end_offset {
17852            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17853        } else {
17854            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17855        }
17856    }
17857}
17858
17859pub trait RowExt {
17860    fn as_f32(&self) -> f32;
17861
17862    fn next_row(&self) -> Self;
17863
17864    fn previous_row(&self) -> Self;
17865
17866    fn minus(&self, other: Self) -> u32;
17867}
17868
17869impl RowExt for DisplayRow {
17870    fn as_f32(&self) -> f32 {
17871        self.0 as f32
17872    }
17873
17874    fn next_row(&self) -> Self {
17875        Self(self.0 + 1)
17876    }
17877
17878    fn previous_row(&self) -> Self {
17879        Self(self.0.saturating_sub(1))
17880    }
17881
17882    fn minus(&self, other: Self) -> u32 {
17883        self.0 - other.0
17884    }
17885}
17886
17887impl RowExt for MultiBufferRow {
17888    fn as_f32(&self) -> f32 {
17889        self.0 as f32
17890    }
17891
17892    fn next_row(&self) -> Self {
17893        Self(self.0 + 1)
17894    }
17895
17896    fn previous_row(&self) -> Self {
17897        Self(self.0.saturating_sub(1))
17898    }
17899
17900    fn minus(&self, other: Self) -> u32 {
17901        self.0 - other.0
17902    }
17903}
17904
17905trait RowRangeExt {
17906    type Row;
17907
17908    fn len(&self) -> usize;
17909
17910    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17911}
17912
17913impl RowRangeExt for Range<MultiBufferRow> {
17914    type Row = MultiBufferRow;
17915
17916    fn len(&self) -> usize {
17917        (self.end.0 - self.start.0) as usize
17918    }
17919
17920    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17921        (self.start.0..self.end.0).map(MultiBufferRow)
17922    }
17923}
17924
17925impl RowRangeExt for Range<DisplayRow> {
17926    type Row = DisplayRow;
17927
17928    fn len(&self) -> usize {
17929        (self.end.0 - self.start.0) as usize
17930    }
17931
17932    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17933        (self.start.0..self.end.0).map(DisplayRow)
17934    }
17935}
17936
17937/// If select range has more than one line, we
17938/// just point the cursor to range.start.
17939fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17940    if range.start.row == range.end.row {
17941        range
17942    } else {
17943        range.start..range.start
17944    }
17945}
17946pub struct KillRing(ClipboardItem);
17947impl Global for KillRing {}
17948
17949const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17950
17951fn all_edits_insertions_or_deletions(
17952    edits: &Vec<(Range<Anchor>, String)>,
17953    snapshot: &MultiBufferSnapshot,
17954) -> bool {
17955    let mut all_insertions = true;
17956    let mut all_deletions = true;
17957
17958    for (range, new_text) in edits.iter() {
17959        let range_is_empty = range.to_offset(&snapshot).is_empty();
17960        let text_is_empty = new_text.is_empty();
17961
17962        if range_is_empty != text_is_empty {
17963            if range_is_empty {
17964                all_deletions = false;
17965            } else {
17966                all_insertions = false;
17967            }
17968        } else {
17969            return false;
17970        }
17971
17972        if !all_insertions && !all_deletions {
17973            return false;
17974        }
17975    }
17976    all_insertions || all_deletions
17977}