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: multi_buffer::Anchor,
  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, PartialEq, PartialOrd)]
  555struct BufferOffset(usize);
  556
  557// Addons allow storing per-editor state in other crates (e.g. Vim)
  558pub trait Addon: 'static {
  559    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  560
  561    fn render_buffer_header_controls(
  562        &self,
  563        _: &ExcerptInfo,
  564        _: &Window,
  565        _: &App,
  566    ) -> Option<AnyElement> {
  567        None
  568    }
  569
  570    fn to_any(&self) -> &dyn std::any::Any;
  571}
  572
  573#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  574pub enum IsVimMode {
  575    Yes,
  576    No,
  577}
  578
  579/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  580///
  581/// See the [module level documentation](self) for more information.
  582pub struct Editor {
  583    focus_handle: FocusHandle,
  584    last_focused_descendant: Option<WeakFocusHandle>,
  585    /// The text buffer being edited
  586    buffer: Entity<MultiBuffer>,
  587    /// Map of how text in the buffer should be displayed.
  588    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  589    pub display_map: Entity<DisplayMap>,
  590    pub selections: SelectionsCollection,
  591    pub scroll_manager: ScrollManager,
  592    /// When inline assist editors are linked, they all render cursors because
  593    /// typing enters text into each of them, even the ones that aren't focused.
  594    pub(crate) show_cursor_when_unfocused: bool,
  595    columnar_selection_tail: Option<Anchor>,
  596    add_selections_state: Option<AddSelectionsState>,
  597    select_next_state: Option<SelectNextState>,
  598    select_prev_state: Option<SelectNextState>,
  599    selection_history: SelectionHistory,
  600    autoclose_regions: Vec<AutocloseRegion>,
  601    snippet_stack: InvalidationStack<SnippetState>,
  602    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  603    ime_transaction: Option<TransactionId>,
  604    active_diagnostics: Option<ActiveDiagnosticGroup>,
  605    show_inline_diagnostics: bool,
  606    inline_diagnostics_update: Task<()>,
  607    inline_diagnostics_enabled: bool,
  608    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  609    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  610
  611    // TODO: make this a access method
  612    pub project: Option<Entity<Project>>,
  613    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  614    completion_provider: Option<Box<dyn CompletionProvider>>,
  615    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  616    blink_manager: Entity<BlinkManager>,
  617    show_cursor_names: bool,
  618    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  619    pub show_local_selections: bool,
  620    mode: EditorMode,
  621    show_breadcrumbs: bool,
  622    show_gutter: bool,
  623    show_scrollbars: bool,
  624    show_line_numbers: Option<bool>,
  625    use_relative_line_numbers: Option<bool>,
  626    show_git_diff_gutter: Option<bool>,
  627    show_code_actions: Option<bool>,
  628    show_runnables: Option<bool>,
  629    show_wrap_guides: Option<bool>,
  630    show_indent_guides: Option<bool>,
  631    placeholder_text: Option<Arc<str>>,
  632    highlight_order: usize,
  633    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  634    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  635    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  636    scrollbar_marker_state: ScrollbarMarkerState,
  637    active_indent_guides_state: ActiveIndentGuidesState,
  638    nav_history: Option<ItemNavHistory>,
  639    context_menu: RefCell<Option<CodeContextMenu>>,
  640    mouse_context_menu: Option<MouseContextMenu>,
  641    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  642    signature_help_state: SignatureHelpState,
  643    auto_signature_help: Option<bool>,
  644    find_all_references_task_sources: Vec<Anchor>,
  645    next_completion_id: CompletionId,
  646    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  647    code_actions_task: Option<Task<Result<()>>>,
  648    selection_highlight_task: Option<Task<()>>,
  649    document_highlights_task: Option<Task<()>>,
  650    linked_editing_range_task: Option<Task<Option<()>>>,
  651    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  652    pending_rename: Option<RenameState>,
  653    searchable: bool,
  654    cursor_shape: CursorShape,
  655    current_line_highlight: Option<CurrentLineHighlight>,
  656    collapse_matches: bool,
  657    autoindent_mode: Option<AutoindentMode>,
  658    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  659    input_enabled: bool,
  660    use_modal_editing: bool,
  661    read_only: bool,
  662    leader_peer_id: Option<PeerId>,
  663    remote_id: Option<ViewId>,
  664    hover_state: HoverState,
  665    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  666    gutter_hovered: bool,
  667    hovered_link_state: Option<HoveredLinkState>,
  668    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  669    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  670    active_inline_completion: Option<InlineCompletionState>,
  671    /// Used to prevent flickering as the user types while the menu is open
  672    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  673    edit_prediction_settings: EditPredictionSettings,
  674    inline_completions_hidden_for_vim_mode: bool,
  675    show_inline_completions_override: Option<bool>,
  676    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  677    edit_prediction_preview: EditPredictionPreview,
  678    edit_prediction_indent_conflict: bool,
  679    edit_prediction_requires_modifier_in_indent_conflict: bool,
  680    inlay_hint_cache: InlayHintCache,
  681    next_inlay_id: usize,
  682    _subscriptions: Vec<Subscription>,
  683    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  684    gutter_dimensions: GutterDimensions,
  685    style: Option<EditorStyle>,
  686    text_style_refinement: Option<TextStyleRefinement>,
  687    next_editor_action_id: EditorActionId,
  688    editor_actions:
  689        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  690    use_autoclose: bool,
  691    use_auto_surround: bool,
  692    auto_replace_emoji_shortcode: bool,
  693    show_git_blame_gutter: bool,
  694    show_git_blame_inline: bool,
  695    show_git_blame_inline_delay_task: Option<Task<()>>,
  696    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  697    git_blame_inline_enabled: bool,
  698    serialize_dirty_buffers: bool,
  699    show_selection_menu: Option<bool>,
  700    blame: Option<Entity<GitBlame>>,
  701    blame_subscription: Option<Subscription>,
  702    custom_context_menu: Option<
  703        Box<
  704            dyn 'static
  705                + Fn(
  706                    &mut Self,
  707                    DisplayPoint,
  708                    &mut Window,
  709                    &mut Context<Self>,
  710                ) -> Option<Entity<ui::ContextMenu>>,
  711        >,
  712    >,
  713    last_bounds: Option<Bounds<Pixels>>,
  714    last_position_map: Option<Rc<PositionMap>>,
  715    expect_bounds_change: Option<Bounds<Pixels>>,
  716    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  717    tasks_update_task: Option<Task<()>>,
  718    in_project_search: bool,
  719    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  720    breadcrumb_header: Option<String>,
  721    focused_block: Option<FocusedBlock>,
  722    next_scroll_position: NextScrollCursorCenterTopBottom,
  723    addons: HashMap<TypeId, Box<dyn Addon>>,
  724    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  725    load_diff_task: Option<Shared<Task<()>>>,
  726    selection_mark_mode: bool,
  727    toggle_fold_multiple_buffers: Task<()>,
  728    _scroll_cursor_center_top_bottom_task: Task<()>,
  729    serialize_selections: Task<()>,
  730}
  731
  732#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  733enum NextScrollCursorCenterTopBottom {
  734    #[default]
  735    Center,
  736    Top,
  737    Bottom,
  738}
  739
  740impl NextScrollCursorCenterTopBottom {
  741    fn next(&self) -> Self {
  742        match self {
  743            Self::Center => Self::Top,
  744            Self::Top => Self::Bottom,
  745            Self::Bottom => Self::Center,
  746        }
  747    }
  748}
  749
  750#[derive(Clone)]
  751pub struct EditorSnapshot {
  752    pub mode: EditorMode,
  753    show_gutter: bool,
  754    show_line_numbers: Option<bool>,
  755    show_git_diff_gutter: Option<bool>,
  756    show_code_actions: Option<bool>,
  757    show_runnables: Option<bool>,
  758    git_blame_gutter_max_author_length: Option<usize>,
  759    pub display_snapshot: DisplaySnapshot,
  760    pub placeholder_text: Option<Arc<str>>,
  761    is_focused: bool,
  762    scroll_anchor: ScrollAnchor,
  763    ongoing_scroll: OngoingScroll,
  764    current_line_highlight: CurrentLineHighlight,
  765    gutter_hovered: bool,
  766}
  767
  768const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  769
  770#[derive(Default, Debug, Clone, Copy)]
  771pub struct GutterDimensions {
  772    pub left_padding: Pixels,
  773    pub right_padding: Pixels,
  774    pub width: Pixels,
  775    pub margin: Pixels,
  776    pub git_blame_entries_width: Option<Pixels>,
  777}
  778
  779impl GutterDimensions {
  780    /// The full width of the space taken up by the gutter.
  781    pub fn full_width(&self) -> Pixels {
  782        self.margin + self.width
  783    }
  784
  785    /// The width of the space reserved for the fold indicators,
  786    /// use alongside 'justify_end' and `gutter_width` to
  787    /// right align content with the line numbers
  788    pub fn fold_area_width(&self) -> Pixels {
  789        self.margin + self.right_padding
  790    }
  791}
  792
  793#[derive(Debug)]
  794pub struct RemoteSelection {
  795    pub replica_id: ReplicaId,
  796    pub selection: Selection<Anchor>,
  797    pub cursor_shape: CursorShape,
  798    pub peer_id: PeerId,
  799    pub line_mode: bool,
  800    pub participant_index: Option<ParticipantIndex>,
  801    pub user_name: Option<SharedString>,
  802}
  803
  804#[derive(Clone, Debug)]
  805struct SelectionHistoryEntry {
  806    selections: Arc<[Selection<Anchor>]>,
  807    select_next_state: Option<SelectNextState>,
  808    select_prev_state: Option<SelectNextState>,
  809    add_selections_state: Option<AddSelectionsState>,
  810}
  811
  812enum SelectionHistoryMode {
  813    Normal,
  814    Undoing,
  815    Redoing,
  816}
  817
  818#[derive(Clone, PartialEq, Eq, Hash)]
  819struct HoveredCursor {
  820    replica_id: u16,
  821    selection_id: usize,
  822}
  823
  824impl Default for SelectionHistoryMode {
  825    fn default() -> Self {
  826        Self::Normal
  827    }
  828}
  829
  830#[derive(Default)]
  831struct SelectionHistory {
  832    #[allow(clippy::type_complexity)]
  833    selections_by_transaction:
  834        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  835    mode: SelectionHistoryMode,
  836    undo_stack: VecDeque<SelectionHistoryEntry>,
  837    redo_stack: VecDeque<SelectionHistoryEntry>,
  838}
  839
  840impl SelectionHistory {
  841    fn insert_transaction(
  842        &mut self,
  843        transaction_id: TransactionId,
  844        selections: Arc<[Selection<Anchor>]>,
  845    ) {
  846        self.selections_by_transaction
  847            .insert(transaction_id, (selections, None));
  848    }
  849
  850    #[allow(clippy::type_complexity)]
  851    fn transaction(
  852        &self,
  853        transaction_id: TransactionId,
  854    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  855        self.selections_by_transaction.get(&transaction_id)
  856    }
  857
  858    #[allow(clippy::type_complexity)]
  859    fn transaction_mut(
  860        &mut self,
  861        transaction_id: TransactionId,
  862    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  863        self.selections_by_transaction.get_mut(&transaction_id)
  864    }
  865
  866    fn push(&mut self, entry: SelectionHistoryEntry) {
  867        if !entry.selections.is_empty() {
  868            match self.mode {
  869                SelectionHistoryMode::Normal => {
  870                    self.push_undo(entry);
  871                    self.redo_stack.clear();
  872                }
  873                SelectionHistoryMode::Undoing => self.push_redo(entry),
  874                SelectionHistoryMode::Redoing => self.push_undo(entry),
  875            }
  876        }
  877    }
  878
  879    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  880        if self
  881            .undo_stack
  882            .back()
  883            .map_or(true, |e| e.selections != entry.selections)
  884        {
  885            self.undo_stack.push_back(entry);
  886            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  887                self.undo_stack.pop_front();
  888            }
  889        }
  890    }
  891
  892    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  893        if self
  894            .redo_stack
  895            .back()
  896            .map_or(true, |e| e.selections != entry.selections)
  897        {
  898            self.redo_stack.push_back(entry);
  899            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  900                self.redo_stack.pop_front();
  901            }
  902        }
  903    }
  904}
  905
  906struct RowHighlight {
  907    index: usize,
  908    range: Range<Anchor>,
  909    color: Hsla,
  910    should_autoscroll: bool,
  911}
  912
  913#[derive(Clone, Debug)]
  914struct AddSelectionsState {
  915    above: bool,
  916    stack: Vec<usize>,
  917}
  918
  919#[derive(Clone)]
  920struct SelectNextState {
  921    query: AhoCorasick,
  922    wordwise: bool,
  923    done: bool,
  924}
  925
  926impl std::fmt::Debug for SelectNextState {
  927    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  928        f.debug_struct(std::any::type_name::<Self>())
  929            .field("wordwise", &self.wordwise)
  930            .field("done", &self.done)
  931            .finish()
  932    }
  933}
  934
  935#[derive(Debug)]
  936struct AutocloseRegion {
  937    selection_id: usize,
  938    range: Range<Anchor>,
  939    pair: BracketPair,
  940}
  941
  942#[derive(Debug)]
  943struct SnippetState {
  944    ranges: Vec<Vec<Range<Anchor>>>,
  945    active_index: usize,
  946    choices: Vec<Option<Vec<String>>>,
  947}
  948
  949#[doc(hidden)]
  950pub struct RenameState {
  951    pub range: Range<Anchor>,
  952    pub old_name: Arc<str>,
  953    pub editor: Entity<Editor>,
  954    block_id: CustomBlockId,
  955}
  956
  957struct InvalidationStack<T>(Vec<T>);
  958
  959struct RegisteredInlineCompletionProvider {
  960    provider: Arc<dyn InlineCompletionProviderHandle>,
  961    _subscription: Subscription,
  962}
  963
  964#[derive(Debug)]
  965struct ActiveDiagnosticGroup {
  966    primary_range: Range<Anchor>,
  967    primary_message: String,
  968    group_id: usize,
  969    blocks: HashMap<CustomBlockId, Diagnostic>,
  970    is_valid: bool,
  971}
  972
  973#[derive(Serialize, Deserialize, Clone, Debug)]
  974pub struct ClipboardSelection {
  975    /// The number of bytes in this selection.
  976    pub len: usize,
  977    /// Whether this was a full-line selection.
  978    pub is_entire_line: bool,
  979    /// The column where this selection originally started.
  980    pub start_column: u32,
  981}
  982
  983#[derive(Debug)]
  984pub(crate) struct NavigationData {
  985    cursor_anchor: Anchor,
  986    cursor_position: Point,
  987    scroll_anchor: ScrollAnchor,
  988    scroll_top_row: u32,
  989}
  990
  991#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  992pub enum GotoDefinitionKind {
  993    Symbol,
  994    Declaration,
  995    Type,
  996    Implementation,
  997}
  998
  999#[derive(Debug, Clone)]
 1000enum InlayHintRefreshReason {
 1001    Toggle(bool),
 1002    SettingsChange(InlayHintSettings),
 1003    NewLinesShown,
 1004    BufferEdited(HashSet<Arc<Language>>),
 1005    RefreshRequested,
 1006    ExcerptsRemoved(Vec<ExcerptId>),
 1007}
 1008
 1009impl InlayHintRefreshReason {
 1010    fn description(&self) -> &'static str {
 1011        match self {
 1012            Self::Toggle(_) => "toggle",
 1013            Self::SettingsChange(_) => "settings change",
 1014            Self::NewLinesShown => "new lines shown",
 1015            Self::BufferEdited(_) => "buffer edited",
 1016            Self::RefreshRequested => "refresh requested",
 1017            Self::ExcerptsRemoved(_) => "excerpts removed",
 1018        }
 1019    }
 1020}
 1021
 1022pub enum FormatTarget {
 1023    Buffers,
 1024    Ranges(Vec<Range<MultiBufferPoint>>),
 1025}
 1026
 1027pub(crate) struct FocusedBlock {
 1028    id: BlockId,
 1029    focus_handle: WeakFocusHandle,
 1030}
 1031
 1032#[derive(Clone)]
 1033enum JumpData {
 1034    MultiBufferRow {
 1035        row: MultiBufferRow,
 1036        line_offset_from_top: u32,
 1037    },
 1038    MultiBufferPoint {
 1039        excerpt_id: ExcerptId,
 1040        position: Point,
 1041        anchor: text::Anchor,
 1042        line_offset_from_top: u32,
 1043    },
 1044}
 1045
 1046pub enum MultibufferSelectionMode {
 1047    First,
 1048    All,
 1049}
 1050
 1051impl Editor {
 1052    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1053        let buffer = cx.new(|cx| Buffer::local("", cx));
 1054        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1055        Self::new(
 1056            EditorMode::SingleLine { auto_width: false },
 1057            buffer,
 1058            None,
 1059            false,
 1060            window,
 1061            cx,
 1062        )
 1063    }
 1064
 1065    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1066        let buffer = cx.new(|cx| Buffer::local("", cx));
 1067        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1068        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1069    }
 1070
 1071    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1072        let buffer = cx.new(|cx| Buffer::local("", cx));
 1073        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1074        Self::new(
 1075            EditorMode::SingleLine { auto_width: true },
 1076            buffer,
 1077            None,
 1078            false,
 1079            window,
 1080            cx,
 1081        )
 1082    }
 1083
 1084    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1085        let buffer = cx.new(|cx| Buffer::local("", cx));
 1086        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1087        Self::new(
 1088            EditorMode::AutoHeight { max_lines },
 1089            buffer,
 1090            None,
 1091            false,
 1092            window,
 1093            cx,
 1094        )
 1095    }
 1096
 1097    pub fn for_buffer(
 1098        buffer: Entity<Buffer>,
 1099        project: Option<Entity<Project>>,
 1100        window: &mut Window,
 1101        cx: &mut Context<Self>,
 1102    ) -> Self {
 1103        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1104        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1105    }
 1106
 1107    pub fn for_multibuffer(
 1108        buffer: Entity<MultiBuffer>,
 1109        project: Option<Entity<Project>>,
 1110        show_excerpt_controls: bool,
 1111        window: &mut Window,
 1112        cx: &mut Context<Self>,
 1113    ) -> Self {
 1114        Self::new(
 1115            EditorMode::Full,
 1116            buffer,
 1117            project,
 1118            show_excerpt_controls,
 1119            window,
 1120            cx,
 1121        )
 1122    }
 1123
 1124    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1125        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1126        let mut clone = Self::new(
 1127            self.mode,
 1128            self.buffer.clone(),
 1129            self.project.clone(),
 1130            show_excerpt_controls,
 1131            window,
 1132            cx,
 1133        );
 1134        self.display_map.update(cx, |display_map, cx| {
 1135            let snapshot = display_map.snapshot(cx);
 1136            clone.display_map.update(cx, |display_map, cx| {
 1137                display_map.set_state(&snapshot, cx);
 1138            });
 1139        });
 1140        clone.selections.clone_state(&self.selections);
 1141        clone.scroll_manager.clone_state(&self.scroll_manager);
 1142        clone.searchable = self.searchable;
 1143        clone
 1144    }
 1145
 1146    pub fn new(
 1147        mode: EditorMode,
 1148        buffer: Entity<MultiBuffer>,
 1149        project: Option<Entity<Project>>,
 1150        show_excerpt_controls: bool,
 1151        window: &mut Window,
 1152        cx: &mut Context<Self>,
 1153    ) -> Self {
 1154        let style = window.text_style();
 1155        let font_size = style.font_size.to_pixels(window.rem_size());
 1156        let editor = cx.entity().downgrade();
 1157        let fold_placeholder = FoldPlaceholder {
 1158            constrain_width: true,
 1159            render: Arc::new(move |fold_id, fold_range, cx| {
 1160                let editor = editor.clone();
 1161                div()
 1162                    .id(fold_id)
 1163                    .bg(cx.theme().colors().ghost_element_background)
 1164                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1165                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1166                    .rounded_sm()
 1167                    .size_full()
 1168                    .cursor_pointer()
 1169                    .child("")
 1170                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1171                    .on_click(move |_, _window, cx| {
 1172                        editor
 1173                            .update(cx, |editor, cx| {
 1174                                editor.unfold_ranges(
 1175                                    &[fold_range.start..fold_range.end],
 1176                                    true,
 1177                                    false,
 1178                                    cx,
 1179                                );
 1180                                cx.stop_propagation();
 1181                            })
 1182                            .ok();
 1183                    })
 1184                    .into_any()
 1185            }),
 1186            merge_adjacent: true,
 1187            ..Default::default()
 1188        };
 1189        let display_map = cx.new(|cx| {
 1190            DisplayMap::new(
 1191                buffer.clone(),
 1192                style.font(),
 1193                font_size,
 1194                None,
 1195                show_excerpt_controls,
 1196                FILE_HEADER_HEIGHT,
 1197                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1198                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1199                fold_placeholder,
 1200                cx,
 1201            )
 1202        });
 1203
 1204        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1205
 1206        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1207
 1208        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1209            .then(|| language_settings::SoftWrap::None);
 1210
 1211        let mut project_subscriptions = Vec::new();
 1212        if mode == EditorMode::Full {
 1213            if let Some(project) = project.as_ref() {
 1214                if buffer.read(cx).is_singleton() {
 1215                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1216                        cx.emit(EditorEvent::TitleChanged);
 1217                    }));
 1218                }
 1219                project_subscriptions.push(cx.subscribe_in(
 1220                    project,
 1221                    window,
 1222                    |editor, _, event, window, cx| {
 1223                        if let project::Event::RefreshInlayHints = event {
 1224                            editor
 1225                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1226                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1227                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1228                                let focus_handle = editor.focus_handle(cx);
 1229                                if focus_handle.is_focused(window) {
 1230                                    let snapshot = buffer.read(cx).snapshot();
 1231                                    for (range, snippet) in snippet_edits {
 1232                                        let editor_range =
 1233                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1234                                        editor
 1235                                            .insert_snippet(
 1236                                                &[editor_range],
 1237                                                snippet.clone(),
 1238                                                window,
 1239                                                cx,
 1240                                            )
 1241                                            .ok();
 1242                                    }
 1243                                }
 1244                            }
 1245                        }
 1246                    },
 1247                ));
 1248                if let Some(task_inventory) = project
 1249                    .read(cx)
 1250                    .task_store()
 1251                    .read(cx)
 1252                    .task_inventory()
 1253                    .cloned()
 1254                {
 1255                    project_subscriptions.push(cx.observe_in(
 1256                        &task_inventory,
 1257                        window,
 1258                        |editor, _, window, cx| {
 1259                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1260                        },
 1261                    ));
 1262                }
 1263            }
 1264        }
 1265
 1266        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1267
 1268        let inlay_hint_settings =
 1269            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1270        let focus_handle = cx.focus_handle();
 1271        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1272            .detach();
 1273        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1274            .detach();
 1275        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1276            .detach();
 1277        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1278            .detach();
 1279
 1280        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1281            Some(false)
 1282        } else {
 1283            None
 1284        };
 1285
 1286        let mut code_action_providers = Vec::new();
 1287        let mut load_uncommitted_diff = None;
 1288        if let Some(project) = project.clone() {
 1289            load_uncommitted_diff = Some(
 1290                get_uncommitted_diff_for_buffer(
 1291                    &project,
 1292                    buffer.read(cx).all_buffers(),
 1293                    buffer.clone(),
 1294                    cx,
 1295                )
 1296                .shared(),
 1297            );
 1298            code_action_providers.push(Rc::new(project) as Rc<_>);
 1299        }
 1300
 1301        let mut this = Self {
 1302            focus_handle,
 1303            show_cursor_when_unfocused: false,
 1304            last_focused_descendant: None,
 1305            buffer: buffer.clone(),
 1306            display_map: display_map.clone(),
 1307            selections,
 1308            scroll_manager: ScrollManager::new(cx),
 1309            columnar_selection_tail: None,
 1310            add_selections_state: None,
 1311            select_next_state: None,
 1312            select_prev_state: None,
 1313            selection_history: Default::default(),
 1314            autoclose_regions: Default::default(),
 1315            snippet_stack: Default::default(),
 1316            select_larger_syntax_node_stack: Vec::new(),
 1317            ime_transaction: Default::default(),
 1318            active_diagnostics: None,
 1319            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1320            inline_diagnostics_update: Task::ready(()),
 1321            inline_diagnostics: Vec::new(),
 1322            soft_wrap_mode_override,
 1323            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1324            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1325            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1326            project,
 1327            blink_manager: blink_manager.clone(),
 1328            show_local_selections: true,
 1329            show_scrollbars: true,
 1330            mode,
 1331            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1332            show_gutter: mode == EditorMode::Full,
 1333            show_line_numbers: None,
 1334            use_relative_line_numbers: None,
 1335            show_git_diff_gutter: None,
 1336            show_code_actions: None,
 1337            show_runnables: None,
 1338            show_wrap_guides: None,
 1339            show_indent_guides,
 1340            placeholder_text: None,
 1341            highlight_order: 0,
 1342            highlighted_rows: HashMap::default(),
 1343            background_highlights: Default::default(),
 1344            gutter_highlights: TreeMap::default(),
 1345            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1346            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1347            nav_history: None,
 1348            context_menu: RefCell::new(None),
 1349            mouse_context_menu: None,
 1350            completion_tasks: Default::default(),
 1351            signature_help_state: SignatureHelpState::default(),
 1352            auto_signature_help: None,
 1353            find_all_references_task_sources: Vec::new(),
 1354            next_completion_id: 0,
 1355            next_inlay_id: 0,
 1356            code_action_providers,
 1357            available_code_actions: Default::default(),
 1358            code_actions_task: Default::default(),
 1359            selection_highlight_task: Default::default(),
 1360            document_highlights_task: Default::default(),
 1361            linked_editing_range_task: Default::default(),
 1362            pending_rename: Default::default(),
 1363            searchable: true,
 1364            cursor_shape: EditorSettings::get_global(cx)
 1365                .cursor_shape
 1366                .unwrap_or_default(),
 1367            current_line_highlight: None,
 1368            autoindent_mode: Some(AutoindentMode::EachLine),
 1369            collapse_matches: false,
 1370            workspace: None,
 1371            input_enabled: true,
 1372            use_modal_editing: mode == EditorMode::Full,
 1373            read_only: false,
 1374            use_autoclose: true,
 1375            use_auto_surround: true,
 1376            auto_replace_emoji_shortcode: false,
 1377            leader_peer_id: None,
 1378            remote_id: None,
 1379            hover_state: Default::default(),
 1380            pending_mouse_down: None,
 1381            hovered_link_state: Default::default(),
 1382            edit_prediction_provider: None,
 1383            active_inline_completion: None,
 1384            stale_inline_completion_in_menu: None,
 1385            edit_prediction_preview: EditPredictionPreview::Inactive,
 1386            inline_diagnostics_enabled: mode == EditorMode::Full,
 1387            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1388
 1389            gutter_hovered: false,
 1390            pixel_position_of_newest_cursor: None,
 1391            last_bounds: None,
 1392            last_position_map: None,
 1393            expect_bounds_change: None,
 1394            gutter_dimensions: GutterDimensions::default(),
 1395            style: None,
 1396            show_cursor_names: false,
 1397            hovered_cursors: Default::default(),
 1398            next_editor_action_id: EditorActionId::default(),
 1399            editor_actions: Rc::default(),
 1400            inline_completions_hidden_for_vim_mode: false,
 1401            show_inline_completions_override: None,
 1402            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1403            edit_prediction_settings: EditPredictionSettings::Disabled,
 1404            edit_prediction_indent_conflict: false,
 1405            edit_prediction_requires_modifier_in_indent_conflict: true,
 1406            custom_context_menu: None,
 1407            show_git_blame_gutter: false,
 1408            show_git_blame_inline: false,
 1409            show_selection_menu: None,
 1410            show_git_blame_inline_delay_task: None,
 1411            git_blame_inline_tooltip: None,
 1412            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1413            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1414                .session
 1415                .restore_unsaved_buffers,
 1416            blame: None,
 1417            blame_subscription: None,
 1418            tasks: Default::default(),
 1419            _subscriptions: vec![
 1420                cx.observe(&buffer, Self::on_buffer_changed),
 1421                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1422                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1423                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1424                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1425                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1426                cx.observe_window_activation(window, |editor, window, cx| {
 1427                    let active = window.is_window_active();
 1428                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1429                        if active {
 1430                            blink_manager.enable(cx);
 1431                        } else {
 1432                            blink_manager.disable(cx);
 1433                        }
 1434                    });
 1435                }),
 1436            ],
 1437            tasks_update_task: None,
 1438            linked_edit_ranges: Default::default(),
 1439            in_project_search: false,
 1440            previous_search_ranges: None,
 1441            breadcrumb_header: None,
 1442            focused_block: None,
 1443            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1444            addons: HashMap::default(),
 1445            registered_buffers: HashMap::default(),
 1446            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1447            selection_mark_mode: false,
 1448            toggle_fold_multiple_buffers: Task::ready(()),
 1449            serialize_selections: Task::ready(()),
 1450            text_style_refinement: None,
 1451            load_diff_task: load_uncommitted_diff,
 1452        };
 1453        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1454        this._subscriptions.extend(project_subscriptions);
 1455
 1456        this.end_selection(window, cx);
 1457        this.scroll_manager.show_scrollbar(window, cx);
 1458
 1459        if mode == EditorMode::Full {
 1460            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1461            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1462
 1463            if this.git_blame_inline_enabled {
 1464                this.git_blame_inline_enabled = true;
 1465                this.start_git_blame_inline(false, window, cx);
 1466            }
 1467
 1468            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1469                if let Some(project) = this.project.as_ref() {
 1470                    let handle = project.update(cx, |project, cx| {
 1471                        project.register_buffer_with_language_servers(&buffer, cx)
 1472                    });
 1473                    this.registered_buffers
 1474                        .insert(buffer.read(cx).remote_id(), handle);
 1475                }
 1476            }
 1477        }
 1478
 1479        this.report_editor_event("Editor Opened", None, cx);
 1480        this
 1481    }
 1482
 1483    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1484        self.mouse_context_menu
 1485            .as_ref()
 1486            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1487    }
 1488
 1489    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1490        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1491    }
 1492
 1493    fn key_context_internal(
 1494        &self,
 1495        has_active_edit_prediction: bool,
 1496        window: &Window,
 1497        cx: &App,
 1498    ) -> KeyContext {
 1499        let mut key_context = KeyContext::new_with_defaults();
 1500        key_context.add("Editor");
 1501        let mode = match self.mode {
 1502            EditorMode::SingleLine { .. } => "single_line",
 1503            EditorMode::AutoHeight { .. } => "auto_height",
 1504            EditorMode::Full => "full",
 1505        };
 1506
 1507        if EditorSettings::jupyter_enabled(cx) {
 1508            key_context.add("jupyter");
 1509        }
 1510
 1511        key_context.set("mode", mode);
 1512        if self.pending_rename.is_some() {
 1513            key_context.add("renaming");
 1514        }
 1515
 1516        match self.context_menu.borrow().as_ref() {
 1517            Some(CodeContextMenu::Completions(_)) => {
 1518                key_context.add("menu");
 1519                key_context.add("showing_completions");
 1520            }
 1521            Some(CodeContextMenu::CodeActions(_)) => {
 1522                key_context.add("menu");
 1523                key_context.add("showing_code_actions")
 1524            }
 1525            None => {}
 1526        }
 1527
 1528        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1529        if !self.focus_handle(cx).contains_focused(window, cx)
 1530            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1531        {
 1532            for addon in self.addons.values() {
 1533                addon.extend_key_context(&mut key_context, cx)
 1534            }
 1535        }
 1536
 1537        if let Some(extension) = self
 1538            .buffer
 1539            .read(cx)
 1540            .as_singleton()
 1541            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1542        {
 1543            key_context.set("extension", extension.to_string());
 1544        }
 1545
 1546        if has_active_edit_prediction {
 1547            if self.edit_prediction_in_conflict() {
 1548                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1549            } else {
 1550                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1551                key_context.add("copilot_suggestion");
 1552            }
 1553        }
 1554
 1555        if self.selection_mark_mode {
 1556            key_context.add("selection_mode");
 1557        }
 1558
 1559        key_context
 1560    }
 1561
 1562    pub fn edit_prediction_in_conflict(&self) -> bool {
 1563        if !self.show_edit_predictions_in_menu() {
 1564            return false;
 1565        }
 1566
 1567        let showing_completions = self
 1568            .context_menu
 1569            .borrow()
 1570            .as_ref()
 1571            .map_or(false, |context| {
 1572                matches!(context, CodeContextMenu::Completions(_))
 1573            });
 1574
 1575        showing_completions
 1576            || self.edit_prediction_requires_modifier()
 1577            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1578            // bindings to insert tab characters.
 1579            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1580    }
 1581
 1582    pub fn accept_edit_prediction_keybind(
 1583        &self,
 1584        window: &Window,
 1585        cx: &App,
 1586    ) -> AcceptEditPredictionBinding {
 1587        let key_context = self.key_context_internal(true, window, cx);
 1588        let in_conflict = self.edit_prediction_in_conflict();
 1589
 1590        AcceptEditPredictionBinding(
 1591            window
 1592                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1593                .into_iter()
 1594                .filter(|binding| {
 1595                    !in_conflict
 1596                        || binding
 1597                            .keystrokes()
 1598                            .first()
 1599                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1600                })
 1601                .rev()
 1602                .min_by_key(|binding| {
 1603                    binding
 1604                        .keystrokes()
 1605                        .first()
 1606                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1607                }),
 1608        )
 1609    }
 1610
 1611    pub fn new_file(
 1612        workspace: &mut Workspace,
 1613        _: &workspace::NewFile,
 1614        window: &mut Window,
 1615        cx: &mut Context<Workspace>,
 1616    ) {
 1617        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1618            "Failed to create buffer",
 1619            window,
 1620            cx,
 1621            |e, _, _| match e.error_code() {
 1622                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1623                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1624                e.error_tag("required").unwrap_or("the latest version")
 1625            )),
 1626                _ => None,
 1627            },
 1628        );
 1629    }
 1630
 1631    pub fn new_in_workspace(
 1632        workspace: &mut Workspace,
 1633        window: &mut Window,
 1634        cx: &mut Context<Workspace>,
 1635    ) -> Task<Result<Entity<Editor>>> {
 1636        let project = workspace.project().clone();
 1637        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1638
 1639        cx.spawn_in(window, |workspace, mut cx| async move {
 1640            let buffer = create.await?;
 1641            workspace.update_in(&mut cx, |workspace, window, cx| {
 1642                let editor =
 1643                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1644                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1645                editor
 1646            })
 1647        })
 1648    }
 1649
 1650    fn new_file_vertical(
 1651        workspace: &mut Workspace,
 1652        _: &workspace::NewFileSplitVertical,
 1653        window: &mut Window,
 1654        cx: &mut Context<Workspace>,
 1655    ) {
 1656        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1657    }
 1658
 1659    fn new_file_horizontal(
 1660        workspace: &mut Workspace,
 1661        _: &workspace::NewFileSplitHorizontal,
 1662        window: &mut Window,
 1663        cx: &mut Context<Workspace>,
 1664    ) {
 1665        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1666    }
 1667
 1668    fn new_file_in_direction(
 1669        workspace: &mut Workspace,
 1670        direction: SplitDirection,
 1671        window: &mut Window,
 1672        cx: &mut Context<Workspace>,
 1673    ) {
 1674        let project = workspace.project().clone();
 1675        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1676
 1677        cx.spawn_in(window, |workspace, mut cx| async move {
 1678            let buffer = create.await?;
 1679            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1680                workspace.split_item(
 1681                    direction,
 1682                    Box::new(
 1683                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1684                    ),
 1685                    window,
 1686                    cx,
 1687                )
 1688            })?;
 1689            anyhow::Ok(())
 1690        })
 1691        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1692            match e.error_code() {
 1693                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1694                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1695                e.error_tag("required").unwrap_or("the latest version")
 1696            )),
 1697                _ => None,
 1698            }
 1699        });
 1700    }
 1701
 1702    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1703        self.leader_peer_id
 1704    }
 1705
 1706    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1707        &self.buffer
 1708    }
 1709
 1710    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1711        self.workspace.as_ref()?.0.upgrade()
 1712    }
 1713
 1714    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1715        self.buffer().read(cx).title(cx)
 1716    }
 1717
 1718    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1719        let git_blame_gutter_max_author_length = self
 1720            .render_git_blame_gutter(cx)
 1721            .then(|| {
 1722                if let Some(blame) = self.blame.as_ref() {
 1723                    let max_author_length =
 1724                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1725                    Some(max_author_length)
 1726                } else {
 1727                    None
 1728                }
 1729            })
 1730            .flatten();
 1731
 1732        EditorSnapshot {
 1733            mode: self.mode,
 1734            show_gutter: self.show_gutter,
 1735            show_line_numbers: self.show_line_numbers,
 1736            show_git_diff_gutter: self.show_git_diff_gutter,
 1737            show_code_actions: self.show_code_actions,
 1738            show_runnables: self.show_runnables,
 1739            git_blame_gutter_max_author_length,
 1740            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1741            scroll_anchor: self.scroll_manager.anchor(),
 1742            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1743            placeholder_text: self.placeholder_text.clone(),
 1744            is_focused: self.focus_handle.is_focused(window),
 1745            current_line_highlight: self
 1746                .current_line_highlight
 1747                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1748            gutter_hovered: self.gutter_hovered,
 1749        }
 1750    }
 1751
 1752    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1753        self.buffer.read(cx).language_at(point, cx)
 1754    }
 1755
 1756    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1757        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1758    }
 1759
 1760    pub fn active_excerpt(
 1761        &self,
 1762        cx: &App,
 1763    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1764        self.buffer
 1765            .read(cx)
 1766            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1767    }
 1768
 1769    pub fn mode(&self) -> EditorMode {
 1770        self.mode
 1771    }
 1772
 1773    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1774        self.collaboration_hub.as_deref()
 1775    }
 1776
 1777    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1778        self.collaboration_hub = Some(hub);
 1779    }
 1780
 1781    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1782        self.in_project_search = in_project_search;
 1783    }
 1784
 1785    pub fn set_custom_context_menu(
 1786        &mut self,
 1787        f: impl 'static
 1788            + Fn(
 1789                &mut Self,
 1790                DisplayPoint,
 1791                &mut Window,
 1792                &mut Context<Self>,
 1793            ) -> Option<Entity<ui::ContextMenu>>,
 1794    ) {
 1795        self.custom_context_menu = Some(Box::new(f))
 1796    }
 1797
 1798    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1799        self.completion_provider = provider;
 1800    }
 1801
 1802    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1803        self.semantics_provider.clone()
 1804    }
 1805
 1806    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1807        self.semantics_provider = provider;
 1808    }
 1809
 1810    pub fn set_edit_prediction_provider<T>(
 1811        &mut self,
 1812        provider: Option<Entity<T>>,
 1813        window: &mut Window,
 1814        cx: &mut Context<Self>,
 1815    ) where
 1816        T: EditPredictionProvider,
 1817    {
 1818        self.edit_prediction_provider =
 1819            provider.map(|provider| RegisteredInlineCompletionProvider {
 1820                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1821                    if this.focus_handle.is_focused(window) {
 1822                        this.update_visible_inline_completion(window, cx);
 1823                    }
 1824                }),
 1825                provider: Arc::new(provider),
 1826            });
 1827        self.update_edit_prediction_settings(cx);
 1828        self.refresh_inline_completion(false, false, window, cx);
 1829    }
 1830
 1831    pub fn placeholder_text(&self) -> Option<&str> {
 1832        self.placeholder_text.as_deref()
 1833    }
 1834
 1835    pub fn set_placeholder_text(
 1836        &mut self,
 1837        placeholder_text: impl Into<Arc<str>>,
 1838        cx: &mut Context<Self>,
 1839    ) {
 1840        let placeholder_text = Some(placeholder_text.into());
 1841        if self.placeholder_text != placeholder_text {
 1842            self.placeholder_text = placeholder_text;
 1843            cx.notify();
 1844        }
 1845    }
 1846
 1847    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1848        self.cursor_shape = cursor_shape;
 1849
 1850        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1851        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1852
 1853        cx.notify();
 1854    }
 1855
 1856    pub fn set_current_line_highlight(
 1857        &mut self,
 1858        current_line_highlight: Option<CurrentLineHighlight>,
 1859    ) {
 1860        self.current_line_highlight = current_line_highlight;
 1861    }
 1862
 1863    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1864        self.collapse_matches = collapse_matches;
 1865    }
 1866
 1867    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1868        let buffers = self.buffer.read(cx).all_buffers();
 1869        let Some(project) = self.project.as_ref() else {
 1870            return;
 1871        };
 1872        project.update(cx, |project, cx| {
 1873            for buffer in buffers {
 1874                self.registered_buffers
 1875                    .entry(buffer.read(cx).remote_id())
 1876                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1877            }
 1878        })
 1879    }
 1880
 1881    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1882        if self.collapse_matches {
 1883            return range.start..range.start;
 1884        }
 1885        range.clone()
 1886    }
 1887
 1888    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1889        if self.display_map.read(cx).clip_at_line_ends != clip {
 1890            self.display_map
 1891                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1892        }
 1893    }
 1894
 1895    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1896        self.input_enabled = input_enabled;
 1897    }
 1898
 1899    pub fn set_inline_completions_hidden_for_vim_mode(
 1900        &mut self,
 1901        hidden: bool,
 1902        window: &mut Window,
 1903        cx: &mut Context<Self>,
 1904    ) {
 1905        if hidden != self.inline_completions_hidden_for_vim_mode {
 1906            self.inline_completions_hidden_for_vim_mode = hidden;
 1907            if hidden {
 1908                self.update_visible_inline_completion(window, cx);
 1909            } else {
 1910                self.refresh_inline_completion(true, false, window, cx);
 1911            }
 1912        }
 1913    }
 1914
 1915    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1916        self.menu_inline_completions_policy = value;
 1917    }
 1918
 1919    pub fn set_autoindent(&mut self, autoindent: bool) {
 1920        if autoindent {
 1921            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1922        } else {
 1923            self.autoindent_mode = None;
 1924        }
 1925    }
 1926
 1927    pub fn read_only(&self, cx: &App) -> bool {
 1928        self.read_only || self.buffer.read(cx).read_only()
 1929    }
 1930
 1931    pub fn set_read_only(&mut self, read_only: bool) {
 1932        self.read_only = read_only;
 1933    }
 1934
 1935    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1936        self.use_autoclose = autoclose;
 1937    }
 1938
 1939    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1940        self.use_auto_surround = auto_surround;
 1941    }
 1942
 1943    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1944        self.auto_replace_emoji_shortcode = auto_replace;
 1945    }
 1946
 1947    pub fn toggle_edit_predictions(
 1948        &mut self,
 1949        _: &ToggleEditPrediction,
 1950        window: &mut Window,
 1951        cx: &mut Context<Self>,
 1952    ) {
 1953        if self.show_inline_completions_override.is_some() {
 1954            self.set_show_edit_predictions(None, window, cx);
 1955        } else {
 1956            let show_edit_predictions = !self.edit_predictions_enabled();
 1957            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1958        }
 1959    }
 1960
 1961    pub fn set_show_edit_predictions(
 1962        &mut self,
 1963        show_edit_predictions: Option<bool>,
 1964        window: &mut Window,
 1965        cx: &mut Context<Self>,
 1966    ) {
 1967        self.show_inline_completions_override = show_edit_predictions;
 1968        self.update_edit_prediction_settings(cx);
 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_indent_conflict = 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.edit_predictions_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    pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
 4877        if self.edit_prediction_provider.is_none() {
 4878            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 4879        } else {
 4880            let selection = self.selections.newest_anchor();
 4881            let cursor = selection.head();
 4882
 4883            if let Some((buffer, cursor_buffer_position)) =
 4884                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4885            {
 4886                self.edit_prediction_settings =
 4887                    self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 4888            }
 4889        }
 4890    }
 4891
 4892    fn edit_prediction_settings_at_position(
 4893        &self,
 4894        buffer: &Entity<Buffer>,
 4895        buffer_position: language::Anchor,
 4896        cx: &App,
 4897    ) -> EditPredictionSettings {
 4898        if self.mode != EditorMode::Full
 4899            || !self.show_inline_completions_override.unwrap_or(true)
 4900            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4901        {
 4902            return EditPredictionSettings::Disabled;
 4903        }
 4904
 4905        let buffer = buffer.read(cx);
 4906
 4907        let file = buffer.file();
 4908
 4909        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4910            return EditPredictionSettings::Disabled;
 4911        };
 4912
 4913        let by_provider = matches!(
 4914            self.menu_inline_completions_policy,
 4915            MenuInlineCompletionsPolicy::ByProvider
 4916        );
 4917
 4918        let show_in_menu = by_provider
 4919            && self
 4920                .edit_prediction_provider
 4921                .as_ref()
 4922                .map_or(false, |provider| {
 4923                    provider.provider.show_completions_in_menu()
 4924                });
 4925
 4926        let preview_requires_modifier =
 4927            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4928
 4929        EditPredictionSettings::Enabled {
 4930            show_in_menu,
 4931            preview_requires_modifier,
 4932        }
 4933    }
 4934
 4935    fn should_show_edit_predictions(&self) -> bool {
 4936        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4937    }
 4938
 4939    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4940        matches!(
 4941            self.edit_prediction_preview,
 4942            EditPredictionPreview::Active { .. }
 4943        )
 4944    }
 4945
 4946    pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
 4947        let cursor = self.selections.newest_anchor().head();
 4948        if let Some((buffer, cursor_position)) =
 4949            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4950        {
 4951            self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
 4952        } else {
 4953            false
 4954        }
 4955    }
 4956
 4957    fn edit_predictions_enabled_in_buffer(
 4958        &self,
 4959        buffer: &Entity<Buffer>,
 4960        buffer_position: language::Anchor,
 4961        cx: &App,
 4962    ) -> bool {
 4963        maybe!({
 4964            let provider = self.edit_prediction_provider()?;
 4965            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4966                return Some(false);
 4967            }
 4968            let buffer = buffer.read(cx);
 4969            let Some(file) = buffer.file() else {
 4970                return Some(true);
 4971            };
 4972            let settings = all_language_settings(Some(file), cx);
 4973            Some(settings.inline_completions_enabled_for_path(file.path()))
 4974        })
 4975        .unwrap_or(false)
 4976    }
 4977
 4978    fn cycle_inline_completion(
 4979        &mut self,
 4980        direction: Direction,
 4981        window: &mut Window,
 4982        cx: &mut Context<Self>,
 4983    ) -> Option<()> {
 4984        let provider = self.edit_prediction_provider()?;
 4985        let cursor = self.selections.newest_anchor().head();
 4986        let (buffer, cursor_buffer_position) =
 4987            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4988        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4989            return None;
 4990        }
 4991
 4992        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4993        self.update_visible_inline_completion(window, cx);
 4994
 4995        Some(())
 4996    }
 4997
 4998    pub fn show_inline_completion(
 4999        &mut self,
 5000        _: &ShowEditPrediction,
 5001        window: &mut Window,
 5002        cx: &mut Context<Self>,
 5003    ) {
 5004        if !self.has_active_inline_completion() {
 5005            self.refresh_inline_completion(false, true, window, cx);
 5006            return;
 5007        }
 5008
 5009        self.update_visible_inline_completion(window, cx);
 5010    }
 5011
 5012    pub fn display_cursor_names(
 5013        &mut self,
 5014        _: &DisplayCursorNames,
 5015        window: &mut Window,
 5016        cx: &mut Context<Self>,
 5017    ) {
 5018        self.show_cursor_names(window, cx);
 5019    }
 5020
 5021    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5022        self.show_cursor_names = true;
 5023        cx.notify();
 5024        cx.spawn_in(window, |this, mut cx| async move {
 5025            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5026            this.update(&mut cx, |this, cx| {
 5027                this.show_cursor_names = false;
 5028                cx.notify()
 5029            })
 5030            .ok()
 5031        })
 5032        .detach();
 5033    }
 5034
 5035    pub fn next_edit_prediction(
 5036        &mut self,
 5037        _: &NextEditPrediction,
 5038        window: &mut Window,
 5039        cx: &mut Context<Self>,
 5040    ) {
 5041        if self.has_active_inline_completion() {
 5042            self.cycle_inline_completion(Direction::Next, window, cx);
 5043        } else {
 5044            let is_copilot_disabled = self
 5045                .refresh_inline_completion(false, true, window, cx)
 5046                .is_none();
 5047            if is_copilot_disabled {
 5048                cx.propagate();
 5049            }
 5050        }
 5051    }
 5052
 5053    pub fn previous_edit_prediction(
 5054        &mut self,
 5055        _: &PreviousEditPrediction,
 5056        window: &mut Window,
 5057        cx: &mut Context<Self>,
 5058    ) {
 5059        if self.has_active_inline_completion() {
 5060            self.cycle_inline_completion(Direction::Prev, window, cx);
 5061        } else {
 5062            let is_copilot_disabled = self
 5063                .refresh_inline_completion(false, true, window, cx)
 5064                .is_none();
 5065            if is_copilot_disabled {
 5066                cx.propagate();
 5067            }
 5068        }
 5069    }
 5070
 5071    pub fn accept_edit_prediction(
 5072        &mut self,
 5073        _: &AcceptEditPrediction,
 5074        window: &mut Window,
 5075        cx: &mut Context<Self>,
 5076    ) {
 5077        if self.show_edit_predictions_in_menu() {
 5078            self.hide_context_menu(window, cx);
 5079        }
 5080
 5081        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5082            return;
 5083        };
 5084
 5085        self.report_inline_completion_event(
 5086            active_inline_completion.completion_id.clone(),
 5087            true,
 5088            cx,
 5089        );
 5090
 5091        match &active_inline_completion.completion {
 5092            InlineCompletion::Move { target, .. } => {
 5093                let target = *target;
 5094
 5095                if let Some(position_map) = &self.last_position_map {
 5096                    if position_map
 5097                        .visible_row_range
 5098                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5099                        || !self.edit_prediction_requires_modifier()
 5100                    {
 5101                        self.unfold_ranges(&[target..target], true, false, cx);
 5102                        // Note that this is also done in vim's handler of the Tab action.
 5103                        self.change_selections(
 5104                            Some(Autoscroll::newest()),
 5105                            window,
 5106                            cx,
 5107                            |selections| {
 5108                                selections.select_anchor_ranges([target..target]);
 5109                            },
 5110                        );
 5111                        self.clear_row_highlights::<EditPredictionPreview>();
 5112
 5113                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5114                            previous_scroll_position: None,
 5115                        };
 5116                    } else {
 5117                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5118                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5119                        };
 5120                        self.highlight_rows::<EditPredictionPreview>(
 5121                            target..target,
 5122                            cx.theme().colors().editor_highlighted_line_background,
 5123                            true,
 5124                            cx,
 5125                        );
 5126                        self.request_autoscroll(Autoscroll::fit(), cx);
 5127                    }
 5128                }
 5129            }
 5130            InlineCompletion::Edit { edits, .. } => {
 5131                if let Some(provider) = self.edit_prediction_provider() {
 5132                    provider.accept(cx);
 5133                }
 5134
 5135                let snapshot = self.buffer.read(cx).snapshot(cx);
 5136                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5137
 5138                self.buffer.update(cx, |buffer, cx| {
 5139                    buffer.edit(edits.iter().cloned(), None, cx)
 5140                });
 5141
 5142                self.change_selections(None, window, cx, |s| {
 5143                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5144                });
 5145
 5146                self.update_visible_inline_completion(window, cx);
 5147                if self.active_inline_completion.is_none() {
 5148                    self.refresh_inline_completion(true, true, window, cx);
 5149                }
 5150
 5151                cx.notify();
 5152            }
 5153        }
 5154
 5155        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5156    }
 5157
 5158    pub fn accept_partial_inline_completion(
 5159        &mut self,
 5160        _: &AcceptPartialEditPrediction,
 5161        window: &mut Window,
 5162        cx: &mut Context<Self>,
 5163    ) {
 5164        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5165            return;
 5166        };
 5167        if self.selections.count() != 1 {
 5168            return;
 5169        }
 5170
 5171        self.report_inline_completion_event(
 5172            active_inline_completion.completion_id.clone(),
 5173            true,
 5174            cx,
 5175        );
 5176
 5177        match &active_inline_completion.completion {
 5178            InlineCompletion::Move { target, .. } => {
 5179                let target = *target;
 5180                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5181                    selections.select_anchor_ranges([target..target]);
 5182                });
 5183            }
 5184            InlineCompletion::Edit { edits, .. } => {
 5185                // Find an insertion that starts at the cursor position.
 5186                let snapshot = self.buffer.read(cx).snapshot(cx);
 5187                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5188                let insertion = edits.iter().find_map(|(range, text)| {
 5189                    let range = range.to_offset(&snapshot);
 5190                    if range.is_empty() && range.start == cursor_offset {
 5191                        Some(text)
 5192                    } else {
 5193                        None
 5194                    }
 5195                });
 5196
 5197                if let Some(text) = insertion {
 5198                    let mut partial_completion = text
 5199                        .chars()
 5200                        .by_ref()
 5201                        .take_while(|c| c.is_alphabetic())
 5202                        .collect::<String>();
 5203                    if partial_completion.is_empty() {
 5204                        partial_completion = text
 5205                            .chars()
 5206                            .by_ref()
 5207                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5208                            .collect::<String>();
 5209                    }
 5210
 5211                    cx.emit(EditorEvent::InputHandled {
 5212                        utf16_range_to_replace: None,
 5213                        text: partial_completion.clone().into(),
 5214                    });
 5215
 5216                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5217
 5218                    self.refresh_inline_completion(true, true, window, cx);
 5219                    cx.notify();
 5220                } else {
 5221                    self.accept_edit_prediction(&Default::default(), window, cx);
 5222                }
 5223            }
 5224        }
 5225    }
 5226
 5227    fn discard_inline_completion(
 5228        &mut self,
 5229        should_report_inline_completion_event: bool,
 5230        cx: &mut Context<Self>,
 5231    ) -> bool {
 5232        if should_report_inline_completion_event {
 5233            let completion_id = self
 5234                .active_inline_completion
 5235                .as_ref()
 5236                .and_then(|active_completion| active_completion.completion_id.clone());
 5237
 5238            self.report_inline_completion_event(completion_id, false, cx);
 5239        }
 5240
 5241        if let Some(provider) = self.edit_prediction_provider() {
 5242            provider.discard(cx);
 5243        }
 5244
 5245        self.take_active_inline_completion(cx)
 5246    }
 5247
 5248    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5249        let Some(provider) = self.edit_prediction_provider() else {
 5250            return;
 5251        };
 5252
 5253        let Some((_, buffer, _)) = self
 5254            .buffer
 5255            .read(cx)
 5256            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5257        else {
 5258            return;
 5259        };
 5260
 5261        let extension = buffer
 5262            .read(cx)
 5263            .file()
 5264            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5265
 5266        let event_type = match accepted {
 5267            true => "Edit Prediction Accepted",
 5268            false => "Edit Prediction Discarded",
 5269        };
 5270        telemetry::event!(
 5271            event_type,
 5272            provider = provider.name(),
 5273            prediction_id = id,
 5274            suggestion_accepted = accepted,
 5275            file_extension = extension,
 5276        );
 5277    }
 5278
 5279    pub fn has_active_inline_completion(&self) -> bool {
 5280        self.active_inline_completion.is_some()
 5281    }
 5282
 5283    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5284        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5285            return false;
 5286        };
 5287
 5288        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5289        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5290        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5291        true
 5292    }
 5293
 5294    /// Returns true when we're displaying the edit prediction popover below the cursor
 5295    /// like we are not previewing and the LSP autocomplete menu is visible
 5296    /// or we are in `when_holding_modifier` mode.
 5297    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5298        if self.edit_prediction_preview_is_active()
 5299            || !self.show_edit_predictions_in_menu()
 5300            || !self.edit_predictions_enabled()
 5301        {
 5302            return false;
 5303        }
 5304
 5305        if self.has_visible_completions_menu() {
 5306            return true;
 5307        }
 5308
 5309        has_completion && self.edit_prediction_requires_modifier()
 5310    }
 5311
 5312    fn handle_modifiers_changed(
 5313        &mut self,
 5314        modifiers: Modifiers,
 5315        position_map: &PositionMap,
 5316        window: &mut Window,
 5317        cx: &mut Context<Self>,
 5318    ) {
 5319        if self.show_edit_predictions_in_menu() {
 5320            self.update_edit_prediction_preview(&modifiers, window, cx);
 5321        }
 5322
 5323        self.update_selection_mode(&modifiers, position_map, window, cx);
 5324
 5325        let mouse_position = window.mouse_position();
 5326        if !position_map.text_hitbox.is_hovered(window) {
 5327            return;
 5328        }
 5329
 5330        self.update_hovered_link(
 5331            position_map.point_for_position(mouse_position),
 5332            &position_map.snapshot,
 5333            modifiers,
 5334            window,
 5335            cx,
 5336        )
 5337    }
 5338
 5339    fn update_selection_mode(
 5340        &mut self,
 5341        modifiers: &Modifiers,
 5342        position_map: &PositionMap,
 5343        window: &mut Window,
 5344        cx: &mut Context<Self>,
 5345    ) {
 5346        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5347            return;
 5348        }
 5349
 5350        let mouse_position = window.mouse_position();
 5351        let point_for_position = position_map.point_for_position(mouse_position);
 5352        let position = point_for_position.previous_valid;
 5353
 5354        self.select(
 5355            SelectPhase::BeginColumnar {
 5356                position,
 5357                reset: false,
 5358                goal_column: point_for_position.exact_unclipped.column(),
 5359            },
 5360            window,
 5361            cx,
 5362        );
 5363    }
 5364
 5365    fn update_edit_prediction_preview(
 5366        &mut self,
 5367        modifiers: &Modifiers,
 5368        window: &mut Window,
 5369        cx: &mut Context<Self>,
 5370    ) {
 5371        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5372        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5373            return;
 5374        };
 5375
 5376        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5377            if matches!(
 5378                self.edit_prediction_preview,
 5379                EditPredictionPreview::Inactive
 5380            ) {
 5381                self.edit_prediction_preview = EditPredictionPreview::Active {
 5382                    previous_scroll_position: None,
 5383                };
 5384
 5385                self.update_visible_inline_completion(window, cx);
 5386                cx.notify();
 5387            }
 5388        } else if let EditPredictionPreview::Active {
 5389            previous_scroll_position,
 5390        } = self.edit_prediction_preview
 5391        {
 5392            if let (Some(previous_scroll_position), Some(position_map)) =
 5393                (previous_scroll_position, self.last_position_map.as_ref())
 5394            {
 5395                self.set_scroll_position(
 5396                    previous_scroll_position
 5397                        .scroll_position(&position_map.snapshot.display_snapshot),
 5398                    window,
 5399                    cx,
 5400                );
 5401            }
 5402
 5403            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5404            self.clear_row_highlights::<EditPredictionPreview>();
 5405            self.update_visible_inline_completion(window, cx);
 5406            cx.notify();
 5407        }
 5408    }
 5409
 5410    fn update_visible_inline_completion(
 5411        &mut self,
 5412        _window: &mut Window,
 5413        cx: &mut Context<Self>,
 5414    ) -> Option<()> {
 5415        let selection = self.selections.newest_anchor();
 5416        let cursor = selection.head();
 5417        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5418        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5419        let excerpt_id = cursor.excerpt_id;
 5420
 5421        let show_in_menu = self.show_edit_predictions_in_menu();
 5422        let completions_menu_has_precedence = !show_in_menu
 5423            && (self.context_menu.borrow().is_some()
 5424                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5425
 5426        if completions_menu_has_precedence
 5427            || !offset_selection.is_empty()
 5428            || self
 5429                .active_inline_completion
 5430                .as_ref()
 5431                .map_or(false, |completion| {
 5432                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5433                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5434                    !invalidation_range.contains(&offset_selection.head())
 5435                })
 5436        {
 5437            self.discard_inline_completion(false, cx);
 5438            return None;
 5439        }
 5440
 5441        self.take_active_inline_completion(cx);
 5442        let Some(provider) = self.edit_prediction_provider() else {
 5443            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5444            return None;
 5445        };
 5446
 5447        let (buffer, cursor_buffer_position) =
 5448            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5449
 5450        self.edit_prediction_settings =
 5451            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5452
 5453        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5454
 5455        if self.edit_prediction_indent_conflict {
 5456            let cursor_point = cursor.to_point(&multibuffer);
 5457
 5458            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5459
 5460            if let Some((_, indent)) = indents.iter().next() {
 5461                if indent.len == cursor_point.column {
 5462                    self.edit_prediction_indent_conflict = false;
 5463                }
 5464            }
 5465        }
 5466
 5467        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5468        let edits = inline_completion
 5469            .edits
 5470            .into_iter()
 5471            .flat_map(|(range, new_text)| {
 5472                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5473                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5474                Some((start..end, new_text))
 5475            })
 5476            .collect::<Vec<_>>();
 5477        if edits.is_empty() {
 5478            return None;
 5479        }
 5480
 5481        let first_edit_start = edits.first().unwrap().0.start;
 5482        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5483        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5484
 5485        let last_edit_end = edits.last().unwrap().0.end;
 5486        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5487        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5488
 5489        let cursor_row = cursor.to_point(&multibuffer).row;
 5490
 5491        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5492
 5493        let mut inlay_ids = Vec::new();
 5494        let invalidation_row_range;
 5495        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5496            Some(cursor_row..edit_end_row)
 5497        } else if cursor_row > edit_end_row {
 5498            Some(edit_start_row..cursor_row)
 5499        } else {
 5500            None
 5501        };
 5502        let is_move =
 5503            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5504        let completion = if is_move {
 5505            invalidation_row_range =
 5506                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5507            let target = first_edit_start;
 5508            InlineCompletion::Move { target, snapshot }
 5509        } else {
 5510            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5511                && !self.inline_completions_hidden_for_vim_mode;
 5512
 5513            if show_completions_in_buffer {
 5514                if edits
 5515                    .iter()
 5516                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5517                {
 5518                    let mut inlays = Vec::new();
 5519                    for (range, new_text) in &edits {
 5520                        let inlay = Inlay::inline_completion(
 5521                            post_inc(&mut self.next_inlay_id),
 5522                            range.start,
 5523                            new_text.as_str(),
 5524                        );
 5525                        inlay_ids.push(inlay.id);
 5526                        inlays.push(inlay);
 5527                    }
 5528
 5529                    self.splice_inlays(&[], inlays, cx);
 5530                } else {
 5531                    let background_color = cx.theme().status().deleted_background;
 5532                    self.highlight_text::<InlineCompletionHighlight>(
 5533                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5534                        HighlightStyle {
 5535                            background_color: Some(background_color),
 5536                            ..Default::default()
 5537                        },
 5538                        cx,
 5539                    );
 5540                }
 5541            }
 5542
 5543            invalidation_row_range = edit_start_row..edit_end_row;
 5544
 5545            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5546                if provider.show_tab_accept_marker() {
 5547                    EditDisplayMode::TabAccept
 5548                } else {
 5549                    EditDisplayMode::Inline
 5550                }
 5551            } else {
 5552                EditDisplayMode::DiffPopover
 5553            };
 5554
 5555            InlineCompletion::Edit {
 5556                edits,
 5557                edit_preview: inline_completion.edit_preview,
 5558                display_mode,
 5559                snapshot,
 5560            }
 5561        };
 5562
 5563        let invalidation_range = multibuffer
 5564            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5565            ..multibuffer.anchor_after(Point::new(
 5566                invalidation_row_range.end,
 5567                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5568            ));
 5569
 5570        self.stale_inline_completion_in_menu = None;
 5571        self.active_inline_completion = Some(InlineCompletionState {
 5572            inlay_ids,
 5573            completion,
 5574            completion_id: inline_completion.id,
 5575            invalidation_range,
 5576        });
 5577
 5578        cx.notify();
 5579
 5580        Some(())
 5581    }
 5582
 5583    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5584        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5585    }
 5586
 5587    fn render_code_actions_indicator(
 5588        &self,
 5589        _style: &EditorStyle,
 5590        row: DisplayRow,
 5591        is_active: bool,
 5592        cx: &mut Context<Self>,
 5593    ) -> Option<IconButton> {
 5594        if self.available_code_actions.is_some() {
 5595            Some(
 5596                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5597                    .shape(ui::IconButtonShape::Square)
 5598                    .icon_size(IconSize::XSmall)
 5599                    .icon_color(Color::Muted)
 5600                    .toggle_state(is_active)
 5601                    .tooltip({
 5602                        let focus_handle = self.focus_handle.clone();
 5603                        move |window, cx| {
 5604                            Tooltip::for_action_in(
 5605                                "Toggle Code Actions",
 5606                                &ToggleCodeActions {
 5607                                    deployed_from_indicator: None,
 5608                                },
 5609                                &focus_handle,
 5610                                window,
 5611                                cx,
 5612                            )
 5613                        }
 5614                    })
 5615                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5616                        window.focus(&editor.focus_handle(cx));
 5617                        editor.toggle_code_actions(
 5618                            &ToggleCodeActions {
 5619                                deployed_from_indicator: Some(row),
 5620                            },
 5621                            window,
 5622                            cx,
 5623                        );
 5624                    })),
 5625            )
 5626        } else {
 5627            None
 5628        }
 5629    }
 5630
 5631    fn clear_tasks(&mut self) {
 5632        self.tasks.clear()
 5633    }
 5634
 5635    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5636        if self.tasks.insert(key, value).is_some() {
 5637            // This case should hopefully be rare, but just in case...
 5638            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5639        }
 5640    }
 5641
 5642    fn build_tasks_context(
 5643        project: &Entity<Project>,
 5644        buffer: &Entity<Buffer>,
 5645        buffer_row: u32,
 5646        tasks: &Arc<RunnableTasks>,
 5647        cx: &mut Context<Self>,
 5648    ) -> Task<Option<task::TaskContext>> {
 5649        let position = Point::new(buffer_row, tasks.column);
 5650        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5651        let location = Location {
 5652            buffer: buffer.clone(),
 5653            range: range_start..range_start,
 5654        };
 5655        // Fill in the environmental variables from the tree-sitter captures
 5656        let mut captured_task_variables = TaskVariables::default();
 5657        for (capture_name, value) in tasks.extra_variables.clone() {
 5658            captured_task_variables.insert(
 5659                task::VariableName::Custom(capture_name.into()),
 5660                value.clone(),
 5661            );
 5662        }
 5663        project.update(cx, |project, cx| {
 5664            project.task_store().update(cx, |task_store, cx| {
 5665                task_store.task_context_for_location(captured_task_variables, location, cx)
 5666            })
 5667        })
 5668    }
 5669
 5670    pub fn spawn_nearest_task(
 5671        &mut self,
 5672        action: &SpawnNearestTask,
 5673        window: &mut Window,
 5674        cx: &mut Context<Self>,
 5675    ) {
 5676        let Some((workspace, _)) = self.workspace.clone() else {
 5677            return;
 5678        };
 5679        let Some(project) = self.project.clone() else {
 5680            return;
 5681        };
 5682
 5683        // Try to find a closest, enclosing node using tree-sitter that has a
 5684        // task
 5685        let Some((buffer, buffer_row, tasks)) = self
 5686            .find_enclosing_node_task(cx)
 5687            // Or find the task that's closest in row-distance.
 5688            .or_else(|| self.find_closest_task(cx))
 5689        else {
 5690            return;
 5691        };
 5692
 5693        let reveal_strategy = action.reveal;
 5694        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5695        cx.spawn_in(window, |_, mut cx| async move {
 5696            let context = task_context.await?;
 5697            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5698
 5699            let resolved = resolved_task.resolved.as_mut()?;
 5700            resolved.reveal = reveal_strategy;
 5701
 5702            workspace
 5703                .update(&mut cx, |workspace, cx| {
 5704                    workspace::tasks::schedule_resolved_task(
 5705                        workspace,
 5706                        task_source_kind,
 5707                        resolved_task,
 5708                        false,
 5709                        cx,
 5710                    );
 5711                })
 5712                .ok()
 5713        })
 5714        .detach();
 5715    }
 5716
 5717    fn find_closest_task(
 5718        &mut self,
 5719        cx: &mut Context<Self>,
 5720    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5721        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5722
 5723        let ((buffer_id, row), tasks) = self
 5724            .tasks
 5725            .iter()
 5726            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5727
 5728        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5729        let tasks = Arc::new(tasks.to_owned());
 5730        Some((buffer, *row, tasks))
 5731    }
 5732
 5733    fn find_enclosing_node_task(
 5734        &mut self,
 5735        cx: &mut Context<Self>,
 5736    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5737        let snapshot = self.buffer.read(cx).snapshot(cx);
 5738        let offset = self.selections.newest::<usize>(cx).head();
 5739        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5740        let buffer_id = excerpt.buffer().remote_id();
 5741
 5742        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5743        let mut cursor = layer.node().walk();
 5744
 5745        while cursor.goto_first_child_for_byte(offset).is_some() {
 5746            if cursor.node().end_byte() == offset {
 5747                cursor.goto_next_sibling();
 5748            }
 5749        }
 5750
 5751        // Ascend to the smallest ancestor that contains the range and has a task.
 5752        loop {
 5753            let node = cursor.node();
 5754            let node_range = node.byte_range();
 5755            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5756
 5757            // Check if this node contains our offset
 5758            if node_range.start <= offset && node_range.end >= offset {
 5759                // If it contains offset, check for task
 5760                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5761                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5762                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5763                }
 5764            }
 5765
 5766            if !cursor.goto_parent() {
 5767                break;
 5768            }
 5769        }
 5770        None
 5771    }
 5772
 5773    fn render_run_indicator(
 5774        &self,
 5775        _style: &EditorStyle,
 5776        is_active: bool,
 5777        row: DisplayRow,
 5778        cx: &mut Context<Self>,
 5779    ) -> IconButton {
 5780        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5781            .shape(ui::IconButtonShape::Square)
 5782            .icon_size(IconSize::XSmall)
 5783            .icon_color(Color::Muted)
 5784            .toggle_state(is_active)
 5785            .on_click(cx.listener(move |editor, _e, window, cx| {
 5786                window.focus(&editor.focus_handle(cx));
 5787                editor.toggle_code_actions(
 5788                    &ToggleCodeActions {
 5789                        deployed_from_indicator: Some(row),
 5790                    },
 5791                    window,
 5792                    cx,
 5793                );
 5794            }))
 5795    }
 5796
 5797    pub fn context_menu_visible(&self) -> bool {
 5798        !self.edit_prediction_preview_is_active()
 5799            && self
 5800                .context_menu
 5801                .borrow()
 5802                .as_ref()
 5803                .map_or(false, |menu| menu.visible())
 5804    }
 5805
 5806    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5807        self.context_menu
 5808            .borrow()
 5809            .as_ref()
 5810            .map(|menu| menu.origin())
 5811    }
 5812
 5813    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5814    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5815
 5816    #[allow(clippy::too_many_arguments)]
 5817    fn render_edit_prediction_popover(
 5818        &mut self,
 5819        text_bounds: &Bounds<Pixels>,
 5820        content_origin: gpui::Point<Pixels>,
 5821        editor_snapshot: &EditorSnapshot,
 5822        visible_row_range: Range<DisplayRow>,
 5823        scroll_top: f32,
 5824        scroll_bottom: f32,
 5825        line_layouts: &[LineWithInvisibles],
 5826        line_height: Pixels,
 5827        scroll_pixel_position: gpui::Point<Pixels>,
 5828        newest_selection_head: Option<DisplayPoint>,
 5829        editor_width: Pixels,
 5830        style: &EditorStyle,
 5831        window: &mut Window,
 5832        cx: &mut App,
 5833    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5834        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5835
 5836        if self.edit_prediction_visible_in_cursor_popover(true) {
 5837            return None;
 5838        }
 5839
 5840        match &active_inline_completion.completion {
 5841            InlineCompletion::Move { target, .. } => {
 5842                let target_display_point = target.to_display_point(editor_snapshot);
 5843
 5844                if self.edit_prediction_requires_modifier() {
 5845                    if !self.edit_prediction_preview_is_active() {
 5846                        return None;
 5847                    }
 5848
 5849                    self.render_edit_prediction_modifier_jump_popover(
 5850                        text_bounds,
 5851                        content_origin,
 5852                        visible_row_range,
 5853                        line_layouts,
 5854                        line_height,
 5855                        scroll_pixel_position,
 5856                        newest_selection_head,
 5857                        target_display_point,
 5858                        window,
 5859                        cx,
 5860                    )
 5861                } else {
 5862                    self.render_edit_prediction_eager_jump_popover(
 5863                        text_bounds,
 5864                        content_origin,
 5865                        editor_snapshot,
 5866                        visible_row_range,
 5867                        scroll_top,
 5868                        scroll_bottom,
 5869                        line_height,
 5870                        scroll_pixel_position,
 5871                        target_display_point,
 5872                        editor_width,
 5873                        window,
 5874                        cx,
 5875                    )
 5876                }
 5877            }
 5878            InlineCompletion::Edit {
 5879                display_mode: EditDisplayMode::Inline,
 5880                ..
 5881            } => None,
 5882            InlineCompletion::Edit {
 5883                display_mode: EditDisplayMode::TabAccept,
 5884                edits,
 5885                ..
 5886            } => {
 5887                let range = &edits.first()?.0;
 5888                let target_display_point = range.end.to_display_point(editor_snapshot);
 5889
 5890                self.render_edit_prediction_end_of_line_popover(
 5891                    "Accept",
 5892                    editor_snapshot,
 5893                    visible_row_range,
 5894                    target_display_point,
 5895                    line_height,
 5896                    scroll_pixel_position,
 5897                    content_origin,
 5898                    editor_width,
 5899                    window,
 5900                    cx,
 5901                )
 5902            }
 5903            InlineCompletion::Edit {
 5904                edits,
 5905                edit_preview,
 5906                display_mode: EditDisplayMode::DiffPopover,
 5907                snapshot,
 5908            } => self.render_edit_prediction_diff_popover(
 5909                text_bounds,
 5910                content_origin,
 5911                editor_snapshot,
 5912                visible_row_range,
 5913                line_layouts,
 5914                line_height,
 5915                scroll_pixel_position,
 5916                newest_selection_head,
 5917                editor_width,
 5918                style,
 5919                edits,
 5920                edit_preview,
 5921                snapshot,
 5922                window,
 5923                cx,
 5924            ),
 5925        }
 5926    }
 5927
 5928    #[allow(clippy::too_many_arguments)]
 5929    fn render_edit_prediction_modifier_jump_popover(
 5930        &mut self,
 5931        text_bounds: &Bounds<Pixels>,
 5932        content_origin: gpui::Point<Pixels>,
 5933        visible_row_range: Range<DisplayRow>,
 5934        line_layouts: &[LineWithInvisibles],
 5935        line_height: Pixels,
 5936        scroll_pixel_position: gpui::Point<Pixels>,
 5937        newest_selection_head: Option<DisplayPoint>,
 5938        target_display_point: DisplayPoint,
 5939        window: &mut Window,
 5940        cx: &mut App,
 5941    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5942        let scrolled_content_origin =
 5943            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 5944
 5945        const SCROLL_PADDING_Y: Pixels = px(12.);
 5946
 5947        if target_display_point.row() < visible_row_range.start {
 5948            return self.render_edit_prediction_scroll_popover(
 5949                |_| SCROLL_PADDING_Y,
 5950                IconName::ArrowUp,
 5951                visible_row_range,
 5952                line_layouts,
 5953                newest_selection_head,
 5954                scrolled_content_origin,
 5955                window,
 5956                cx,
 5957            );
 5958        } else if target_display_point.row() >= visible_row_range.end {
 5959            return self.render_edit_prediction_scroll_popover(
 5960                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 5961                IconName::ArrowDown,
 5962                visible_row_range,
 5963                line_layouts,
 5964                newest_selection_head,
 5965                scrolled_content_origin,
 5966                window,
 5967                cx,
 5968            );
 5969        }
 5970
 5971        const POLE_WIDTH: Pixels = px(2.);
 5972
 5973        let mut element = v_flex()
 5974            .items_end()
 5975            .child(
 5976                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 5977                    .rounded_br(px(0.))
 5978                    .rounded_tr(px(0.))
 5979                    .border_r_2(),
 5980            )
 5981            .child(
 5982                div()
 5983                    .w(POLE_WIDTH)
 5984                    .bg(Editor::edit_prediction_callout_popover_border_color(cx))
 5985                    .h(line_height),
 5986            )
 5987            .into_any();
 5988
 5989        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 5990
 5991        let line_layout =
 5992            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 5993        let target_column = target_display_point.column() as usize;
 5994
 5995        let target_x = line_layout.x_for_index(target_column);
 5996        let target_y =
 5997            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 5998
 5999        let mut origin = scrolled_content_origin + point(target_x, target_y)
 6000            - point(size.width - POLE_WIDTH, size.height - line_height);
 6001
 6002        origin.x = origin.x.max(content_origin.x);
 6003
 6004        element.prepaint_at(origin, window, cx);
 6005
 6006        Some((element, origin))
 6007    }
 6008
 6009    #[allow(clippy::too_many_arguments)]
 6010    fn render_edit_prediction_scroll_popover(
 6011        &mut self,
 6012        to_y: impl Fn(Size<Pixels>) -> Pixels,
 6013        scroll_icon: IconName,
 6014        visible_row_range: Range<DisplayRow>,
 6015        line_layouts: &[LineWithInvisibles],
 6016        newest_selection_head: Option<DisplayPoint>,
 6017        scrolled_content_origin: gpui::Point<Pixels>,
 6018        window: &mut Window,
 6019        cx: &mut App,
 6020    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6021        let mut element = self
 6022            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6023            .into_any();
 6024
 6025        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6026
 6027        let cursor = newest_selection_head?;
 6028        let cursor_row_layout =
 6029            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6030        let cursor_column = cursor.column() as usize;
 6031
 6032        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6033
 6034        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6035
 6036        element.prepaint_at(origin, window, cx);
 6037        Some((element, origin))
 6038    }
 6039
 6040    #[allow(clippy::too_many_arguments)]
 6041    fn render_edit_prediction_eager_jump_popover(
 6042        &mut self,
 6043        text_bounds: &Bounds<Pixels>,
 6044        content_origin: gpui::Point<Pixels>,
 6045        editor_snapshot: &EditorSnapshot,
 6046        visible_row_range: Range<DisplayRow>,
 6047        scroll_top: f32,
 6048        scroll_bottom: f32,
 6049        line_height: Pixels,
 6050        scroll_pixel_position: gpui::Point<Pixels>,
 6051        target_display_point: DisplayPoint,
 6052        editor_width: Pixels,
 6053        window: &mut Window,
 6054        cx: &mut App,
 6055    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6056        if target_display_point.row().as_f32() < scroll_top {
 6057            let mut element = self
 6058                .render_edit_prediction_line_popover(
 6059                    "Jump to Edit",
 6060                    Some(IconName::ArrowUp),
 6061                    window,
 6062                    cx,
 6063                )?
 6064                .into_any();
 6065
 6066            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6067            let offset = point(
 6068                (text_bounds.size.width - size.width) / 2.,
 6069                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6070            );
 6071
 6072            let origin = text_bounds.origin + offset;
 6073            element.prepaint_at(origin, window, cx);
 6074            Some((element, origin))
 6075        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6076            let mut element = self
 6077                .render_edit_prediction_line_popover(
 6078                    "Jump to Edit",
 6079                    Some(IconName::ArrowDown),
 6080                    window,
 6081                    cx,
 6082                )?
 6083                .into_any();
 6084
 6085            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6086            let offset = point(
 6087                (text_bounds.size.width - size.width) / 2.,
 6088                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6089            );
 6090
 6091            let origin = text_bounds.origin + offset;
 6092            element.prepaint_at(origin, window, cx);
 6093            Some((element, origin))
 6094        } else {
 6095            self.render_edit_prediction_end_of_line_popover(
 6096                "Jump to Edit",
 6097                editor_snapshot,
 6098                visible_row_range,
 6099                target_display_point,
 6100                line_height,
 6101                scroll_pixel_position,
 6102                content_origin,
 6103                editor_width,
 6104                window,
 6105                cx,
 6106            )
 6107        }
 6108    }
 6109
 6110    #[allow(clippy::too_many_arguments)]
 6111    fn render_edit_prediction_end_of_line_popover(
 6112        self: &mut Editor,
 6113        label: &'static str,
 6114        editor_snapshot: &EditorSnapshot,
 6115        visible_row_range: Range<DisplayRow>,
 6116        target_display_point: DisplayPoint,
 6117        line_height: Pixels,
 6118        scroll_pixel_position: gpui::Point<Pixels>,
 6119        content_origin: gpui::Point<Pixels>,
 6120        editor_width: Pixels,
 6121        window: &mut Window,
 6122        cx: &mut App,
 6123    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6124        let target_line_end = DisplayPoint::new(
 6125            target_display_point.row(),
 6126            editor_snapshot.line_len(target_display_point.row()),
 6127        );
 6128
 6129        let mut element = self
 6130            .render_edit_prediction_line_popover(label, None, window, cx)?
 6131            .into_any();
 6132
 6133        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6134
 6135        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6136
 6137        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6138        let mut origin = start_point
 6139            + line_origin
 6140            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6141        origin.x = origin.x.max(content_origin.x);
 6142
 6143        let max_x = content_origin.x + editor_width - size.width;
 6144
 6145        if origin.x > max_x {
 6146            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6147
 6148            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6149                origin.y += offset;
 6150                IconName::ArrowUp
 6151            } else {
 6152                origin.y -= offset;
 6153                IconName::ArrowDown
 6154            };
 6155
 6156            element = self
 6157                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6158                .into_any();
 6159
 6160            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6161
 6162            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6163        }
 6164
 6165        element.prepaint_at(origin, window, cx);
 6166        Some((element, origin))
 6167    }
 6168
 6169    #[allow(clippy::too_many_arguments)]
 6170    fn render_edit_prediction_diff_popover(
 6171        self: &Editor,
 6172        text_bounds: &Bounds<Pixels>,
 6173        content_origin: gpui::Point<Pixels>,
 6174        editor_snapshot: &EditorSnapshot,
 6175        visible_row_range: Range<DisplayRow>,
 6176        line_layouts: &[LineWithInvisibles],
 6177        line_height: Pixels,
 6178        scroll_pixel_position: gpui::Point<Pixels>,
 6179        newest_selection_head: Option<DisplayPoint>,
 6180        editor_width: Pixels,
 6181        style: &EditorStyle,
 6182        edits: &Vec<(Range<Anchor>, String)>,
 6183        edit_preview: &Option<language::EditPreview>,
 6184        snapshot: &language::BufferSnapshot,
 6185        window: &mut Window,
 6186        cx: &mut App,
 6187    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6188        let edit_start = edits
 6189            .first()
 6190            .unwrap()
 6191            .0
 6192            .start
 6193            .to_display_point(editor_snapshot);
 6194        let edit_end = edits
 6195            .last()
 6196            .unwrap()
 6197            .0
 6198            .end
 6199            .to_display_point(editor_snapshot);
 6200
 6201        let is_visible = visible_row_range.contains(&edit_start.row())
 6202            || visible_row_range.contains(&edit_end.row());
 6203        if !is_visible {
 6204            return None;
 6205        }
 6206
 6207        let highlighted_edits =
 6208            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6209
 6210        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6211        let line_count = highlighted_edits.text.lines().count();
 6212
 6213        const BORDER_WIDTH: Pixels = px(1.);
 6214
 6215        let mut element = h_flex()
 6216            .items_start()
 6217            .child(
 6218                h_flex()
 6219                    .bg(cx.theme().colors().editor_background)
 6220                    .border(BORDER_WIDTH)
 6221                    .shadow_sm()
 6222                    .border_color(cx.theme().colors().border)
 6223                    .rounded_l_lg()
 6224                    .when(line_count > 1, |el| el.rounded_br_lg())
 6225                    .pr_1()
 6226                    .child(styled_text),
 6227            )
 6228            .child(
 6229                h_flex()
 6230                    .h(line_height + BORDER_WIDTH * px(2.))
 6231                    .px_1p5()
 6232                    .gap_1()
 6233                    // Workaround: For some reason, there's a gap if we don't do this
 6234                    .ml(-BORDER_WIDTH)
 6235                    .shadow(smallvec![gpui::BoxShadow {
 6236                        color: gpui::black().opacity(0.05),
 6237                        offset: point(px(1.), px(1.)),
 6238                        blur_radius: px(2.),
 6239                        spread_radius: px(0.),
 6240                    }])
 6241                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6242                    .border(BORDER_WIDTH)
 6243                    .border_color(cx.theme().colors().border)
 6244                    .rounded_r_lg()
 6245                    .children(self.render_edit_prediction_accept_keybind(window, cx)),
 6246            )
 6247            .into_any();
 6248
 6249        let longest_row =
 6250            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6251        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6252            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6253        } else {
 6254            layout_line(
 6255                longest_row,
 6256                editor_snapshot,
 6257                style,
 6258                editor_width,
 6259                |_| false,
 6260                window,
 6261                cx,
 6262            )
 6263            .width
 6264        };
 6265
 6266        let viewport_bounds =
 6267            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6268                right: -EditorElement::SCROLLBAR_WIDTH,
 6269                ..Default::default()
 6270            });
 6271
 6272        let x_after_longest =
 6273            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6274                - scroll_pixel_position.x;
 6275
 6276        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6277
 6278        // Fully visible if it can be displayed within the window (allow overlapping other
 6279        // panes). However, this is only allowed if the popover starts within text_bounds.
 6280        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6281            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6282
 6283        let mut origin = if can_position_to_the_right {
 6284            point(
 6285                x_after_longest,
 6286                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6287                    - scroll_pixel_position.y,
 6288            )
 6289        } else {
 6290            let cursor_row = newest_selection_head.map(|head| head.row());
 6291            let above_edit = edit_start
 6292                .row()
 6293                .0
 6294                .checked_sub(line_count as u32)
 6295                .map(DisplayRow);
 6296            let below_edit = Some(edit_end.row() + 1);
 6297            let above_cursor =
 6298                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6299            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6300
 6301            // Place the edit popover adjacent to the edit if there is a location
 6302            // available that is onscreen and does not obscure the cursor. Otherwise,
 6303            // place it adjacent to the cursor.
 6304            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6305                .into_iter()
 6306                .flatten()
 6307                .find(|&start_row| {
 6308                    let end_row = start_row + line_count as u32;
 6309                    visible_row_range.contains(&start_row)
 6310                        && visible_row_range.contains(&end_row)
 6311                        && cursor_row.map_or(true, |cursor_row| {
 6312                            !((start_row..end_row).contains(&cursor_row))
 6313                        })
 6314                })?;
 6315
 6316            content_origin
 6317                + point(
 6318                    -scroll_pixel_position.x,
 6319                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6320                )
 6321        };
 6322
 6323        origin.x -= BORDER_WIDTH;
 6324
 6325        window.defer_draw(element, origin, 1);
 6326
 6327        // Do not return an element, since it will already be drawn due to defer_draw.
 6328        None
 6329    }
 6330
 6331    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6332        px(30.)
 6333    }
 6334
 6335    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6336        if self.read_only(cx) {
 6337            cx.theme().players().read_only()
 6338        } else {
 6339            self.style.as_ref().unwrap().local_player
 6340        }
 6341    }
 6342
 6343    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 6344        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6345        let accept_keystroke = accept_binding.keystroke()?;
 6346
 6347        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6348
 6349        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6350            Color::Accent
 6351        } else {
 6352            Color::Muted
 6353        };
 6354
 6355        h_flex()
 6356            .px_0p5()
 6357            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6358            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6359            .text_size(TextSize::XSmall.rems(cx))
 6360            .child(h_flex().children(ui::render_modifiers(
 6361                &accept_keystroke.modifiers,
 6362                PlatformStyle::platform(),
 6363                Some(modifiers_color),
 6364                Some(IconSize::XSmall.rems().into()),
 6365                true,
 6366            )))
 6367            .when(is_platform_style_mac, |parent| {
 6368                parent.child(accept_keystroke.key.clone())
 6369            })
 6370            .when(!is_platform_style_mac, |parent| {
 6371                parent.child(
 6372                    Key::new(
 6373                        util::capitalize(&accept_keystroke.key),
 6374                        Some(Color::Default),
 6375                    )
 6376                    .size(Some(IconSize::XSmall.rems().into())),
 6377                )
 6378            })
 6379            .into()
 6380    }
 6381
 6382    fn render_edit_prediction_line_popover(
 6383        &self,
 6384        label: impl Into<SharedString>,
 6385        icon: Option<IconName>,
 6386        window: &mut Window,
 6387        cx: &App,
 6388    ) -> Option<Div> {
 6389        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6390
 6391        let result = h_flex()
 6392            .py_0p5()
 6393            .pl_1()
 6394            .pr(padding_right)
 6395            .gap_1()
 6396            .rounded(px(6.))
 6397            .border_1()
 6398            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6399            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6400            .shadow_sm()
 6401            .children(self.render_edit_prediction_accept_keybind(window, cx))
 6402            .child(Label::new(label).size(LabelSize::Small))
 6403            .when_some(icon, |element, icon| {
 6404                element.child(
 6405                    div()
 6406                        .mt(px(1.5))
 6407                        .child(Icon::new(icon).size(IconSize::Small)),
 6408                )
 6409            });
 6410
 6411        Some(result)
 6412    }
 6413
 6414    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6415        let accent_color = cx.theme().colors().text_accent;
 6416        let editor_bg_color = cx.theme().colors().editor_background;
 6417        editor_bg_color.blend(accent_color.opacity(0.1))
 6418    }
 6419
 6420    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6421        let accent_color = cx.theme().colors().text_accent;
 6422        let editor_bg_color = cx.theme().colors().editor_background;
 6423        editor_bg_color.blend(accent_color.opacity(0.6))
 6424    }
 6425
 6426    #[allow(clippy::too_many_arguments)]
 6427    fn render_edit_prediction_cursor_popover(
 6428        &self,
 6429        min_width: Pixels,
 6430        max_width: Pixels,
 6431        cursor_point: Point,
 6432        style: &EditorStyle,
 6433        accept_keystroke: Option<&gpui::Keystroke>,
 6434        _window: &Window,
 6435        cx: &mut Context<Editor>,
 6436    ) -> Option<AnyElement> {
 6437        let provider = self.edit_prediction_provider.as_ref()?;
 6438
 6439        if provider.provider.needs_terms_acceptance(cx) {
 6440            return Some(
 6441                h_flex()
 6442                    .min_w(min_width)
 6443                    .flex_1()
 6444                    .px_2()
 6445                    .py_1()
 6446                    .gap_3()
 6447                    .elevation_2(cx)
 6448                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6449                    .id("accept-terms")
 6450                    .cursor_pointer()
 6451                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6452                    .on_click(cx.listener(|this, _event, window, cx| {
 6453                        cx.stop_propagation();
 6454                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6455                        window.dispatch_action(
 6456                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6457                            cx,
 6458                        );
 6459                    }))
 6460                    .child(
 6461                        h_flex()
 6462                            .flex_1()
 6463                            .gap_2()
 6464                            .child(Icon::new(IconName::ZedPredict))
 6465                            .child(Label::new("Accept Terms of Service"))
 6466                            .child(div().w_full())
 6467                            .child(
 6468                                Icon::new(IconName::ArrowUpRight)
 6469                                    .color(Color::Muted)
 6470                                    .size(IconSize::Small),
 6471                            )
 6472                            .into_any_element(),
 6473                    )
 6474                    .into_any(),
 6475            );
 6476        }
 6477
 6478        let is_refreshing = provider.provider.is_refreshing(cx);
 6479
 6480        fn pending_completion_container() -> Div {
 6481            h_flex()
 6482                .h_full()
 6483                .flex_1()
 6484                .gap_2()
 6485                .child(Icon::new(IconName::ZedPredict))
 6486        }
 6487
 6488        let completion = match &self.active_inline_completion {
 6489            Some(completion) => match &completion.completion {
 6490                InlineCompletion::Move {
 6491                    target, snapshot, ..
 6492                } if !self.has_visible_completions_menu() => {
 6493                    use text::ToPoint as _;
 6494
 6495                    return Some(
 6496                        h_flex()
 6497                            .px_2()
 6498                            .py_1()
 6499                            .gap_2()
 6500                            .elevation_2(cx)
 6501                            .border_color(cx.theme().colors().border)
 6502                            .rounded(px(6.))
 6503                            .rounded_tl(px(0.))
 6504                            .child(
 6505                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6506                                    Icon::new(IconName::ZedPredictDown)
 6507                                } else {
 6508                                    Icon::new(IconName::ZedPredictUp)
 6509                                },
 6510                            )
 6511                            .child(Label::new("Hold").size(LabelSize::Small))
 6512                            .child(h_flex().children(ui::render_modifiers(
 6513                                &accept_keystroke?.modifiers,
 6514                                PlatformStyle::platform(),
 6515                                Some(Color::Default),
 6516                                Some(IconSize::Small.rems().into()),
 6517                                false,
 6518                            )))
 6519                            .into_any(),
 6520                    );
 6521                }
 6522                _ => self.render_edit_prediction_cursor_popover_preview(
 6523                    completion,
 6524                    cursor_point,
 6525                    style,
 6526                    cx,
 6527                )?,
 6528            },
 6529
 6530            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6531                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6532                    stale_completion,
 6533                    cursor_point,
 6534                    style,
 6535                    cx,
 6536                )?,
 6537
 6538                None => {
 6539                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6540                }
 6541            },
 6542
 6543            None => pending_completion_container().child(Label::new("No Prediction")),
 6544        };
 6545
 6546        let completion = if is_refreshing {
 6547            completion
 6548                .with_animation(
 6549                    "loading-completion",
 6550                    Animation::new(Duration::from_secs(2))
 6551                        .repeat()
 6552                        .with_easing(pulsating_between(0.4, 0.8)),
 6553                    |label, delta| label.opacity(delta),
 6554                )
 6555                .into_any_element()
 6556        } else {
 6557            completion.into_any_element()
 6558        };
 6559
 6560        let has_completion = self.active_inline_completion.is_some();
 6561
 6562        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6563        Some(
 6564            h_flex()
 6565                .min_w(min_width)
 6566                .max_w(max_width)
 6567                .flex_1()
 6568                .elevation_2(cx)
 6569                .border_color(cx.theme().colors().border)
 6570                .child(
 6571                    div()
 6572                        .flex_1()
 6573                        .py_1()
 6574                        .px_2()
 6575                        .overflow_hidden()
 6576                        .child(completion),
 6577                )
 6578                .when_some(accept_keystroke, |el, accept_keystroke| {
 6579                    if !accept_keystroke.modifiers.modified() {
 6580                        return el;
 6581                    }
 6582
 6583                    el.child(
 6584                        h_flex()
 6585                            .h_full()
 6586                            .border_l_1()
 6587                            .rounded_r_lg()
 6588                            .border_color(cx.theme().colors().border)
 6589                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6590                            .gap_1()
 6591                            .py_1()
 6592                            .px_2()
 6593                            .child(
 6594                                h_flex()
 6595                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6596                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6597                                    .child(h_flex().children(ui::render_modifiers(
 6598                                        &accept_keystroke.modifiers,
 6599                                        PlatformStyle::platform(),
 6600                                        Some(if !has_completion {
 6601                                            Color::Muted
 6602                                        } else {
 6603                                            Color::Default
 6604                                        }),
 6605                                        None,
 6606                                        false,
 6607                                    ))),
 6608                            )
 6609                            .child(Label::new("Preview").into_any_element())
 6610                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6611                    )
 6612                })
 6613                .into_any(),
 6614        )
 6615    }
 6616
 6617    fn render_edit_prediction_cursor_popover_preview(
 6618        &self,
 6619        completion: &InlineCompletionState,
 6620        cursor_point: Point,
 6621        style: &EditorStyle,
 6622        cx: &mut Context<Editor>,
 6623    ) -> Option<Div> {
 6624        use text::ToPoint as _;
 6625
 6626        fn render_relative_row_jump(
 6627            prefix: impl Into<String>,
 6628            current_row: u32,
 6629            target_row: u32,
 6630        ) -> Div {
 6631            let (row_diff, arrow) = if target_row < current_row {
 6632                (current_row - target_row, IconName::ArrowUp)
 6633            } else {
 6634                (target_row - current_row, IconName::ArrowDown)
 6635            };
 6636
 6637            h_flex()
 6638                .child(
 6639                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6640                        .color(Color::Muted)
 6641                        .size(LabelSize::Small),
 6642                )
 6643                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6644        }
 6645
 6646        match &completion.completion {
 6647            InlineCompletion::Move {
 6648                target, snapshot, ..
 6649            } => Some(
 6650                h_flex()
 6651                    .px_2()
 6652                    .gap_2()
 6653                    .flex_1()
 6654                    .child(
 6655                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6656                            Icon::new(IconName::ZedPredictDown)
 6657                        } else {
 6658                            Icon::new(IconName::ZedPredictUp)
 6659                        },
 6660                    )
 6661                    .child(Label::new("Jump to Edit")),
 6662            ),
 6663
 6664            InlineCompletion::Edit {
 6665                edits,
 6666                edit_preview,
 6667                snapshot,
 6668                display_mode: _,
 6669            } => {
 6670                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6671
 6672                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6673                    &snapshot,
 6674                    &edits,
 6675                    edit_preview.as_ref()?,
 6676                    true,
 6677                    cx,
 6678                )
 6679                .first_line_preview();
 6680
 6681                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6682                    .with_highlights(&style.text, highlighted_edits.highlights);
 6683
 6684                let preview = h_flex()
 6685                    .gap_1()
 6686                    .min_w_16()
 6687                    .child(styled_text)
 6688                    .when(has_more_lines, |parent| parent.child(""));
 6689
 6690                let left = if first_edit_row != cursor_point.row {
 6691                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6692                        .into_any_element()
 6693                } else {
 6694                    Icon::new(IconName::ZedPredict).into_any_element()
 6695                };
 6696
 6697                Some(
 6698                    h_flex()
 6699                        .h_full()
 6700                        .flex_1()
 6701                        .gap_2()
 6702                        .pr_1()
 6703                        .overflow_x_hidden()
 6704                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6705                        .child(left)
 6706                        .child(preview),
 6707                )
 6708            }
 6709        }
 6710    }
 6711
 6712    fn render_context_menu(
 6713        &self,
 6714        style: &EditorStyle,
 6715        max_height_in_lines: u32,
 6716        y_flipped: bool,
 6717        window: &mut Window,
 6718        cx: &mut Context<Editor>,
 6719    ) -> Option<AnyElement> {
 6720        let menu = self.context_menu.borrow();
 6721        let menu = menu.as_ref()?;
 6722        if !menu.visible() {
 6723            return None;
 6724        };
 6725        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6726    }
 6727
 6728    fn render_context_menu_aside(
 6729        &mut self,
 6730        max_size: Size<Pixels>,
 6731        window: &mut Window,
 6732        cx: &mut Context<Editor>,
 6733    ) -> Option<AnyElement> {
 6734        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6735            if menu.visible() {
 6736                menu.render_aside(self, max_size, window, cx)
 6737            } else {
 6738                None
 6739            }
 6740        })
 6741    }
 6742
 6743    fn hide_context_menu(
 6744        &mut self,
 6745        window: &mut Window,
 6746        cx: &mut Context<Self>,
 6747    ) -> Option<CodeContextMenu> {
 6748        cx.notify();
 6749        self.completion_tasks.clear();
 6750        let context_menu = self.context_menu.borrow_mut().take();
 6751        self.stale_inline_completion_in_menu.take();
 6752        self.update_visible_inline_completion(window, cx);
 6753        context_menu
 6754    }
 6755
 6756    fn show_snippet_choices(
 6757        &mut self,
 6758        choices: &Vec<String>,
 6759        selection: Range<Anchor>,
 6760        cx: &mut Context<Self>,
 6761    ) {
 6762        if selection.start.buffer_id.is_none() {
 6763            return;
 6764        }
 6765        let buffer_id = selection.start.buffer_id.unwrap();
 6766        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6767        let id = post_inc(&mut self.next_completion_id);
 6768
 6769        if let Some(buffer) = buffer {
 6770            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6771                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6772            ));
 6773        }
 6774    }
 6775
 6776    pub fn insert_snippet(
 6777        &mut self,
 6778        insertion_ranges: &[Range<usize>],
 6779        snippet: Snippet,
 6780        window: &mut Window,
 6781        cx: &mut Context<Self>,
 6782    ) -> Result<()> {
 6783        struct Tabstop<T> {
 6784            is_end_tabstop: bool,
 6785            ranges: Vec<Range<T>>,
 6786            choices: Option<Vec<String>>,
 6787        }
 6788
 6789        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6790            let snippet_text: Arc<str> = snippet.text.clone().into();
 6791            buffer.edit(
 6792                insertion_ranges
 6793                    .iter()
 6794                    .cloned()
 6795                    .map(|range| (range, snippet_text.clone())),
 6796                Some(AutoindentMode::EachLine),
 6797                cx,
 6798            );
 6799
 6800            let snapshot = &*buffer.read(cx);
 6801            let snippet = &snippet;
 6802            snippet
 6803                .tabstops
 6804                .iter()
 6805                .map(|tabstop| {
 6806                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6807                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6808                    });
 6809                    let mut tabstop_ranges = tabstop
 6810                        .ranges
 6811                        .iter()
 6812                        .flat_map(|tabstop_range| {
 6813                            let mut delta = 0_isize;
 6814                            insertion_ranges.iter().map(move |insertion_range| {
 6815                                let insertion_start = insertion_range.start as isize + delta;
 6816                                delta +=
 6817                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6818
 6819                                let start = ((insertion_start + tabstop_range.start) as usize)
 6820                                    .min(snapshot.len());
 6821                                let end = ((insertion_start + tabstop_range.end) as usize)
 6822                                    .min(snapshot.len());
 6823                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6824                            })
 6825                        })
 6826                        .collect::<Vec<_>>();
 6827                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6828
 6829                    Tabstop {
 6830                        is_end_tabstop,
 6831                        ranges: tabstop_ranges,
 6832                        choices: tabstop.choices.clone(),
 6833                    }
 6834                })
 6835                .collect::<Vec<_>>()
 6836        });
 6837        if let Some(tabstop) = tabstops.first() {
 6838            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6839                s.select_ranges(tabstop.ranges.iter().cloned());
 6840            });
 6841
 6842            if let Some(choices) = &tabstop.choices {
 6843                if let Some(selection) = tabstop.ranges.first() {
 6844                    self.show_snippet_choices(choices, selection.clone(), cx)
 6845                }
 6846            }
 6847
 6848            // If we're already at the last tabstop and it's at the end of the snippet,
 6849            // we're done, we don't need to keep the state around.
 6850            if !tabstop.is_end_tabstop {
 6851                let choices = tabstops
 6852                    .iter()
 6853                    .map(|tabstop| tabstop.choices.clone())
 6854                    .collect();
 6855
 6856                let ranges = tabstops
 6857                    .into_iter()
 6858                    .map(|tabstop| tabstop.ranges)
 6859                    .collect::<Vec<_>>();
 6860
 6861                self.snippet_stack.push(SnippetState {
 6862                    active_index: 0,
 6863                    ranges,
 6864                    choices,
 6865                });
 6866            }
 6867
 6868            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6869            if self.autoclose_regions.is_empty() {
 6870                let snapshot = self.buffer.read(cx).snapshot(cx);
 6871                for selection in &mut self.selections.all::<Point>(cx) {
 6872                    let selection_head = selection.head();
 6873                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6874                        continue;
 6875                    };
 6876
 6877                    let mut bracket_pair = None;
 6878                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6879                    let prev_chars = snapshot
 6880                        .reversed_chars_at(selection_head)
 6881                        .collect::<String>();
 6882                    for (pair, enabled) in scope.brackets() {
 6883                        if enabled
 6884                            && pair.close
 6885                            && prev_chars.starts_with(pair.start.as_str())
 6886                            && next_chars.starts_with(pair.end.as_str())
 6887                        {
 6888                            bracket_pair = Some(pair.clone());
 6889                            break;
 6890                        }
 6891                    }
 6892                    if let Some(pair) = bracket_pair {
 6893                        let start = snapshot.anchor_after(selection_head);
 6894                        let end = snapshot.anchor_after(selection_head);
 6895                        self.autoclose_regions.push(AutocloseRegion {
 6896                            selection_id: selection.id,
 6897                            range: start..end,
 6898                            pair,
 6899                        });
 6900                    }
 6901                }
 6902            }
 6903        }
 6904        Ok(())
 6905    }
 6906
 6907    pub fn move_to_next_snippet_tabstop(
 6908        &mut self,
 6909        window: &mut Window,
 6910        cx: &mut Context<Self>,
 6911    ) -> bool {
 6912        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6913    }
 6914
 6915    pub fn move_to_prev_snippet_tabstop(
 6916        &mut self,
 6917        window: &mut Window,
 6918        cx: &mut Context<Self>,
 6919    ) -> bool {
 6920        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6921    }
 6922
 6923    pub fn move_to_snippet_tabstop(
 6924        &mut self,
 6925        bias: Bias,
 6926        window: &mut Window,
 6927        cx: &mut Context<Self>,
 6928    ) -> bool {
 6929        if let Some(mut snippet) = self.snippet_stack.pop() {
 6930            match bias {
 6931                Bias::Left => {
 6932                    if snippet.active_index > 0 {
 6933                        snippet.active_index -= 1;
 6934                    } else {
 6935                        self.snippet_stack.push(snippet);
 6936                        return false;
 6937                    }
 6938                }
 6939                Bias::Right => {
 6940                    if snippet.active_index + 1 < snippet.ranges.len() {
 6941                        snippet.active_index += 1;
 6942                    } else {
 6943                        self.snippet_stack.push(snippet);
 6944                        return false;
 6945                    }
 6946                }
 6947            }
 6948            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6949                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6950                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6951                });
 6952
 6953                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6954                    if let Some(selection) = current_ranges.first() {
 6955                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6956                    }
 6957                }
 6958
 6959                // If snippet state is not at the last tabstop, push it back on the stack
 6960                if snippet.active_index + 1 < snippet.ranges.len() {
 6961                    self.snippet_stack.push(snippet);
 6962                }
 6963                return true;
 6964            }
 6965        }
 6966
 6967        false
 6968    }
 6969
 6970    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6971        self.transact(window, cx, |this, window, cx| {
 6972            this.select_all(&SelectAll, window, cx);
 6973            this.insert("", window, cx);
 6974        });
 6975    }
 6976
 6977    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6978        self.transact(window, cx, |this, window, cx| {
 6979            this.select_autoclose_pair(window, cx);
 6980            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6981            if !this.linked_edit_ranges.is_empty() {
 6982                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6983                let snapshot = this.buffer.read(cx).snapshot(cx);
 6984
 6985                for selection in selections.iter() {
 6986                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6987                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6988                    if selection_start.buffer_id != selection_end.buffer_id {
 6989                        continue;
 6990                    }
 6991                    if let Some(ranges) =
 6992                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6993                    {
 6994                        for (buffer, entries) in ranges {
 6995                            linked_ranges.entry(buffer).or_default().extend(entries);
 6996                        }
 6997                    }
 6998                }
 6999            }
 7000
 7001            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7002            if !this.selections.line_mode {
 7003                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 7004                for selection in &mut selections {
 7005                    if selection.is_empty() {
 7006                        let old_head = selection.head();
 7007                        let mut new_head =
 7008                            movement::left(&display_map, old_head.to_display_point(&display_map))
 7009                                .to_point(&display_map);
 7010                        if let Some((buffer, line_buffer_range)) = display_map
 7011                            .buffer_snapshot
 7012                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 7013                        {
 7014                            let indent_size =
 7015                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7016                            let indent_len = match indent_size.kind {
 7017                                IndentKind::Space => {
 7018                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7019                                }
 7020                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7021                            };
 7022                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7023                                let indent_len = indent_len.get();
 7024                                new_head = cmp::min(
 7025                                    new_head,
 7026                                    MultiBufferPoint::new(
 7027                                        old_head.row,
 7028                                        ((old_head.column - 1) / indent_len) * indent_len,
 7029                                    ),
 7030                                );
 7031                            }
 7032                        }
 7033
 7034                        selection.set_head(new_head, SelectionGoal::None);
 7035                    }
 7036                }
 7037            }
 7038
 7039            this.signature_help_state.set_backspace_pressed(true);
 7040            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7041                s.select(selections)
 7042            });
 7043            this.insert("", window, cx);
 7044            let empty_str: Arc<str> = Arc::from("");
 7045            for (buffer, edits) in linked_ranges {
 7046                let snapshot = buffer.read(cx).snapshot();
 7047                use text::ToPoint as TP;
 7048
 7049                let edits = edits
 7050                    .into_iter()
 7051                    .map(|range| {
 7052                        let end_point = TP::to_point(&range.end, &snapshot);
 7053                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7054
 7055                        if end_point == start_point {
 7056                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7057                                .saturating_sub(1);
 7058                            start_point =
 7059                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7060                        };
 7061
 7062                        (start_point..end_point, empty_str.clone())
 7063                    })
 7064                    .sorted_by_key(|(range, _)| range.start)
 7065                    .collect::<Vec<_>>();
 7066                buffer.update(cx, |this, cx| {
 7067                    this.edit(edits, None, cx);
 7068                })
 7069            }
 7070            this.refresh_inline_completion(true, false, window, cx);
 7071            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7072        });
 7073    }
 7074
 7075    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7076        self.transact(window, cx, |this, window, cx| {
 7077            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7078                let line_mode = s.line_mode;
 7079                s.move_with(|map, selection| {
 7080                    if selection.is_empty() && !line_mode {
 7081                        let cursor = movement::right(map, selection.head());
 7082                        selection.end = cursor;
 7083                        selection.reversed = true;
 7084                        selection.goal = SelectionGoal::None;
 7085                    }
 7086                })
 7087            });
 7088            this.insert("", window, cx);
 7089            this.refresh_inline_completion(true, false, window, cx);
 7090        });
 7091    }
 7092
 7093    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 7094        if self.move_to_prev_snippet_tabstop(window, cx) {
 7095            return;
 7096        }
 7097
 7098        self.outdent(&Outdent, window, cx);
 7099    }
 7100
 7101    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7102        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7103            return;
 7104        }
 7105
 7106        let mut selections = self.selections.all_adjusted(cx);
 7107        let buffer = self.buffer.read(cx);
 7108        let snapshot = buffer.snapshot(cx);
 7109        let rows_iter = selections.iter().map(|s| s.head().row);
 7110        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7111
 7112        let mut edits = Vec::new();
 7113        let mut prev_edited_row = 0;
 7114        let mut row_delta = 0;
 7115        for selection in &mut selections {
 7116            if selection.start.row != prev_edited_row {
 7117                row_delta = 0;
 7118            }
 7119            prev_edited_row = selection.end.row;
 7120
 7121            // If the selection is non-empty, then increase the indentation of the selected lines.
 7122            if !selection.is_empty() {
 7123                row_delta =
 7124                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7125                continue;
 7126            }
 7127
 7128            // If the selection is empty and the cursor is in the leading whitespace before the
 7129            // suggested indentation, then auto-indent the line.
 7130            let cursor = selection.head();
 7131            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7132            if let Some(suggested_indent) =
 7133                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7134            {
 7135                if cursor.column < suggested_indent.len
 7136                    && cursor.column <= current_indent.len
 7137                    && current_indent.len <= suggested_indent.len
 7138                {
 7139                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7140                    selection.end = selection.start;
 7141                    if row_delta == 0 {
 7142                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7143                            cursor.row,
 7144                            current_indent,
 7145                            suggested_indent,
 7146                        ));
 7147                        row_delta = suggested_indent.len - current_indent.len;
 7148                    }
 7149                    continue;
 7150                }
 7151            }
 7152
 7153            // Otherwise, insert a hard or soft tab.
 7154            let settings = buffer.settings_at(cursor, cx);
 7155            let tab_size = if settings.hard_tabs {
 7156                IndentSize::tab()
 7157            } else {
 7158                let tab_size = settings.tab_size.get();
 7159                let char_column = snapshot
 7160                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7161                    .flat_map(str::chars)
 7162                    .count()
 7163                    + row_delta as usize;
 7164                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7165                IndentSize::spaces(chars_to_next_tab_stop)
 7166            };
 7167            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7168            selection.end = selection.start;
 7169            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7170            row_delta += tab_size.len;
 7171        }
 7172
 7173        self.transact(window, cx, |this, window, cx| {
 7174            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7175            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7176                s.select(selections)
 7177            });
 7178            this.refresh_inline_completion(true, false, window, cx);
 7179        });
 7180    }
 7181
 7182    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7183        if self.read_only(cx) {
 7184            return;
 7185        }
 7186        let mut selections = self.selections.all::<Point>(cx);
 7187        let mut prev_edited_row = 0;
 7188        let mut row_delta = 0;
 7189        let mut edits = Vec::new();
 7190        let buffer = self.buffer.read(cx);
 7191        let snapshot = buffer.snapshot(cx);
 7192        for selection in &mut selections {
 7193            if selection.start.row != prev_edited_row {
 7194                row_delta = 0;
 7195            }
 7196            prev_edited_row = selection.end.row;
 7197
 7198            row_delta =
 7199                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7200        }
 7201
 7202        self.transact(window, cx, |this, window, cx| {
 7203            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7204            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7205                s.select(selections)
 7206            });
 7207        });
 7208    }
 7209
 7210    fn indent_selection(
 7211        buffer: &MultiBuffer,
 7212        snapshot: &MultiBufferSnapshot,
 7213        selection: &mut Selection<Point>,
 7214        edits: &mut Vec<(Range<Point>, String)>,
 7215        delta_for_start_row: u32,
 7216        cx: &App,
 7217    ) -> u32 {
 7218        let settings = buffer.settings_at(selection.start, cx);
 7219        let tab_size = settings.tab_size.get();
 7220        let indent_kind = if settings.hard_tabs {
 7221            IndentKind::Tab
 7222        } else {
 7223            IndentKind::Space
 7224        };
 7225        let mut start_row = selection.start.row;
 7226        let mut end_row = selection.end.row + 1;
 7227
 7228        // If a selection ends at the beginning of a line, don't indent
 7229        // that last line.
 7230        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7231            end_row -= 1;
 7232        }
 7233
 7234        // Avoid re-indenting a row that has already been indented by a
 7235        // previous selection, but still update this selection's column
 7236        // to reflect that indentation.
 7237        if delta_for_start_row > 0 {
 7238            start_row += 1;
 7239            selection.start.column += delta_for_start_row;
 7240            if selection.end.row == selection.start.row {
 7241                selection.end.column += delta_for_start_row;
 7242            }
 7243        }
 7244
 7245        let mut delta_for_end_row = 0;
 7246        let has_multiple_rows = start_row + 1 != end_row;
 7247        for row in start_row..end_row {
 7248            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7249            let indent_delta = match (current_indent.kind, indent_kind) {
 7250                (IndentKind::Space, IndentKind::Space) => {
 7251                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7252                    IndentSize::spaces(columns_to_next_tab_stop)
 7253                }
 7254                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7255                (_, IndentKind::Tab) => IndentSize::tab(),
 7256            };
 7257
 7258            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7259                0
 7260            } else {
 7261                selection.start.column
 7262            };
 7263            let row_start = Point::new(row, start);
 7264            edits.push((
 7265                row_start..row_start,
 7266                indent_delta.chars().collect::<String>(),
 7267            ));
 7268
 7269            // Update this selection's endpoints to reflect the indentation.
 7270            if row == selection.start.row {
 7271                selection.start.column += indent_delta.len;
 7272            }
 7273            if row == selection.end.row {
 7274                selection.end.column += indent_delta.len;
 7275                delta_for_end_row = indent_delta.len;
 7276            }
 7277        }
 7278
 7279        if selection.start.row == selection.end.row {
 7280            delta_for_start_row + delta_for_end_row
 7281        } else {
 7282            delta_for_end_row
 7283        }
 7284    }
 7285
 7286    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7287        if self.read_only(cx) {
 7288            return;
 7289        }
 7290        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7291        let selections = self.selections.all::<Point>(cx);
 7292        let mut deletion_ranges = Vec::new();
 7293        let mut last_outdent = None;
 7294        {
 7295            let buffer = self.buffer.read(cx);
 7296            let snapshot = buffer.snapshot(cx);
 7297            for selection in &selections {
 7298                let settings = buffer.settings_at(selection.start, cx);
 7299                let tab_size = settings.tab_size.get();
 7300                let mut rows = selection.spanned_rows(false, &display_map);
 7301
 7302                // Avoid re-outdenting a row that has already been outdented by a
 7303                // previous selection.
 7304                if let Some(last_row) = last_outdent {
 7305                    if last_row == rows.start {
 7306                        rows.start = rows.start.next_row();
 7307                    }
 7308                }
 7309                let has_multiple_rows = rows.len() > 1;
 7310                for row in rows.iter_rows() {
 7311                    let indent_size = snapshot.indent_size_for_line(row);
 7312                    if indent_size.len > 0 {
 7313                        let deletion_len = match indent_size.kind {
 7314                            IndentKind::Space => {
 7315                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7316                                if columns_to_prev_tab_stop == 0 {
 7317                                    tab_size
 7318                                } else {
 7319                                    columns_to_prev_tab_stop
 7320                                }
 7321                            }
 7322                            IndentKind::Tab => 1,
 7323                        };
 7324                        let start = if has_multiple_rows
 7325                            || deletion_len > selection.start.column
 7326                            || indent_size.len < selection.start.column
 7327                        {
 7328                            0
 7329                        } else {
 7330                            selection.start.column - deletion_len
 7331                        };
 7332                        deletion_ranges.push(
 7333                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7334                        );
 7335                        last_outdent = Some(row);
 7336                    }
 7337                }
 7338            }
 7339        }
 7340
 7341        self.transact(window, cx, |this, window, cx| {
 7342            this.buffer.update(cx, |buffer, cx| {
 7343                let empty_str: Arc<str> = Arc::default();
 7344                buffer.edit(
 7345                    deletion_ranges
 7346                        .into_iter()
 7347                        .map(|range| (range, empty_str.clone())),
 7348                    None,
 7349                    cx,
 7350                );
 7351            });
 7352            let selections = this.selections.all::<usize>(cx);
 7353            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7354                s.select(selections)
 7355            });
 7356        });
 7357    }
 7358
 7359    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7360        if self.read_only(cx) {
 7361            return;
 7362        }
 7363        let selections = self
 7364            .selections
 7365            .all::<usize>(cx)
 7366            .into_iter()
 7367            .map(|s| s.range());
 7368
 7369        self.transact(window, cx, |this, window, cx| {
 7370            this.buffer.update(cx, |buffer, cx| {
 7371                buffer.autoindent_ranges(selections, cx);
 7372            });
 7373            let selections = this.selections.all::<usize>(cx);
 7374            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7375                s.select(selections)
 7376            });
 7377        });
 7378    }
 7379
 7380    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7381        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7382        let selections = self.selections.all::<Point>(cx);
 7383
 7384        let mut new_cursors = Vec::new();
 7385        let mut edit_ranges = Vec::new();
 7386        let mut selections = selections.iter().peekable();
 7387        while let Some(selection) = selections.next() {
 7388            let mut rows = selection.spanned_rows(false, &display_map);
 7389            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7390
 7391            // Accumulate contiguous regions of rows that we want to delete.
 7392            while let Some(next_selection) = selections.peek() {
 7393                let next_rows = next_selection.spanned_rows(false, &display_map);
 7394                if next_rows.start <= rows.end {
 7395                    rows.end = next_rows.end;
 7396                    selections.next().unwrap();
 7397                } else {
 7398                    break;
 7399                }
 7400            }
 7401
 7402            let buffer = &display_map.buffer_snapshot;
 7403            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7404            let edit_end;
 7405            let cursor_buffer_row;
 7406            if buffer.max_point().row >= rows.end.0 {
 7407                // If there's a line after the range, delete the \n from the end of the row range
 7408                // and position the cursor on the next line.
 7409                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7410                cursor_buffer_row = rows.end;
 7411            } else {
 7412                // If there isn't a line after the range, delete the \n from the line before the
 7413                // start of the row range and position the cursor there.
 7414                edit_start = edit_start.saturating_sub(1);
 7415                edit_end = buffer.len();
 7416                cursor_buffer_row = rows.start.previous_row();
 7417            }
 7418
 7419            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7420            *cursor.column_mut() =
 7421                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7422
 7423            new_cursors.push((
 7424                selection.id,
 7425                buffer.anchor_after(cursor.to_point(&display_map)),
 7426            ));
 7427            edit_ranges.push(edit_start..edit_end);
 7428        }
 7429
 7430        self.transact(window, cx, |this, window, cx| {
 7431            let buffer = this.buffer.update(cx, |buffer, cx| {
 7432                let empty_str: Arc<str> = Arc::default();
 7433                buffer.edit(
 7434                    edit_ranges
 7435                        .into_iter()
 7436                        .map(|range| (range, empty_str.clone())),
 7437                    None,
 7438                    cx,
 7439                );
 7440                buffer.snapshot(cx)
 7441            });
 7442            let new_selections = new_cursors
 7443                .into_iter()
 7444                .map(|(id, cursor)| {
 7445                    let cursor = cursor.to_point(&buffer);
 7446                    Selection {
 7447                        id,
 7448                        start: cursor,
 7449                        end: cursor,
 7450                        reversed: false,
 7451                        goal: SelectionGoal::None,
 7452                    }
 7453                })
 7454                .collect();
 7455
 7456            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7457                s.select(new_selections);
 7458            });
 7459        });
 7460    }
 7461
 7462    pub fn join_lines_impl(
 7463        &mut self,
 7464        insert_whitespace: bool,
 7465        window: &mut Window,
 7466        cx: &mut Context<Self>,
 7467    ) {
 7468        if self.read_only(cx) {
 7469            return;
 7470        }
 7471        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7472        for selection in self.selections.all::<Point>(cx) {
 7473            let start = MultiBufferRow(selection.start.row);
 7474            // Treat single line selections as if they include the next line. Otherwise this action
 7475            // would do nothing for single line selections individual cursors.
 7476            let end = if selection.start.row == selection.end.row {
 7477                MultiBufferRow(selection.start.row + 1)
 7478            } else {
 7479                MultiBufferRow(selection.end.row)
 7480            };
 7481
 7482            if let Some(last_row_range) = row_ranges.last_mut() {
 7483                if start <= last_row_range.end {
 7484                    last_row_range.end = end;
 7485                    continue;
 7486                }
 7487            }
 7488            row_ranges.push(start..end);
 7489        }
 7490
 7491        let snapshot = self.buffer.read(cx).snapshot(cx);
 7492        let mut cursor_positions = Vec::new();
 7493        for row_range in &row_ranges {
 7494            let anchor = snapshot.anchor_before(Point::new(
 7495                row_range.end.previous_row().0,
 7496                snapshot.line_len(row_range.end.previous_row()),
 7497            ));
 7498            cursor_positions.push(anchor..anchor);
 7499        }
 7500
 7501        self.transact(window, cx, |this, window, cx| {
 7502            for row_range in row_ranges.into_iter().rev() {
 7503                for row in row_range.iter_rows().rev() {
 7504                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7505                    let next_line_row = row.next_row();
 7506                    let indent = snapshot.indent_size_for_line(next_line_row);
 7507                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7508
 7509                    let replace =
 7510                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7511                            " "
 7512                        } else {
 7513                            ""
 7514                        };
 7515
 7516                    this.buffer.update(cx, |buffer, cx| {
 7517                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7518                    });
 7519                }
 7520            }
 7521
 7522            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7523                s.select_anchor_ranges(cursor_positions)
 7524            });
 7525        });
 7526    }
 7527
 7528    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7529        self.join_lines_impl(true, window, cx);
 7530    }
 7531
 7532    pub fn sort_lines_case_sensitive(
 7533        &mut self,
 7534        _: &SortLinesCaseSensitive,
 7535        window: &mut Window,
 7536        cx: &mut Context<Self>,
 7537    ) {
 7538        self.manipulate_lines(window, cx, |lines| lines.sort())
 7539    }
 7540
 7541    pub fn sort_lines_case_insensitive(
 7542        &mut self,
 7543        _: &SortLinesCaseInsensitive,
 7544        window: &mut Window,
 7545        cx: &mut Context<Self>,
 7546    ) {
 7547        self.manipulate_lines(window, cx, |lines| {
 7548            lines.sort_by_key(|line| line.to_lowercase())
 7549        })
 7550    }
 7551
 7552    pub fn unique_lines_case_insensitive(
 7553        &mut self,
 7554        _: &UniqueLinesCaseInsensitive,
 7555        window: &mut Window,
 7556        cx: &mut Context<Self>,
 7557    ) {
 7558        self.manipulate_lines(window, cx, |lines| {
 7559            let mut seen = HashSet::default();
 7560            lines.retain(|line| seen.insert(line.to_lowercase()));
 7561        })
 7562    }
 7563
 7564    pub fn unique_lines_case_sensitive(
 7565        &mut self,
 7566        _: &UniqueLinesCaseSensitive,
 7567        window: &mut Window,
 7568        cx: &mut Context<Self>,
 7569    ) {
 7570        self.manipulate_lines(window, cx, |lines| {
 7571            let mut seen = HashSet::default();
 7572            lines.retain(|line| seen.insert(*line));
 7573        })
 7574    }
 7575
 7576    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7577        let Some(project) = self.project.clone() else {
 7578            return;
 7579        };
 7580        self.reload(project, window, cx)
 7581            .detach_and_notify_err(window, cx);
 7582    }
 7583
 7584    pub fn restore_file(
 7585        &mut self,
 7586        _: &::git::RestoreFile,
 7587        window: &mut Window,
 7588        cx: &mut Context<Self>,
 7589    ) {
 7590        let mut buffer_ids = HashSet::default();
 7591        let snapshot = self.buffer().read(cx).snapshot(cx);
 7592        for selection in self.selections.all::<usize>(cx) {
 7593            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7594        }
 7595
 7596        let buffer = self.buffer().read(cx);
 7597        let ranges = buffer_ids
 7598            .into_iter()
 7599            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7600            .collect::<Vec<_>>();
 7601
 7602        self.restore_hunks_in_ranges(ranges, window, cx);
 7603    }
 7604
 7605    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7606        let selections = self
 7607            .selections
 7608            .all(cx)
 7609            .into_iter()
 7610            .map(|s| s.range())
 7611            .collect();
 7612        self.restore_hunks_in_ranges(selections, window, cx);
 7613    }
 7614
 7615    fn restore_hunks_in_ranges(
 7616        &mut self,
 7617        ranges: Vec<Range<Point>>,
 7618        window: &mut Window,
 7619        cx: &mut Context<Editor>,
 7620    ) {
 7621        let mut revert_changes = HashMap::default();
 7622        let snapshot = self.buffer.read(cx).snapshot(cx);
 7623        let Some(project) = &self.project else {
 7624            return;
 7625        };
 7626
 7627        let chunk_by = self
 7628            .snapshot(window, cx)
 7629            .hunks_for_ranges(ranges.into_iter())
 7630            .into_iter()
 7631            .chunk_by(|hunk| hunk.buffer_id);
 7632        for (buffer_id, hunks) in &chunk_by {
 7633            let hunks = hunks.collect::<Vec<_>>();
 7634            for hunk in &hunks {
 7635                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7636            }
 7637            Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
 7638        }
 7639        drop(chunk_by);
 7640        if !revert_changes.is_empty() {
 7641            self.transact(window, cx, |editor, window, cx| {
 7642                editor.revert(revert_changes, window, cx);
 7643            });
 7644        }
 7645    }
 7646
 7647    pub fn open_active_item_in_terminal(
 7648        &mut self,
 7649        _: &OpenInTerminal,
 7650        window: &mut Window,
 7651        cx: &mut Context<Self>,
 7652    ) {
 7653        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7654            let project_path = buffer.read(cx).project_path(cx)?;
 7655            let project = self.project.as_ref()?.read(cx);
 7656            let entry = project.entry_for_path(&project_path, cx)?;
 7657            let parent = match &entry.canonical_path {
 7658                Some(canonical_path) => canonical_path.to_path_buf(),
 7659                None => project.absolute_path(&project_path, cx)?,
 7660            }
 7661            .parent()?
 7662            .to_path_buf();
 7663            Some(parent)
 7664        }) {
 7665            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7666        }
 7667    }
 7668
 7669    pub fn prepare_restore_change(
 7670        &self,
 7671        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7672        hunk: &MultiBufferDiffHunk,
 7673        cx: &mut App,
 7674    ) -> Option<()> {
 7675        let buffer = self.buffer.read(cx);
 7676        let diff = buffer.diff_for(hunk.buffer_id)?;
 7677        let buffer = buffer.buffer(hunk.buffer_id)?;
 7678        let buffer = buffer.read(cx);
 7679        let original_text = diff
 7680            .read(cx)
 7681            .base_text()
 7682            .as_ref()?
 7683            .as_rope()
 7684            .slice(hunk.diff_base_byte_range.clone());
 7685        let buffer_snapshot = buffer.snapshot();
 7686        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7687        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7688            probe
 7689                .0
 7690                .start
 7691                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7692                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7693        }) {
 7694            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7695            Some(())
 7696        } else {
 7697            None
 7698        }
 7699    }
 7700
 7701    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7702        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7703    }
 7704
 7705    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7706        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7707    }
 7708
 7709    fn manipulate_lines<Fn>(
 7710        &mut self,
 7711        window: &mut Window,
 7712        cx: &mut Context<Self>,
 7713        mut callback: Fn,
 7714    ) where
 7715        Fn: FnMut(&mut Vec<&str>),
 7716    {
 7717        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7718        let buffer = self.buffer.read(cx).snapshot(cx);
 7719
 7720        let mut edits = Vec::new();
 7721
 7722        let selections = self.selections.all::<Point>(cx);
 7723        let mut selections = selections.iter().peekable();
 7724        let mut contiguous_row_selections = Vec::new();
 7725        let mut new_selections = Vec::new();
 7726        let mut added_lines = 0;
 7727        let mut removed_lines = 0;
 7728
 7729        while let Some(selection) = selections.next() {
 7730            let (start_row, end_row) = consume_contiguous_rows(
 7731                &mut contiguous_row_selections,
 7732                selection,
 7733                &display_map,
 7734                &mut selections,
 7735            );
 7736
 7737            let start_point = Point::new(start_row.0, 0);
 7738            let end_point = Point::new(
 7739                end_row.previous_row().0,
 7740                buffer.line_len(end_row.previous_row()),
 7741            );
 7742            let text = buffer
 7743                .text_for_range(start_point..end_point)
 7744                .collect::<String>();
 7745
 7746            let mut lines = text.split('\n').collect_vec();
 7747
 7748            let lines_before = lines.len();
 7749            callback(&mut lines);
 7750            let lines_after = lines.len();
 7751
 7752            edits.push((start_point..end_point, lines.join("\n")));
 7753
 7754            // Selections must change based on added and removed line count
 7755            let start_row =
 7756                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7757            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7758            new_selections.push(Selection {
 7759                id: selection.id,
 7760                start: start_row,
 7761                end: end_row,
 7762                goal: SelectionGoal::None,
 7763                reversed: selection.reversed,
 7764            });
 7765
 7766            if lines_after > lines_before {
 7767                added_lines += lines_after - lines_before;
 7768            } else if lines_before > lines_after {
 7769                removed_lines += lines_before - lines_after;
 7770            }
 7771        }
 7772
 7773        self.transact(window, cx, |this, window, cx| {
 7774            let buffer = this.buffer.update(cx, |buffer, cx| {
 7775                buffer.edit(edits, None, cx);
 7776                buffer.snapshot(cx)
 7777            });
 7778
 7779            // Recalculate offsets on newly edited buffer
 7780            let new_selections = new_selections
 7781                .iter()
 7782                .map(|s| {
 7783                    let start_point = Point::new(s.start.0, 0);
 7784                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7785                    Selection {
 7786                        id: s.id,
 7787                        start: buffer.point_to_offset(start_point),
 7788                        end: buffer.point_to_offset(end_point),
 7789                        goal: s.goal,
 7790                        reversed: s.reversed,
 7791                    }
 7792                })
 7793                .collect();
 7794
 7795            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7796                s.select(new_selections);
 7797            });
 7798
 7799            this.request_autoscroll(Autoscroll::fit(), cx);
 7800        });
 7801    }
 7802
 7803    pub fn convert_to_upper_case(
 7804        &mut self,
 7805        _: &ConvertToUpperCase,
 7806        window: &mut Window,
 7807        cx: &mut Context<Self>,
 7808    ) {
 7809        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7810    }
 7811
 7812    pub fn convert_to_lower_case(
 7813        &mut self,
 7814        _: &ConvertToLowerCase,
 7815        window: &mut Window,
 7816        cx: &mut Context<Self>,
 7817    ) {
 7818        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7819    }
 7820
 7821    pub fn convert_to_title_case(
 7822        &mut self,
 7823        _: &ConvertToTitleCase,
 7824        window: &mut Window,
 7825        cx: &mut Context<Self>,
 7826    ) {
 7827        self.manipulate_text(window, cx, |text| {
 7828            text.split('\n')
 7829                .map(|line| line.to_case(Case::Title))
 7830                .join("\n")
 7831        })
 7832    }
 7833
 7834    pub fn convert_to_snake_case(
 7835        &mut self,
 7836        _: &ConvertToSnakeCase,
 7837        window: &mut Window,
 7838        cx: &mut Context<Self>,
 7839    ) {
 7840        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7841    }
 7842
 7843    pub fn convert_to_kebab_case(
 7844        &mut self,
 7845        _: &ConvertToKebabCase,
 7846        window: &mut Window,
 7847        cx: &mut Context<Self>,
 7848    ) {
 7849        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7850    }
 7851
 7852    pub fn convert_to_upper_camel_case(
 7853        &mut self,
 7854        _: &ConvertToUpperCamelCase,
 7855        window: &mut Window,
 7856        cx: &mut Context<Self>,
 7857    ) {
 7858        self.manipulate_text(window, cx, |text| {
 7859            text.split('\n')
 7860                .map(|line| line.to_case(Case::UpperCamel))
 7861                .join("\n")
 7862        })
 7863    }
 7864
 7865    pub fn convert_to_lower_camel_case(
 7866        &mut self,
 7867        _: &ConvertToLowerCamelCase,
 7868        window: &mut Window,
 7869        cx: &mut Context<Self>,
 7870    ) {
 7871        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7872    }
 7873
 7874    pub fn convert_to_opposite_case(
 7875        &mut self,
 7876        _: &ConvertToOppositeCase,
 7877        window: &mut Window,
 7878        cx: &mut Context<Self>,
 7879    ) {
 7880        self.manipulate_text(window, cx, |text| {
 7881            text.chars()
 7882                .fold(String::with_capacity(text.len()), |mut t, c| {
 7883                    if c.is_uppercase() {
 7884                        t.extend(c.to_lowercase());
 7885                    } else {
 7886                        t.extend(c.to_uppercase());
 7887                    }
 7888                    t
 7889                })
 7890        })
 7891    }
 7892
 7893    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7894    where
 7895        Fn: FnMut(&str) -> String,
 7896    {
 7897        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7898        let buffer = self.buffer.read(cx).snapshot(cx);
 7899
 7900        let mut new_selections = Vec::new();
 7901        let mut edits = Vec::new();
 7902        let mut selection_adjustment = 0i32;
 7903
 7904        for selection in self.selections.all::<usize>(cx) {
 7905            let selection_is_empty = selection.is_empty();
 7906
 7907            let (start, end) = if selection_is_empty {
 7908                let word_range = movement::surrounding_word(
 7909                    &display_map,
 7910                    selection.start.to_display_point(&display_map),
 7911                );
 7912                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7913                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7914                (start, end)
 7915            } else {
 7916                (selection.start, selection.end)
 7917            };
 7918
 7919            let text = buffer.text_for_range(start..end).collect::<String>();
 7920            let old_length = text.len() as i32;
 7921            let text = callback(&text);
 7922
 7923            new_selections.push(Selection {
 7924                start: (start as i32 - selection_adjustment) as usize,
 7925                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7926                goal: SelectionGoal::None,
 7927                ..selection
 7928            });
 7929
 7930            selection_adjustment += old_length - text.len() as i32;
 7931
 7932            edits.push((start..end, text));
 7933        }
 7934
 7935        self.transact(window, cx, |this, window, cx| {
 7936            this.buffer.update(cx, |buffer, cx| {
 7937                buffer.edit(edits, None, cx);
 7938            });
 7939
 7940            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7941                s.select(new_selections);
 7942            });
 7943
 7944            this.request_autoscroll(Autoscroll::fit(), cx);
 7945        });
 7946    }
 7947
 7948    pub fn duplicate(
 7949        &mut self,
 7950        upwards: bool,
 7951        whole_lines: bool,
 7952        window: &mut Window,
 7953        cx: &mut Context<Self>,
 7954    ) {
 7955        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7956        let buffer = &display_map.buffer_snapshot;
 7957        let selections = self.selections.all::<Point>(cx);
 7958
 7959        let mut edits = Vec::new();
 7960        let mut selections_iter = selections.iter().peekable();
 7961        while let Some(selection) = selections_iter.next() {
 7962            let mut rows = selection.spanned_rows(false, &display_map);
 7963            // duplicate line-wise
 7964            if whole_lines || selection.start == selection.end {
 7965                // Avoid duplicating the same lines twice.
 7966                while let Some(next_selection) = selections_iter.peek() {
 7967                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7968                    if next_rows.start < rows.end {
 7969                        rows.end = next_rows.end;
 7970                        selections_iter.next().unwrap();
 7971                    } else {
 7972                        break;
 7973                    }
 7974                }
 7975
 7976                // Copy the text from the selected row region and splice it either at the start
 7977                // or end of the region.
 7978                let start = Point::new(rows.start.0, 0);
 7979                let end = Point::new(
 7980                    rows.end.previous_row().0,
 7981                    buffer.line_len(rows.end.previous_row()),
 7982                );
 7983                let text = buffer
 7984                    .text_for_range(start..end)
 7985                    .chain(Some("\n"))
 7986                    .collect::<String>();
 7987                let insert_location = if upwards {
 7988                    Point::new(rows.end.0, 0)
 7989                } else {
 7990                    start
 7991                };
 7992                edits.push((insert_location..insert_location, text));
 7993            } else {
 7994                // duplicate character-wise
 7995                let start = selection.start;
 7996                let end = selection.end;
 7997                let text = buffer.text_for_range(start..end).collect::<String>();
 7998                edits.push((selection.end..selection.end, text));
 7999            }
 8000        }
 8001
 8002        self.transact(window, cx, |this, _, cx| {
 8003            this.buffer.update(cx, |buffer, cx| {
 8004                buffer.edit(edits, None, cx);
 8005            });
 8006
 8007            this.request_autoscroll(Autoscroll::fit(), cx);
 8008        });
 8009    }
 8010
 8011    pub fn duplicate_line_up(
 8012        &mut self,
 8013        _: &DuplicateLineUp,
 8014        window: &mut Window,
 8015        cx: &mut Context<Self>,
 8016    ) {
 8017        self.duplicate(true, true, window, cx);
 8018    }
 8019
 8020    pub fn duplicate_line_down(
 8021        &mut self,
 8022        _: &DuplicateLineDown,
 8023        window: &mut Window,
 8024        cx: &mut Context<Self>,
 8025    ) {
 8026        self.duplicate(false, true, window, cx);
 8027    }
 8028
 8029    pub fn duplicate_selection(
 8030        &mut self,
 8031        _: &DuplicateSelection,
 8032        window: &mut Window,
 8033        cx: &mut Context<Self>,
 8034    ) {
 8035        self.duplicate(false, false, window, cx);
 8036    }
 8037
 8038    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8039        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8040        let buffer = self.buffer.read(cx).snapshot(cx);
 8041
 8042        let mut edits = Vec::new();
 8043        let mut unfold_ranges = Vec::new();
 8044        let mut refold_creases = Vec::new();
 8045
 8046        let selections = self.selections.all::<Point>(cx);
 8047        let mut selections = selections.iter().peekable();
 8048        let mut contiguous_row_selections = Vec::new();
 8049        let mut new_selections = Vec::new();
 8050
 8051        while let Some(selection) = selections.next() {
 8052            // Find all the selections that span a contiguous row range
 8053            let (start_row, end_row) = consume_contiguous_rows(
 8054                &mut contiguous_row_selections,
 8055                selection,
 8056                &display_map,
 8057                &mut selections,
 8058            );
 8059
 8060            // Move the text spanned by the row range to be before the line preceding the row range
 8061            if start_row.0 > 0 {
 8062                let range_to_move = Point::new(
 8063                    start_row.previous_row().0,
 8064                    buffer.line_len(start_row.previous_row()),
 8065                )
 8066                    ..Point::new(
 8067                        end_row.previous_row().0,
 8068                        buffer.line_len(end_row.previous_row()),
 8069                    );
 8070                let insertion_point = display_map
 8071                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8072                    .0;
 8073
 8074                // Don't move lines across excerpts
 8075                if buffer
 8076                    .excerpt_containing(insertion_point..range_to_move.end)
 8077                    .is_some()
 8078                {
 8079                    let text = buffer
 8080                        .text_for_range(range_to_move.clone())
 8081                        .flat_map(|s| s.chars())
 8082                        .skip(1)
 8083                        .chain(['\n'])
 8084                        .collect::<String>();
 8085
 8086                    edits.push((
 8087                        buffer.anchor_after(range_to_move.start)
 8088                            ..buffer.anchor_before(range_to_move.end),
 8089                        String::new(),
 8090                    ));
 8091                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8092                    edits.push((insertion_anchor..insertion_anchor, text));
 8093
 8094                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8095
 8096                    // Move selections up
 8097                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8098                        |mut selection| {
 8099                            selection.start.row -= row_delta;
 8100                            selection.end.row -= row_delta;
 8101                            selection
 8102                        },
 8103                    ));
 8104
 8105                    // Move folds up
 8106                    unfold_ranges.push(range_to_move.clone());
 8107                    for fold in display_map.folds_in_range(
 8108                        buffer.anchor_before(range_to_move.start)
 8109                            ..buffer.anchor_after(range_to_move.end),
 8110                    ) {
 8111                        let mut start = fold.range.start.to_point(&buffer);
 8112                        let mut end = fold.range.end.to_point(&buffer);
 8113                        start.row -= row_delta;
 8114                        end.row -= row_delta;
 8115                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8116                    }
 8117                }
 8118            }
 8119
 8120            // If we didn't move line(s), preserve the existing selections
 8121            new_selections.append(&mut contiguous_row_selections);
 8122        }
 8123
 8124        self.transact(window, cx, |this, window, cx| {
 8125            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8126            this.buffer.update(cx, |buffer, cx| {
 8127                for (range, text) in edits {
 8128                    buffer.edit([(range, text)], None, cx);
 8129                }
 8130            });
 8131            this.fold_creases(refold_creases, true, window, cx);
 8132            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8133                s.select(new_selections);
 8134            })
 8135        });
 8136    }
 8137
 8138    pub fn move_line_down(
 8139        &mut self,
 8140        _: &MoveLineDown,
 8141        window: &mut Window,
 8142        cx: &mut Context<Self>,
 8143    ) {
 8144        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8145        let buffer = self.buffer.read(cx).snapshot(cx);
 8146
 8147        let mut edits = Vec::new();
 8148        let mut unfold_ranges = Vec::new();
 8149        let mut refold_creases = Vec::new();
 8150
 8151        let selections = self.selections.all::<Point>(cx);
 8152        let mut selections = selections.iter().peekable();
 8153        let mut contiguous_row_selections = Vec::new();
 8154        let mut new_selections = Vec::new();
 8155
 8156        while let Some(selection) = selections.next() {
 8157            // Find all the selections that span a contiguous row range
 8158            let (start_row, end_row) = consume_contiguous_rows(
 8159                &mut contiguous_row_selections,
 8160                selection,
 8161                &display_map,
 8162                &mut selections,
 8163            );
 8164
 8165            // Move the text spanned by the row range to be after the last line of the row range
 8166            if end_row.0 <= buffer.max_point().row {
 8167                let range_to_move =
 8168                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8169                let insertion_point = display_map
 8170                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8171                    .0;
 8172
 8173                // Don't move lines across excerpt boundaries
 8174                if buffer
 8175                    .excerpt_containing(range_to_move.start..insertion_point)
 8176                    .is_some()
 8177                {
 8178                    let mut text = String::from("\n");
 8179                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8180                    text.pop(); // Drop trailing newline
 8181                    edits.push((
 8182                        buffer.anchor_after(range_to_move.start)
 8183                            ..buffer.anchor_before(range_to_move.end),
 8184                        String::new(),
 8185                    ));
 8186                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8187                    edits.push((insertion_anchor..insertion_anchor, text));
 8188
 8189                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8190
 8191                    // Move selections down
 8192                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8193                        |mut selection| {
 8194                            selection.start.row += row_delta;
 8195                            selection.end.row += row_delta;
 8196                            selection
 8197                        },
 8198                    ));
 8199
 8200                    // Move folds down
 8201                    unfold_ranges.push(range_to_move.clone());
 8202                    for fold in display_map.folds_in_range(
 8203                        buffer.anchor_before(range_to_move.start)
 8204                            ..buffer.anchor_after(range_to_move.end),
 8205                    ) {
 8206                        let mut start = fold.range.start.to_point(&buffer);
 8207                        let mut end = fold.range.end.to_point(&buffer);
 8208                        start.row += row_delta;
 8209                        end.row += row_delta;
 8210                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8211                    }
 8212                }
 8213            }
 8214
 8215            // If we didn't move line(s), preserve the existing selections
 8216            new_selections.append(&mut contiguous_row_selections);
 8217        }
 8218
 8219        self.transact(window, cx, |this, window, cx| {
 8220            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8221            this.buffer.update(cx, |buffer, cx| {
 8222                for (range, text) in edits {
 8223                    buffer.edit([(range, text)], None, cx);
 8224                }
 8225            });
 8226            this.fold_creases(refold_creases, true, window, cx);
 8227            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8228                s.select(new_selections)
 8229            });
 8230        });
 8231    }
 8232
 8233    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8234        let text_layout_details = &self.text_layout_details(window);
 8235        self.transact(window, cx, |this, window, cx| {
 8236            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8237                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8238                let line_mode = s.line_mode;
 8239                s.move_with(|display_map, selection| {
 8240                    if !selection.is_empty() || line_mode {
 8241                        return;
 8242                    }
 8243
 8244                    let mut head = selection.head();
 8245                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8246                    if head.column() == display_map.line_len(head.row()) {
 8247                        transpose_offset = display_map
 8248                            .buffer_snapshot
 8249                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8250                    }
 8251
 8252                    if transpose_offset == 0 {
 8253                        return;
 8254                    }
 8255
 8256                    *head.column_mut() += 1;
 8257                    head = display_map.clip_point(head, Bias::Right);
 8258                    let goal = SelectionGoal::HorizontalPosition(
 8259                        display_map
 8260                            .x_for_display_point(head, text_layout_details)
 8261                            .into(),
 8262                    );
 8263                    selection.collapse_to(head, goal);
 8264
 8265                    let transpose_start = display_map
 8266                        .buffer_snapshot
 8267                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8268                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8269                        let transpose_end = display_map
 8270                            .buffer_snapshot
 8271                            .clip_offset(transpose_offset + 1, Bias::Right);
 8272                        if let Some(ch) =
 8273                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8274                        {
 8275                            edits.push((transpose_start..transpose_offset, String::new()));
 8276                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8277                        }
 8278                    }
 8279                });
 8280                edits
 8281            });
 8282            this.buffer
 8283                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8284            let selections = this.selections.all::<usize>(cx);
 8285            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8286                s.select(selections);
 8287            });
 8288        });
 8289    }
 8290
 8291    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8292        self.rewrap_impl(IsVimMode::No, cx)
 8293    }
 8294
 8295    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8296        let buffer = self.buffer.read(cx).snapshot(cx);
 8297        let selections = self.selections.all::<Point>(cx);
 8298        let mut selections = selections.iter().peekable();
 8299
 8300        let mut edits = Vec::new();
 8301        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8302
 8303        while let Some(selection) = selections.next() {
 8304            let mut start_row = selection.start.row;
 8305            let mut end_row = selection.end.row;
 8306
 8307            // Skip selections that overlap with a range that has already been rewrapped.
 8308            let selection_range = start_row..end_row;
 8309            if rewrapped_row_ranges
 8310                .iter()
 8311                .any(|range| range.overlaps(&selection_range))
 8312            {
 8313                continue;
 8314            }
 8315
 8316            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 8317
 8318            // Since not all lines in the selection may be at the same indent
 8319            // level, choose the indent size that is the most common between all
 8320            // of the lines.
 8321            //
 8322            // If there is a tie, we use the deepest indent.
 8323            let (indent_size, indent_end) = {
 8324                let mut indent_size_occurrences = HashMap::default();
 8325                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8326
 8327                for row in start_row..=end_row {
 8328                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8329                    rows_by_indent_size.entry(indent).or_default().push(row);
 8330                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8331                }
 8332
 8333                let indent_size = indent_size_occurrences
 8334                    .into_iter()
 8335                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8336                    .map(|(indent, _)| indent)
 8337                    .unwrap_or_default();
 8338                let row = rows_by_indent_size[&indent_size][0];
 8339                let indent_end = Point::new(row, indent_size.len);
 8340
 8341                (indent_size, indent_end)
 8342            };
 8343
 8344            let mut line_prefix = indent_size.chars().collect::<String>();
 8345
 8346            let mut inside_comment = false;
 8347            if let Some(comment_prefix) =
 8348                buffer
 8349                    .language_scope_at(selection.head())
 8350                    .and_then(|language| {
 8351                        language
 8352                            .line_comment_prefixes()
 8353                            .iter()
 8354                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8355                            .cloned()
 8356                    })
 8357            {
 8358                line_prefix.push_str(&comment_prefix);
 8359                inside_comment = true;
 8360            }
 8361
 8362            let language_settings = buffer.settings_at(selection.head(), cx);
 8363            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8364                RewrapBehavior::InComments => inside_comment,
 8365                RewrapBehavior::InSelections => !selection.is_empty(),
 8366                RewrapBehavior::Anywhere => true,
 8367            };
 8368
 8369            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8370            if !should_rewrap {
 8371                continue;
 8372            }
 8373
 8374            if selection.is_empty() {
 8375                'expand_upwards: while start_row > 0 {
 8376                    let prev_row = start_row - 1;
 8377                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8378                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8379                    {
 8380                        start_row = prev_row;
 8381                    } else {
 8382                        break 'expand_upwards;
 8383                    }
 8384                }
 8385
 8386                'expand_downwards: while end_row < buffer.max_point().row {
 8387                    let next_row = end_row + 1;
 8388                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8389                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8390                    {
 8391                        end_row = next_row;
 8392                    } else {
 8393                        break 'expand_downwards;
 8394                    }
 8395                }
 8396            }
 8397
 8398            let start = Point::new(start_row, 0);
 8399            let start_offset = start.to_offset(&buffer);
 8400            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8401            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8402            let Some(lines_without_prefixes) = selection_text
 8403                .lines()
 8404                .map(|line| {
 8405                    line.strip_prefix(&line_prefix)
 8406                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8407                        .ok_or_else(|| {
 8408                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8409                        })
 8410                })
 8411                .collect::<Result<Vec<_>, _>>()
 8412                .log_err()
 8413            else {
 8414                continue;
 8415            };
 8416
 8417            let wrap_column = buffer
 8418                .settings_at(Point::new(start_row, 0), cx)
 8419                .preferred_line_length as usize;
 8420            let wrapped_text = wrap_with_prefix(
 8421                line_prefix,
 8422                lines_without_prefixes.join(" "),
 8423                wrap_column,
 8424                tab_size,
 8425            );
 8426
 8427            // TODO: should always use char-based diff while still supporting cursor behavior that
 8428            // matches vim.
 8429            let mut diff_options = DiffOptions::default();
 8430            if is_vim_mode == IsVimMode::Yes {
 8431                diff_options.max_word_diff_len = 0;
 8432                diff_options.max_word_diff_line_count = 0;
 8433            } else {
 8434                diff_options.max_word_diff_len = usize::MAX;
 8435                diff_options.max_word_diff_line_count = usize::MAX;
 8436            }
 8437
 8438            for (old_range, new_text) in
 8439                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8440            {
 8441                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8442                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8443                edits.push((edit_start..edit_end, new_text));
 8444            }
 8445
 8446            rewrapped_row_ranges.push(start_row..=end_row);
 8447        }
 8448
 8449        self.buffer
 8450            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8451    }
 8452
 8453    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8454        let mut text = String::new();
 8455        let buffer = self.buffer.read(cx).snapshot(cx);
 8456        let mut selections = self.selections.all::<Point>(cx);
 8457        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8458        {
 8459            let max_point = buffer.max_point();
 8460            let mut is_first = true;
 8461            for selection in &mut selections {
 8462                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8463                if is_entire_line {
 8464                    selection.start = Point::new(selection.start.row, 0);
 8465                    if !selection.is_empty() && selection.end.column == 0 {
 8466                        selection.end = cmp::min(max_point, selection.end);
 8467                    } else {
 8468                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8469                    }
 8470                    selection.goal = SelectionGoal::None;
 8471                }
 8472                if is_first {
 8473                    is_first = false;
 8474                } else {
 8475                    text += "\n";
 8476                }
 8477                let mut len = 0;
 8478                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8479                    text.push_str(chunk);
 8480                    len += chunk.len();
 8481                }
 8482                clipboard_selections.push(ClipboardSelection {
 8483                    len,
 8484                    is_entire_line,
 8485                    start_column: selection.start.column,
 8486                });
 8487            }
 8488        }
 8489
 8490        self.transact(window, cx, |this, window, cx| {
 8491            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8492                s.select(selections);
 8493            });
 8494            this.insert("", window, cx);
 8495        });
 8496        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8497    }
 8498
 8499    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8500        let item = self.cut_common(window, cx);
 8501        cx.write_to_clipboard(item);
 8502    }
 8503
 8504    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8505        self.change_selections(None, window, cx, |s| {
 8506            s.move_with(|snapshot, sel| {
 8507                if sel.is_empty() {
 8508                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8509                }
 8510            });
 8511        });
 8512        let item = self.cut_common(window, cx);
 8513        cx.set_global(KillRing(item))
 8514    }
 8515
 8516    pub fn kill_ring_yank(
 8517        &mut self,
 8518        _: &KillRingYank,
 8519        window: &mut Window,
 8520        cx: &mut Context<Self>,
 8521    ) {
 8522        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8523            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8524                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8525            } else {
 8526                return;
 8527            }
 8528        } else {
 8529            return;
 8530        };
 8531        self.do_paste(&text, metadata, false, window, cx);
 8532    }
 8533
 8534    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8535        let selections = self.selections.all::<Point>(cx);
 8536        let buffer = self.buffer.read(cx).read(cx);
 8537        let mut text = String::new();
 8538
 8539        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8540        {
 8541            let max_point = buffer.max_point();
 8542            let mut is_first = true;
 8543            for selection in selections.iter() {
 8544                let mut start = selection.start;
 8545                let mut end = selection.end;
 8546                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8547                if is_entire_line {
 8548                    start = Point::new(start.row, 0);
 8549                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8550                }
 8551                if is_first {
 8552                    is_first = false;
 8553                } else {
 8554                    text += "\n";
 8555                }
 8556                let mut len = 0;
 8557                for chunk in buffer.text_for_range(start..end) {
 8558                    text.push_str(chunk);
 8559                    len += chunk.len();
 8560                }
 8561                clipboard_selections.push(ClipboardSelection {
 8562                    len,
 8563                    is_entire_line,
 8564                    start_column: start.column,
 8565                });
 8566            }
 8567        }
 8568
 8569        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8570            text,
 8571            clipboard_selections,
 8572        ));
 8573    }
 8574
 8575    pub fn do_paste(
 8576        &mut self,
 8577        text: &String,
 8578        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8579        handle_entire_lines: bool,
 8580        window: &mut Window,
 8581        cx: &mut Context<Self>,
 8582    ) {
 8583        if self.read_only(cx) {
 8584            return;
 8585        }
 8586
 8587        let clipboard_text = Cow::Borrowed(text);
 8588
 8589        self.transact(window, cx, |this, window, cx| {
 8590            if let Some(mut clipboard_selections) = clipboard_selections {
 8591                let old_selections = this.selections.all::<usize>(cx);
 8592                let all_selections_were_entire_line =
 8593                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8594                let first_selection_start_column =
 8595                    clipboard_selections.first().map(|s| s.start_column);
 8596                if clipboard_selections.len() != old_selections.len() {
 8597                    clipboard_selections.drain(..);
 8598                }
 8599                let cursor_offset = this.selections.last::<usize>(cx).head();
 8600                let mut auto_indent_on_paste = true;
 8601
 8602                this.buffer.update(cx, |buffer, cx| {
 8603                    let snapshot = buffer.read(cx);
 8604                    auto_indent_on_paste =
 8605                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8606
 8607                    let mut start_offset = 0;
 8608                    let mut edits = Vec::new();
 8609                    let mut original_start_columns = Vec::new();
 8610                    for (ix, selection) in old_selections.iter().enumerate() {
 8611                        let to_insert;
 8612                        let entire_line;
 8613                        let original_start_column;
 8614                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8615                            let end_offset = start_offset + clipboard_selection.len;
 8616                            to_insert = &clipboard_text[start_offset..end_offset];
 8617                            entire_line = clipboard_selection.is_entire_line;
 8618                            start_offset = end_offset + 1;
 8619                            original_start_column = Some(clipboard_selection.start_column);
 8620                        } else {
 8621                            to_insert = clipboard_text.as_str();
 8622                            entire_line = all_selections_were_entire_line;
 8623                            original_start_column = first_selection_start_column
 8624                        }
 8625
 8626                        // If the corresponding selection was empty when this slice of the
 8627                        // clipboard text was written, then the entire line containing the
 8628                        // selection was copied. If this selection is also currently empty,
 8629                        // then paste the line before the current line of the buffer.
 8630                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8631                            let column = selection.start.to_point(&snapshot).column as usize;
 8632                            let line_start = selection.start - column;
 8633                            line_start..line_start
 8634                        } else {
 8635                            selection.range()
 8636                        };
 8637
 8638                        edits.push((range, to_insert));
 8639                        original_start_columns.extend(original_start_column);
 8640                    }
 8641                    drop(snapshot);
 8642
 8643                    buffer.edit(
 8644                        edits,
 8645                        if auto_indent_on_paste {
 8646                            Some(AutoindentMode::Block {
 8647                                original_start_columns,
 8648                            })
 8649                        } else {
 8650                            None
 8651                        },
 8652                        cx,
 8653                    );
 8654                });
 8655
 8656                let selections = this.selections.all::<usize>(cx);
 8657                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8658                    s.select(selections)
 8659                });
 8660            } else {
 8661                this.insert(&clipboard_text, window, cx);
 8662            }
 8663        });
 8664    }
 8665
 8666    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8667        if let Some(item) = cx.read_from_clipboard() {
 8668            let entries = item.entries();
 8669
 8670            match entries.first() {
 8671                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8672                // of all the pasted entries.
 8673                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8674                    .do_paste(
 8675                        clipboard_string.text(),
 8676                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8677                        true,
 8678                        window,
 8679                        cx,
 8680                    ),
 8681                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8682            }
 8683        }
 8684    }
 8685
 8686    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8687        if self.read_only(cx) {
 8688            return;
 8689        }
 8690
 8691        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8692            if let Some((selections, _)) =
 8693                self.selection_history.transaction(transaction_id).cloned()
 8694            {
 8695                self.change_selections(None, window, cx, |s| {
 8696                    s.select_anchors(selections.to_vec());
 8697                });
 8698            }
 8699            self.request_autoscroll(Autoscroll::fit(), cx);
 8700            self.unmark_text(window, cx);
 8701            self.refresh_inline_completion(true, false, window, cx);
 8702            cx.emit(EditorEvent::Edited { transaction_id });
 8703            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8704        }
 8705    }
 8706
 8707    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8708        if self.read_only(cx) {
 8709            return;
 8710        }
 8711
 8712        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8713            if let Some((_, Some(selections))) =
 8714                self.selection_history.transaction(transaction_id).cloned()
 8715            {
 8716                self.change_selections(None, window, cx, |s| {
 8717                    s.select_anchors(selections.to_vec());
 8718                });
 8719            }
 8720            self.request_autoscroll(Autoscroll::fit(), cx);
 8721            self.unmark_text(window, cx);
 8722            self.refresh_inline_completion(true, false, window, cx);
 8723            cx.emit(EditorEvent::Edited { transaction_id });
 8724        }
 8725    }
 8726
 8727    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8728        self.buffer
 8729            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8730    }
 8731
 8732    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8733        self.buffer
 8734            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8735    }
 8736
 8737    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8738        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8739            let line_mode = s.line_mode;
 8740            s.move_with(|map, selection| {
 8741                let cursor = if selection.is_empty() && !line_mode {
 8742                    movement::left(map, selection.start)
 8743                } else {
 8744                    selection.start
 8745                };
 8746                selection.collapse_to(cursor, SelectionGoal::None);
 8747            });
 8748        })
 8749    }
 8750
 8751    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8752        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8753            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8754        })
 8755    }
 8756
 8757    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8758        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8759            let line_mode = s.line_mode;
 8760            s.move_with(|map, selection| {
 8761                let cursor = if selection.is_empty() && !line_mode {
 8762                    movement::right(map, selection.end)
 8763                } else {
 8764                    selection.end
 8765                };
 8766                selection.collapse_to(cursor, SelectionGoal::None)
 8767            });
 8768        })
 8769    }
 8770
 8771    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8772        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8773            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8774        })
 8775    }
 8776
 8777    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8778        if self.take_rename(true, window, cx).is_some() {
 8779            return;
 8780        }
 8781
 8782        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8783            cx.propagate();
 8784            return;
 8785        }
 8786
 8787        let text_layout_details = &self.text_layout_details(window);
 8788        let selection_count = self.selections.count();
 8789        let first_selection = self.selections.first_anchor();
 8790
 8791        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8792            let line_mode = s.line_mode;
 8793            s.move_with(|map, selection| {
 8794                if !selection.is_empty() && !line_mode {
 8795                    selection.goal = SelectionGoal::None;
 8796                }
 8797                let (cursor, goal) = movement::up(
 8798                    map,
 8799                    selection.start,
 8800                    selection.goal,
 8801                    false,
 8802                    text_layout_details,
 8803                );
 8804                selection.collapse_to(cursor, goal);
 8805            });
 8806        });
 8807
 8808        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8809        {
 8810            cx.propagate();
 8811        }
 8812    }
 8813
 8814    pub fn move_up_by_lines(
 8815        &mut self,
 8816        action: &MoveUpByLines,
 8817        window: &mut Window,
 8818        cx: &mut Context<Self>,
 8819    ) {
 8820        if self.take_rename(true, window, cx).is_some() {
 8821            return;
 8822        }
 8823
 8824        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8825            cx.propagate();
 8826            return;
 8827        }
 8828
 8829        let text_layout_details = &self.text_layout_details(window);
 8830
 8831        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8832            let line_mode = s.line_mode;
 8833            s.move_with(|map, selection| {
 8834                if !selection.is_empty() && !line_mode {
 8835                    selection.goal = SelectionGoal::None;
 8836                }
 8837                let (cursor, goal) = movement::up_by_rows(
 8838                    map,
 8839                    selection.start,
 8840                    action.lines,
 8841                    selection.goal,
 8842                    false,
 8843                    text_layout_details,
 8844                );
 8845                selection.collapse_to(cursor, goal);
 8846            });
 8847        })
 8848    }
 8849
 8850    pub fn move_down_by_lines(
 8851        &mut self,
 8852        action: &MoveDownByLines,
 8853        window: &mut Window,
 8854        cx: &mut Context<Self>,
 8855    ) {
 8856        if self.take_rename(true, window, cx).is_some() {
 8857            return;
 8858        }
 8859
 8860        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8861            cx.propagate();
 8862            return;
 8863        }
 8864
 8865        let text_layout_details = &self.text_layout_details(window);
 8866
 8867        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8868            let line_mode = s.line_mode;
 8869            s.move_with(|map, selection| {
 8870                if !selection.is_empty() && !line_mode {
 8871                    selection.goal = SelectionGoal::None;
 8872                }
 8873                let (cursor, goal) = movement::down_by_rows(
 8874                    map,
 8875                    selection.start,
 8876                    action.lines,
 8877                    selection.goal,
 8878                    false,
 8879                    text_layout_details,
 8880                );
 8881                selection.collapse_to(cursor, goal);
 8882            });
 8883        })
 8884    }
 8885
 8886    pub fn select_down_by_lines(
 8887        &mut self,
 8888        action: &SelectDownByLines,
 8889        window: &mut Window,
 8890        cx: &mut Context<Self>,
 8891    ) {
 8892        let text_layout_details = &self.text_layout_details(window);
 8893        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8894            s.move_heads_with(|map, head, goal| {
 8895                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8896            })
 8897        })
 8898    }
 8899
 8900    pub fn select_up_by_lines(
 8901        &mut self,
 8902        action: &SelectUpByLines,
 8903        window: &mut Window,
 8904        cx: &mut Context<Self>,
 8905    ) {
 8906        let text_layout_details = &self.text_layout_details(window);
 8907        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8908            s.move_heads_with(|map, head, goal| {
 8909                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8910            })
 8911        })
 8912    }
 8913
 8914    pub fn select_page_up(
 8915        &mut self,
 8916        _: &SelectPageUp,
 8917        window: &mut Window,
 8918        cx: &mut Context<Self>,
 8919    ) {
 8920        let Some(row_count) = self.visible_row_count() else {
 8921            return;
 8922        };
 8923
 8924        let text_layout_details = &self.text_layout_details(window);
 8925
 8926        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8927            s.move_heads_with(|map, head, goal| {
 8928                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8929            })
 8930        })
 8931    }
 8932
 8933    pub fn move_page_up(
 8934        &mut self,
 8935        action: &MovePageUp,
 8936        window: &mut Window,
 8937        cx: &mut Context<Self>,
 8938    ) {
 8939        if self.take_rename(true, window, cx).is_some() {
 8940            return;
 8941        }
 8942
 8943        if self
 8944            .context_menu
 8945            .borrow_mut()
 8946            .as_mut()
 8947            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8948            .unwrap_or(false)
 8949        {
 8950            return;
 8951        }
 8952
 8953        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8954            cx.propagate();
 8955            return;
 8956        }
 8957
 8958        let Some(row_count) = self.visible_row_count() else {
 8959            return;
 8960        };
 8961
 8962        let autoscroll = if action.center_cursor {
 8963            Autoscroll::center()
 8964        } else {
 8965            Autoscroll::fit()
 8966        };
 8967
 8968        let text_layout_details = &self.text_layout_details(window);
 8969
 8970        self.change_selections(Some(autoscroll), window, cx, |s| {
 8971            let line_mode = s.line_mode;
 8972            s.move_with(|map, selection| {
 8973                if !selection.is_empty() && !line_mode {
 8974                    selection.goal = SelectionGoal::None;
 8975                }
 8976                let (cursor, goal) = movement::up_by_rows(
 8977                    map,
 8978                    selection.end,
 8979                    row_count,
 8980                    selection.goal,
 8981                    false,
 8982                    text_layout_details,
 8983                );
 8984                selection.collapse_to(cursor, goal);
 8985            });
 8986        });
 8987    }
 8988
 8989    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8990        let text_layout_details = &self.text_layout_details(window);
 8991        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8992            s.move_heads_with(|map, head, goal| {
 8993                movement::up(map, head, goal, false, text_layout_details)
 8994            })
 8995        })
 8996    }
 8997
 8998    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8999        self.take_rename(true, window, cx);
 9000
 9001        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9002            cx.propagate();
 9003            return;
 9004        }
 9005
 9006        let text_layout_details = &self.text_layout_details(window);
 9007        let selection_count = self.selections.count();
 9008        let first_selection = self.selections.first_anchor();
 9009
 9010        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9011            let line_mode = s.line_mode;
 9012            s.move_with(|map, selection| {
 9013                if !selection.is_empty() && !line_mode {
 9014                    selection.goal = SelectionGoal::None;
 9015                }
 9016                let (cursor, goal) = movement::down(
 9017                    map,
 9018                    selection.end,
 9019                    selection.goal,
 9020                    false,
 9021                    text_layout_details,
 9022                );
 9023                selection.collapse_to(cursor, goal);
 9024            });
 9025        });
 9026
 9027        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9028        {
 9029            cx.propagate();
 9030        }
 9031    }
 9032
 9033    pub fn select_page_down(
 9034        &mut self,
 9035        _: &SelectPageDown,
 9036        window: &mut Window,
 9037        cx: &mut Context<Self>,
 9038    ) {
 9039        let Some(row_count) = self.visible_row_count() else {
 9040            return;
 9041        };
 9042
 9043        let text_layout_details = &self.text_layout_details(window);
 9044
 9045        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9046            s.move_heads_with(|map, head, goal| {
 9047                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9048            })
 9049        })
 9050    }
 9051
 9052    pub fn move_page_down(
 9053        &mut self,
 9054        action: &MovePageDown,
 9055        window: &mut Window,
 9056        cx: &mut Context<Self>,
 9057    ) {
 9058        if self.take_rename(true, window, cx).is_some() {
 9059            return;
 9060        }
 9061
 9062        if self
 9063            .context_menu
 9064            .borrow_mut()
 9065            .as_mut()
 9066            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9067            .unwrap_or(false)
 9068        {
 9069            return;
 9070        }
 9071
 9072        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9073            cx.propagate();
 9074            return;
 9075        }
 9076
 9077        let Some(row_count) = self.visible_row_count() else {
 9078            return;
 9079        };
 9080
 9081        let autoscroll = if action.center_cursor {
 9082            Autoscroll::center()
 9083        } else {
 9084            Autoscroll::fit()
 9085        };
 9086
 9087        let text_layout_details = &self.text_layout_details(window);
 9088        self.change_selections(Some(autoscroll), window, cx, |s| {
 9089            let line_mode = s.line_mode;
 9090            s.move_with(|map, selection| {
 9091                if !selection.is_empty() && !line_mode {
 9092                    selection.goal = SelectionGoal::None;
 9093                }
 9094                let (cursor, goal) = movement::down_by_rows(
 9095                    map,
 9096                    selection.end,
 9097                    row_count,
 9098                    selection.goal,
 9099                    false,
 9100                    text_layout_details,
 9101                );
 9102                selection.collapse_to(cursor, goal);
 9103            });
 9104        });
 9105    }
 9106
 9107    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9108        let text_layout_details = &self.text_layout_details(window);
 9109        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9110            s.move_heads_with(|map, head, goal| {
 9111                movement::down(map, head, goal, false, text_layout_details)
 9112            })
 9113        });
 9114    }
 9115
 9116    pub fn context_menu_first(
 9117        &mut self,
 9118        _: &ContextMenuFirst,
 9119        _window: &mut Window,
 9120        cx: &mut Context<Self>,
 9121    ) {
 9122        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9123            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9124        }
 9125    }
 9126
 9127    pub fn context_menu_prev(
 9128        &mut self,
 9129        _: &ContextMenuPrev,
 9130        _window: &mut Window,
 9131        cx: &mut Context<Self>,
 9132    ) {
 9133        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9134            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9135        }
 9136    }
 9137
 9138    pub fn context_menu_next(
 9139        &mut self,
 9140        _: &ContextMenuNext,
 9141        _window: &mut Window,
 9142        cx: &mut Context<Self>,
 9143    ) {
 9144        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9145            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9146        }
 9147    }
 9148
 9149    pub fn context_menu_last(
 9150        &mut self,
 9151        _: &ContextMenuLast,
 9152        _window: &mut Window,
 9153        cx: &mut Context<Self>,
 9154    ) {
 9155        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9156            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9157        }
 9158    }
 9159
 9160    pub fn move_to_previous_word_start(
 9161        &mut self,
 9162        _: &MoveToPreviousWordStart,
 9163        window: &mut Window,
 9164        cx: &mut Context<Self>,
 9165    ) {
 9166        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9167            s.move_cursors_with(|map, head, _| {
 9168                (
 9169                    movement::previous_word_start(map, head),
 9170                    SelectionGoal::None,
 9171                )
 9172            });
 9173        })
 9174    }
 9175
 9176    pub fn move_to_previous_subword_start(
 9177        &mut self,
 9178        _: &MoveToPreviousSubwordStart,
 9179        window: &mut Window,
 9180        cx: &mut Context<Self>,
 9181    ) {
 9182        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9183            s.move_cursors_with(|map, head, _| {
 9184                (
 9185                    movement::previous_subword_start(map, head),
 9186                    SelectionGoal::None,
 9187                )
 9188            });
 9189        })
 9190    }
 9191
 9192    pub fn select_to_previous_word_start(
 9193        &mut self,
 9194        _: &SelectToPreviousWordStart,
 9195        window: &mut Window,
 9196        cx: &mut Context<Self>,
 9197    ) {
 9198        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9199            s.move_heads_with(|map, head, _| {
 9200                (
 9201                    movement::previous_word_start(map, head),
 9202                    SelectionGoal::None,
 9203                )
 9204            });
 9205        })
 9206    }
 9207
 9208    pub fn select_to_previous_subword_start(
 9209        &mut self,
 9210        _: &SelectToPreviousSubwordStart,
 9211        window: &mut Window,
 9212        cx: &mut Context<Self>,
 9213    ) {
 9214        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9215            s.move_heads_with(|map, head, _| {
 9216                (
 9217                    movement::previous_subword_start(map, head),
 9218                    SelectionGoal::None,
 9219                )
 9220            });
 9221        })
 9222    }
 9223
 9224    pub fn delete_to_previous_word_start(
 9225        &mut self,
 9226        action: &DeleteToPreviousWordStart,
 9227        window: &mut Window,
 9228        cx: &mut Context<Self>,
 9229    ) {
 9230        self.transact(window, cx, |this, window, cx| {
 9231            this.select_autoclose_pair(window, cx);
 9232            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9233                let line_mode = s.line_mode;
 9234                s.move_with(|map, selection| {
 9235                    if selection.is_empty() && !line_mode {
 9236                        let cursor = if action.ignore_newlines {
 9237                            movement::previous_word_start(map, selection.head())
 9238                        } else {
 9239                            movement::previous_word_start_or_newline(map, selection.head())
 9240                        };
 9241                        selection.set_head(cursor, SelectionGoal::None);
 9242                    }
 9243                });
 9244            });
 9245            this.insert("", window, cx);
 9246        });
 9247    }
 9248
 9249    pub fn delete_to_previous_subword_start(
 9250        &mut self,
 9251        _: &DeleteToPreviousSubwordStart,
 9252        window: &mut Window,
 9253        cx: &mut Context<Self>,
 9254    ) {
 9255        self.transact(window, cx, |this, window, cx| {
 9256            this.select_autoclose_pair(window, cx);
 9257            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9258                let line_mode = s.line_mode;
 9259                s.move_with(|map, selection| {
 9260                    if selection.is_empty() && !line_mode {
 9261                        let cursor = movement::previous_subword_start(map, selection.head());
 9262                        selection.set_head(cursor, SelectionGoal::None);
 9263                    }
 9264                });
 9265            });
 9266            this.insert("", window, cx);
 9267        });
 9268    }
 9269
 9270    pub fn move_to_next_word_end(
 9271        &mut self,
 9272        _: &MoveToNextWordEnd,
 9273        window: &mut Window,
 9274        cx: &mut Context<Self>,
 9275    ) {
 9276        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9277            s.move_cursors_with(|map, head, _| {
 9278                (movement::next_word_end(map, head), SelectionGoal::None)
 9279            });
 9280        })
 9281    }
 9282
 9283    pub fn move_to_next_subword_end(
 9284        &mut self,
 9285        _: &MoveToNextSubwordEnd,
 9286        window: &mut Window,
 9287        cx: &mut Context<Self>,
 9288    ) {
 9289        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9290            s.move_cursors_with(|map, head, _| {
 9291                (movement::next_subword_end(map, head), SelectionGoal::None)
 9292            });
 9293        })
 9294    }
 9295
 9296    pub fn select_to_next_word_end(
 9297        &mut self,
 9298        _: &SelectToNextWordEnd,
 9299        window: &mut Window,
 9300        cx: &mut Context<Self>,
 9301    ) {
 9302        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9303            s.move_heads_with(|map, head, _| {
 9304                (movement::next_word_end(map, head), SelectionGoal::None)
 9305            });
 9306        })
 9307    }
 9308
 9309    pub fn select_to_next_subword_end(
 9310        &mut self,
 9311        _: &SelectToNextSubwordEnd,
 9312        window: &mut Window,
 9313        cx: &mut Context<Self>,
 9314    ) {
 9315        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9316            s.move_heads_with(|map, head, _| {
 9317                (movement::next_subword_end(map, head), SelectionGoal::None)
 9318            });
 9319        })
 9320    }
 9321
 9322    pub fn delete_to_next_word_end(
 9323        &mut self,
 9324        action: &DeleteToNextWordEnd,
 9325        window: &mut Window,
 9326        cx: &mut Context<Self>,
 9327    ) {
 9328        self.transact(window, cx, |this, window, cx| {
 9329            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9330                let line_mode = s.line_mode;
 9331                s.move_with(|map, selection| {
 9332                    if selection.is_empty() && !line_mode {
 9333                        let cursor = if action.ignore_newlines {
 9334                            movement::next_word_end(map, selection.head())
 9335                        } else {
 9336                            movement::next_word_end_or_newline(map, selection.head())
 9337                        };
 9338                        selection.set_head(cursor, SelectionGoal::None);
 9339                    }
 9340                });
 9341            });
 9342            this.insert("", window, cx);
 9343        });
 9344    }
 9345
 9346    pub fn delete_to_next_subword_end(
 9347        &mut self,
 9348        _: &DeleteToNextSubwordEnd,
 9349        window: &mut Window,
 9350        cx: &mut Context<Self>,
 9351    ) {
 9352        self.transact(window, cx, |this, window, cx| {
 9353            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9354                s.move_with(|map, selection| {
 9355                    if selection.is_empty() {
 9356                        let cursor = movement::next_subword_end(map, selection.head());
 9357                        selection.set_head(cursor, SelectionGoal::None);
 9358                    }
 9359                });
 9360            });
 9361            this.insert("", window, cx);
 9362        });
 9363    }
 9364
 9365    pub fn move_to_beginning_of_line(
 9366        &mut self,
 9367        action: &MoveToBeginningOfLine,
 9368        window: &mut Window,
 9369        cx: &mut Context<Self>,
 9370    ) {
 9371        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9372            s.move_cursors_with(|map, head, _| {
 9373                (
 9374                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 9375                    SelectionGoal::None,
 9376                )
 9377            });
 9378        })
 9379    }
 9380
 9381    pub fn select_to_beginning_of_line(
 9382        &mut self,
 9383        action: &SelectToBeginningOfLine,
 9384        window: &mut Window,
 9385        cx: &mut Context<Self>,
 9386    ) {
 9387        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9388            s.move_heads_with(|map, head, _| {
 9389                (
 9390                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 9391                    SelectionGoal::None,
 9392                )
 9393            });
 9394        });
 9395    }
 9396
 9397    pub fn delete_to_beginning_of_line(
 9398        &mut self,
 9399        _: &DeleteToBeginningOfLine,
 9400        window: &mut Window,
 9401        cx: &mut Context<Self>,
 9402    ) {
 9403        self.transact(window, cx, |this, window, cx| {
 9404            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9405                s.move_with(|_, selection| {
 9406                    selection.reversed = true;
 9407                });
 9408            });
 9409
 9410            this.select_to_beginning_of_line(
 9411                &SelectToBeginningOfLine {
 9412                    stop_at_soft_wraps: false,
 9413                },
 9414                window,
 9415                cx,
 9416            );
 9417            this.backspace(&Backspace, window, cx);
 9418        });
 9419    }
 9420
 9421    pub fn move_to_end_of_line(
 9422        &mut self,
 9423        action: &MoveToEndOfLine,
 9424        window: &mut Window,
 9425        cx: &mut Context<Self>,
 9426    ) {
 9427        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9428            s.move_cursors_with(|map, head, _| {
 9429                (
 9430                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9431                    SelectionGoal::None,
 9432                )
 9433            });
 9434        })
 9435    }
 9436
 9437    pub fn select_to_end_of_line(
 9438        &mut self,
 9439        action: &SelectToEndOfLine,
 9440        window: &mut Window,
 9441        cx: &mut Context<Self>,
 9442    ) {
 9443        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9444            s.move_heads_with(|map, head, _| {
 9445                (
 9446                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9447                    SelectionGoal::None,
 9448                )
 9449            });
 9450        })
 9451    }
 9452
 9453    pub fn delete_to_end_of_line(
 9454        &mut self,
 9455        _: &DeleteToEndOfLine,
 9456        window: &mut Window,
 9457        cx: &mut Context<Self>,
 9458    ) {
 9459        self.transact(window, cx, |this, window, cx| {
 9460            this.select_to_end_of_line(
 9461                &SelectToEndOfLine {
 9462                    stop_at_soft_wraps: false,
 9463                },
 9464                window,
 9465                cx,
 9466            );
 9467            this.delete(&Delete, window, cx);
 9468        });
 9469    }
 9470
 9471    pub fn cut_to_end_of_line(
 9472        &mut self,
 9473        _: &CutToEndOfLine,
 9474        window: &mut Window,
 9475        cx: &mut Context<Self>,
 9476    ) {
 9477        self.transact(window, cx, |this, window, cx| {
 9478            this.select_to_end_of_line(
 9479                &SelectToEndOfLine {
 9480                    stop_at_soft_wraps: false,
 9481                },
 9482                window,
 9483                cx,
 9484            );
 9485            this.cut(&Cut, window, cx);
 9486        });
 9487    }
 9488
 9489    pub fn move_to_start_of_paragraph(
 9490        &mut self,
 9491        _: &MoveToStartOfParagraph,
 9492        window: &mut Window,
 9493        cx: &mut Context<Self>,
 9494    ) {
 9495        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9496            cx.propagate();
 9497            return;
 9498        }
 9499
 9500        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9501            s.move_with(|map, selection| {
 9502                selection.collapse_to(
 9503                    movement::start_of_paragraph(map, selection.head(), 1),
 9504                    SelectionGoal::None,
 9505                )
 9506            });
 9507        })
 9508    }
 9509
 9510    pub fn move_to_end_of_paragraph(
 9511        &mut self,
 9512        _: &MoveToEndOfParagraph,
 9513        window: &mut Window,
 9514        cx: &mut Context<Self>,
 9515    ) {
 9516        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9517            cx.propagate();
 9518            return;
 9519        }
 9520
 9521        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9522            s.move_with(|map, selection| {
 9523                selection.collapse_to(
 9524                    movement::end_of_paragraph(map, selection.head(), 1),
 9525                    SelectionGoal::None,
 9526                )
 9527            });
 9528        })
 9529    }
 9530
 9531    pub fn select_to_start_of_paragraph(
 9532        &mut self,
 9533        _: &SelectToStartOfParagraph,
 9534        window: &mut Window,
 9535        cx: &mut Context<Self>,
 9536    ) {
 9537        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9538            cx.propagate();
 9539            return;
 9540        }
 9541
 9542        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9543            s.move_heads_with(|map, head, _| {
 9544                (
 9545                    movement::start_of_paragraph(map, head, 1),
 9546                    SelectionGoal::None,
 9547                )
 9548            });
 9549        })
 9550    }
 9551
 9552    pub fn select_to_end_of_paragraph(
 9553        &mut self,
 9554        _: &SelectToEndOfParagraph,
 9555        window: &mut Window,
 9556        cx: &mut Context<Self>,
 9557    ) {
 9558        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9559            cx.propagate();
 9560            return;
 9561        }
 9562
 9563        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9564            s.move_heads_with(|map, head, _| {
 9565                (
 9566                    movement::end_of_paragraph(map, head, 1),
 9567                    SelectionGoal::None,
 9568                )
 9569            });
 9570        })
 9571    }
 9572
 9573    pub fn move_to_start_of_excerpt(
 9574        &mut self,
 9575        _: &MoveToStartOfExcerpt,
 9576        window: &mut Window,
 9577        cx: &mut Context<Self>,
 9578    ) {
 9579        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9580            cx.propagate();
 9581            return;
 9582        }
 9583
 9584        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9585            s.move_with(|map, selection| {
 9586                selection.collapse_to(
 9587                    movement::start_of_excerpt(
 9588                        map,
 9589                        selection.head(),
 9590                        workspace::searchable::Direction::Prev,
 9591                    ),
 9592                    SelectionGoal::None,
 9593                )
 9594            });
 9595        })
 9596    }
 9597
 9598    pub fn move_to_end_of_excerpt(
 9599        &mut self,
 9600        _: &MoveToEndOfExcerpt,
 9601        window: &mut Window,
 9602        cx: &mut Context<Self>,
 9603    ) {
 9604        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9605            cx.propagate();
 9606            return;
 9607        }
 9608
 9609        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9610            s.move_with(|map, selection| {
 9611                selection.collapse_to(
 9612                    movement::end_of_excerpt(
 9613                        map,
 9614                        selection.head(),
 9615                        workspace::searchable::Direction::Next,
 9616                    ),
 9617                    SelectionGoal::None,
 9618                )
 9619            });
 9620        })
 9621    }
 9622
 9623    pub fn select_to_start_of_excerpt(
 9624        &mut self,
 9625        _: &SelectToStartOfExcerpt,
 9626        window: &mut Window,
 9627        cx: &mut Context<Self>,
 9628    ) {
 9629        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9630            cx.propagate();
 9631            return;
 9632        }
 9633
 9634        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9635            s.move_heads_with(|map, head, _| {
 9636                (
 9637                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9638                    SelectionGoal::None,
 9639                )
 9640            });
 9641        })
 9642    }
 9643
 9644    pub fn select_to_end_of_excerpt(
 9645        &mut self,
 9646        _: &SelectToEndOfExcerpt,
 9647        window: &mut Window,
 9648        cx: &mut Context<Self>,
 9649    ) {
 9650        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9651            cx.propagate();
 9652            return;
 9653        }
 9654
 9655        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9656            s.move_heads_with(|map, head, _| {
 9657                (
 9658                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9659                    SelectionGoal::None,
 9660                )
 9661            });
 9662        })
 9663    }
 9664
 9665    pub fn move_to_beginning(
 9666        &mut self,
 9667        _: &MoveToBeginning,
 9668        window: &mut Window,
 9669        cx: &mut Context<Self>,
 9670    ) {
 9671        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9672            cx.propagate();
 9673            return;
 9674        }
 9675
 9676        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9677            s.select_ranges(vec![0..0]);
 9678        });
 9679    }
 9680
 9681    pub fn select_to_beginning(
 9682        &mut self,
 9683        _: &SelectToBeginning,
 9684        window: &mut Window,
 9685        cx: &mut Context<Self>,
 9686    ) {
 9687        let mut selection = self.selections.last::<Point>(cx);
 9688        selection.set_head(Point::zero(), SelectionGoal::None);
 9689
 9690        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9691            s.select(vec![selection]);
 9692        });
 9693    }
 9694
 9695    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9696        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9697            cx.propagate();
 9698            return;
 9699        }
 9700
 9701        let cursor = self.buffer.read(cx).read(cx).len();
 9702        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9703            s.select_ranges(vec![cursor..cursor])
 9704        });
 9705    }
 9706
 9707    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9708        self.nav_history = nav_history;
 9709    }
 9710
 9711    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9712        self.nav_history.as_ref()
 9713    }
 9714
 9715    fn push_to_nav_history(
 9716        &mut self,
 9717        cursor_anchor: Anchor,
 9718        new_position: Option<Point>,
 9719        cx: &mut Context<Self>,
 9720    ) {
 9721        if let Some(nav_history) = self.nav_history.as_mut() {
 9722            let buffer = self.buffer.read(cx).read(cx);
 9723            let cursor_position = cursor_anchor.to_point(&buffer);
 9724            let scroll_state = self.scroll_manager.anchor();
 9725            let scroll_top_row = scroll_state.top_row(&buffer);
 9726            drop(buffer);
 9727
 9728            if let Some(new_position) = new_position {
 9729                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9730                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9731                    return;
 9732                }
 9733            }
 9734
 9735            nav_history.push(
 9736                Some(NavigationData {
 9737                    cursor_anchor,
 9738                    cursor_position,
 9739                    scroll_anchor: scroll_state,
 9740                    scroll_top_row,
 9741                }),
 9742                cx,
 9743            );
 9744        }
 9745    }
 9746
 9747    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9748        let buffer = self.buffer.read(cx).snapshot(cx);
 9749        let mut selection = self.selections.first::<usize>(cx);
 9750        selection.set_head(buffer.len(), SelectionGoal::None);
 9751        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9752            s.select(vec![selection]);
 9753        });
 9754    }
 9755
 9756    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9757        let end = self.buffer.read(cx).read(cx).len();
 9758        self.change_selections(None, window, cx, |s| {
 9759            s.select_ranges(vec![0..end]);
 9760        });
 9761    }
 9762
 9763    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9764        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9765        let mut selections = self.selections.all::<Point>(cx);
 9766        let max_point = display_map.buffer_snapshot.max_point();
 9767        for selection in &mut selections {
 9768            let rows = selection.spanned_rows(true, &display_map);
 9769            selection.start = Point::new(rows.start.0, 0);
 9770            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9771            selection.reversed = false;
 9772        }
 9773        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9774            s.select(selections);
 9775        });
 9776    }
 9777
 9778    pub fn split_selection_into_lines(
 9779        &mut self,
 9780        _: &SplitSelectionIntoLines,
 9781        window: &mut Window,
 9782        cx: &mut Context<Self>,
 9783    ) {
 9784        let selections = self
 9785            .selections
 9786            .all::<Point>(cx)
 9787            .into_iter()
 9788            .map(|selection| selection.start..selection.end)
 9789            .collect::<Vec<_>>();
 9790        self.unfold_ranges(&selections, true, true, cx);
 9791
 9792        let mut new_selection_ranges = Vec::new();
 9793        {
 9794            let buffer = self.buffer.read(cx).read(cx);
 9795            for selection in selections {
 9796                for row in selection.start.row..selection.end.row {
 9797                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9798                    new_selection_ranges.push(cursor..cursor);
 9799                }
 9800
 9801                let is_multiline_selection = selection.start.row != selection.end.row;
 9802                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9803                // so this action feels more ergonomic when paired with other selection operations
 9804                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9805                if !should_skip_last {
 9806                    new_selection_ranges.push(selection.end..selection.end);
 9807                }
 9808            }
 9809        }
 9810        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9811            s.select_ranges(new_selection_ranges);
 9812        });
 9813    }
 9814
 9815    pub fn add_selection_above(
 9816        &mut self,
 9817        _: &AddSelectionAbove,
 9818        window: &mut Window,
 9819        cx: &mut Context<Self>,
 9820    ) {
 9821        self.add_selection(true, window, cx);
 9822    }
 9823
 9824    pub fn add_selection_below(
 9825        &mut self,
 9826        _: &AddSelectionBelow,
 9827        window: &mut Window,
 9828        cx: &mut Context<Self>,
 9829    ) {
 9830        self.add_selection(false, window, cx);
 9831    }
 9832
 9833    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9834        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9835        let mut selections = self.selections.all::<Point>(cx);
 9836        let text_layout_details = self.text_layout_details(window);
 9837        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9838            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9839            let range = oldest_selection.display_range(&display_map).sorted();
 9840
 9841            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9842            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9843            let positions = start_x.min(end_x)..start_x.max(end_x);
 9844
 9845            selections.clear();
 9846            let mut stack = Vec::new();
 9847            for row in range.start.row().0..=range.end.row().0 {
 9848                if let Some(selection) = self.selections.build_columnar_selection(
 9849                    &display_map,
 9850                    DisplayRow(row),
 9851                    &positions,
 9852                    oldest_selection.reversed,
 9853                    &text_layout_details,
 9854                ) {
 9855                    stack.push(selection.id);
 9856                    selections.push(selection);
 9857                }
 9858            }
 9859
 9860            if above {
 9861                stack.reverse();
 9862            }
 9863
 9864            AddSelectionsState { above, stack }
 9865        });
 9866
 9867        let last_added_selection = *state.stack.last().unwrap();
 9868        let mut new_selections = Vec::new();
 9869        if above == state.above {
 9870            let end_row = if above {
 9871                DisplayRow(0)
 9872            } else {
 9873                display_map.max_point().row()
 9874            };
 9875
 9876            'outer: for selection in selections {
 9877                if selection.id == last_added_selection {
 9878                    let range = selection.display_range(&display_map).sorted();
 9879                    debug_assert_eq!(range.start.row(), range.end.row());
 9880                    let mut row = range.start.row();
 9881                    let positions =
 9882                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9883                            px(start)..px(end)
 9884                        } else {
 9885                            let start_x =
 9886                                display_map.x_for_display_point(range.start, &text_layout_details);
 9887                            let end_x =
 9888                                display_map.x_for_display_point(range.end, &text_layout_details);
 9889                            start_x.min(end_x)..start_x.max(end_x)
 9890                        };
 9891
 9892                    while row != end_row {
 9893                        if above {
 9894                            row.0 -= 1;
 9895                        } else {
 9896                            row.0 += 1;
 9897                        }
 9898
 9899                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9900                            &display_map,
 9901                            row,
 9902                            &positions,
 9903                            selection.reversed,
 9904                            &text_layout_details,
 9905                        ) {
 9906                            state.stack.push(new_selection.id);
 9907                            if above {
 9908                                new_selections.push(new_selection);
 9909                                new_selections.push(selection);
 9910                            } else {
 9911                                new_selections.push(selection);
 9912                                new_selections.push(new_selection);
 9913                            }
 9914
 9915                            continue 'outer;
 9916                        }
 9917                    }
 9918                }
 9919
 9920                new_selections.push(selection);
 9921            }
 9922        } else {
 9923            new_selections = selections;
 9924            new_selections.retain(|s| s.id != last_added_selection);
 9925            state.stack.pop();
 9926        }
 9927
 9928        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9929            s.select(new_selections);
 9930        });
 9931        if state.stack.len() > 1 {
 9932            self.add_selections_state = Some(state);
 9933        }
 9934    }
 9935
 9936    pub fn select_next_match_internal(
 9937        &mut self,
 9938        display_map: &DisplaySnapshot,
 9939        replace_newest: bool,
 9940        autoscroll: Option<Autoscroll>,
 9941        window: &mut Window,
 9942        cx: &mut Context<Self>,
 9943    ) -> Result<()> {
 9944        fn select_next_match_ranges(
 9945            this: &mut Editor,
 9946            range: Range<usize>,
 9947            replace_newest: bool,
 9948            auto_scroll: Option<Autoscroll>,
 9949            window: &mut Window,
 9950            cx: &mut Context<Editor>,
 9951        ) {
 9952            this.unfold_ranges(&[range.clone()], false, true, cx);
 9953            this.change_selections(auto_scroll, window, cx, |s| {
 9954                if replace_newest {
 9955                    s.delete(s.newest_anchor().id);
 9956                }
 9957                s.insert_range(range.clone());
 9958            });
 9959        }
 9960
 9961        let buffer = &display_map.buffer_snapshot;
 9962        let mut selections = self.selections.all::<usize>(cx);
 9963        if let Some(mut select_next_state) = self.select_next_state.take() {
 9964            let query = &select_next_state.query;
 9965            if !select_next_state.done {
 9966                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9967                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9968                let mut next_selected_range = None;
 9969
 9970                let bytes_after_last_selection =
 9971                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9972                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9973                let query_matches = query
 9974                    .stream_find_iter(bytes_after_last_selection)
 9975                    .map(|result| (last_selection.end, result))
 9976                    .chain(
 9977                        query
 9978                            .stream_find_iter(bytes_before_first_selection)
 9979                            .map(|result| (0, result)),
 9980                    );
 9981
 9982                for (start_offset, query_match) in query_matches {
 9983                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9984                    let offset_range =
 9985                        start_offset + query_match.start()..start_offset + query_match.end();
 9986                    let display_range = offset_range.start.to_display_point(display_map)
 9987                        ..offset_range.end.to_display_point(display_map);
 9988
 9989                    if !select_next_state.wordwise
 9990                        || (!movement::is_inside_word(display_map, display_range.start)
 9991                            && !movement::is_inside_word(display_map, display_range.end))
 9992                    {
 9993                        // TODO: This is n^2, because we might check all the selections
 9994                        if !selections
 9995                            .iter()
 9996                            .any(|selection| selection.range().overlaps(&offset_range))
 9997                        {
 9998                            next_selected_range = Some(offset_range);
 9999                            break;
10000                        }
10001                    }
10002                }
10003
10004                if let Some(next_selected_range) = next_selected_range {
10005                    select_next_match_ranges(
10006                        self,
10007                        next_selected_range,
10008                        replace_newest,
10009                        autoscroll,
10010                        window,
10011                        cx,
10012                    );
10013                } else {
10014                    select_next_state.done = true;
10015                }
10016            }
10017
10018            self.select_next_state = Some(select_next_state);
10019        } else {
10020            let mut only_carets = true;
10021            let mut same_text_selected = true;
10022            let mut selected_text = None;
10023
10024            let mut selections_iter = selections.iter().peekable();
10025            while let Some(selection) = selections_iter.next() {
10026                if selection.start != selection.end {
10027                    only_carets = false;
10028                }
10029
10030                if same_text_selected {
10031                    if selected_text.is_none() {
10032                        selected_text =
10033                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10034                    }
10035
10036                    if let Some(next_selection) = selections_iter.peek() {
10037                        if next_selection.range().len() == selection.range().len() {
10038                            let next_selected_text = buffer
10039                                .text_for_range(next_selection.range())
10040                                .collect::<String>();
10041                            if Some(next_selected_text) != selected_text {
10042                                same_text_selected = false;
10043                                selected_text = None;
10044                            }
10045                        } else {
10046                            same_text_selected = false;
10047                            selected_text = None;
10048                        }
10049                    }
10050                }
10051            }
10052
10053            if only_carets {
10054                for selection in &mut selections {
10055                    let word_range = movement::surrounding_word(
10056                        display_map,
10057                        selection.start.to_display_point(display_map),
10058                    );
10059                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10060                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10061                    selection.goal = SelectionGoal::None;
10062                    selection.reversed = false;
10063                    select_next_match_ranges(
10064                        self,
10065                        selection.start..selection.end,
10066                        replace_newest,
10067                        autoscroll,
10068                        window,
10069                        cx,
10070                    );
10071                }
10072
10073                if selections.len() == 1 {
10074                    let selection = selections
10075                        .last()
10076                        .expect("ensured that there's only one selection");
10077                    let query = buffer
10078                        .text_for_range(selection.start..selection.end)
10079                        .collect::<String>();
10080                    let is_empty = query.is_empty();
10081                    let select_state = SelectNextState {
10082                        query: AhoCorasick::new(&[query])?,
10083                        wordwise: true,
10084                        done: is_empty,
10085                    };
10086                    self.select_next_state = Some(select_state);
10087                } else {
10088                    self.select_next_state = None;
10089                }
10090            } else if let Some(selected_text) = selected_text {
10091                self.select_next_state = Some(SelectNextState {
10092                    query: AhoCorasick::new(&[selected_text])?,
10093                    wordwise: false,
10094                    done: false,
10095                });
10096                self.select_next_match_internal(
10097                    display_map,
10098                    replace_newest,
10099                    autoscroll,
10100                    window,
10101                    cx,
10102                )?;
10103            }
10104        }
10105        Ok(())
10106    }
10107
10108    pub fn select_all_matches(
10109        &mut self,
10110        _action: &SelectAllMatches,
10111        window: &mut Window,
10112        cx: &mut Context<Self>,
10113    ) -> Result<()> {
10114        self.push_to_selection_history();
10115        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10116
10117        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10118        let Some(select_next_state) = self.select_next_state.as_mut() else {
10119            return Ok(());
10120        };
10121        if select_next_state.done {
10122            return Ok(());
10123        }
10124
10125        let mut new_selections = self.selections.all::<usize>(cx);
10126
10127        let buffer = &display_map.buffer_snapshot;
10128        let query_matches = select_next_state
10129            .query
10130            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10131
10132        for query_match in query_matches {
10133            let query_match = query_match.unwrap(); // can only fail due to I/O
10134            let offset_range = query_match.start()..query_match.end();
10135            let display_range = offset_range.start.to_display_point(&display_map)
10136                ..offset_range.end.to_display_point(&display_map);
10137
10138            if !select_next_state.wordwise
10139                || (!movement::is_inside_word(&display_map, display_range.start)
10140                    && !movement::is_inside_word(&display_map, display_range.end))
10141            {
10142                self.selections.change_with(cx, |selections| {
10143                    new_selections.push(Selection {
10144                        id: selections.new_selection_id(),
10145                        start: offset_range.start,
10146                        end: offset_range.end,
10147                        reversed: false,
10148                        goal: SelectionGoal::None,
10149                    });
10150                });
10151            }
10152        }
10153
10154        new_selections.sort_by_key(|selection| selection.start);
10155        let mut ix = 0;
10156        while ix + 1 < new_selections.len() {
10157            let current_selection = &new_selections[ix];
10158            let next_selection = &new_selections[ix + 1];
10159            if current_selection.range().overlaps(&next_selection.range()) {
10160                if current_selection.id < next_selection.id {
10161                    new_selections.remove(ix + 1);
10162                } else {
10163                    new_selections.remove(ix);
10164                }
10165            } else {
10166                ix += 1;
10167            }
10168        }
10169
10170        let reversed = self.selections.oldest::<usize>(cx).reversed;
10171
10172        for selection in new_selections.iter_mut() {
10173            selection.reversed = reversed;
10174        }
10175
10176        select_next_state.done = true;
10177        self.unfold_ranges(
10178            &new_selections
10179                .iter()
10180                .map(|selection| selection.range())
10181                .collect::<Vec<_>>(),
10182            false,
10183            false,
10184            cx,
10185        );
10186        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10187            selections.select(new_selections)
10188        });
10189
10190        Ok(())
10191    }
10192
10193    pub fn select_next(
10194        &mut self,
10195        action: &SelectNext,
10196        window: &mut Window,
10197        cx: &mut Context<Self>,
10198    ) -> Result<()> {
10199        self.push_to_selection_history();
10200        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10201        self.select_next_match_internal(
10202            &display_map,
10203            action.replace_newest,
10204            Some(Autoscroll::newest()),
10205            window,
10206            cx,
10207        )?;
10208        Ok(())
10209    }
10210
10211    pub fn select_previous(
10212        &mut self,
10213        action: &SelectPrevious,
10214        window: &mut Window,
10215        cx: &mut Context<Self>,
10216    ) -> Result<()> {
10217        self.push_to_selection_history();
10218        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10219        let buffer = &display_map.buffer_snapshot;
10220        let mut selections = self.selections.all::<usize>(cx);
10221        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10222            let query = &select_prev_state.query;
10223            if !select_prev_state.done {
10224                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10225                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10226                let mut next_selected_range = None;
10227                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10228                let bytes_before_last_selection =
10229                    buffer.reversed_bytes_in_range(0..last_selection.start);
10230                let bytes_after_first_selection =
10231                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10232                let query_matches = query
10233                    .stream_find_iter(bytes_before_last_selection)
10234                    .map(|result| (last_selection.start, result))
10235                    .chain(
10236                        query
10237                            .stream_find_iter(bytes_after_first_selection)
10238                            .map(|result| (buffer.len(), result)),
10239                    );
10240                for (end_offset, query_match) in query_matches {
10241                    let query_match = query_match.unwrap(); // can only fail due to I/O
10242                    let offset_range =
10243                        end_offset - query_match.end()..end_offset - query_match.start();
10244                    let display_range = offset_range.start.to_display_point(&display_map)
10245                        ..offset_range.end.to_display_point(&display_map);
10246
10247                    if !select_prev_state.wordwise
10248                        || (!movement::is_inside_word(&display_map, display_range.start)
10249                            && !movement::is_inside_word(&display_map, display_range.end))
10250                    {
10251                        next_selected_range = Some(offset_range);
10252                        break;
10253                    }
10254                }
10255
10256                if let Some(next_selected_range) = next_selected_range {
10257                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10258                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10259                        if action.replace_newest {
10260                            s.delete(s.newest_anchor().id);
10261                        }
10262                        s.insert_range(next_selected_range);
10263                    });
10264                } else {
10265                    select_prev_state.done = true;
10266                }
10267            }
10268
10269            self.select_prev_state = Some(select_prev_state);
10270        } else {
10271            let mut only_carets = true;
10272            let mut same_text_selected = true;
10273            let mut selected_text = None;
10274
10275            let mut selections_iter = selections.iter().peekable();
10276            while let Some(selection) = selections_iter.next() {
10277                if selection.start != selection.end {
10278                    only_carets = false;
10279                }
10280
10281                if same_text_selected {
10282                    if selected_text.is_none() {
10283                        selected_text =
10284                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10285                    }
10286
10287                    if let Some(next_selection) = selections_iter.peek() {
10288                        if next_selection.range().len() == selection.range().len() {
10289                            let next_selected_text = buffer
10290                                .text_for_range(next_selection.range())
10291                                .collect::<String>();
10292                            if Some(next_selected_text) != selected_text {
10293                                same_text_selected = false;
10294                                selected_text = None;
10295                            }
10296                        } else {
10297                            same_text_selected = false;
10298                            selected_text = None;
10299                        }
10300                    }
10301                }
10302            }
10303
10304            if only_carets {
10305                for selection in &mut selections {
10306                    let word_range = movement::surrounding_word(
10307                        &display_map,
10308                        selection.start.to_display_point(&display_map),
10309                    );
10310                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10311                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10312                    selection.goal = SelectionGoal::None;
10313                    selection.reversed = false;
10314                }
10315                if selections.len() == 1 {
10316                    let selection = selections
10317                        .last()
10318                        .expect("ensured that there's only one selection");
10319                    let query = buffer
10320                        .text_for_range(selection.start..selection.end)
10321                        .collect::<String>();
10322                    let is_empty = query.is_empty();
10323                    let select_state = SelectNextState {
10324                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10325                        wordwise: true,
10326                        done: is_empty,
10327                    };
10328                    self.select_prev_state = Some(select_state);
10329                } else {
10330                    self.select_prev_state = None;
10331                }
10332
10333                self.unfold_ranges(
10334                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10335                    false,
10336                    true,
10337                    cx,
10338                );
10339                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10340                    s.select(selections);
10341                });
10342            } else if let Some(selected_text) = selected_text {
10343                self.select_prev_state = Some(SelectNextState {
10344                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10345                    wordwise: false,
10346                    done: false,
10347                });
10348                self.select_previous(action, window, cx)?;
10349            }
10350        }
10351        Ok(())
10352    }
10353
10354    pub fn toggle_comments(
10355        &mut self,
10356        action: &ToggleComments,
10357        window: &mut Window,
10358        cx: &mut Context<Self>,
10359    ) {
10360        if self.read_only(cx) {
10361            return;
10362        }
10363        let text_layout_details = &self.text_layout_details(window);
10364        self.transact(window, cx, |this, window, cx| {
10365            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10366            let mut edits = Vec::new();
10367            let mut selection_edit_ranges = Vec::new();
10368            let mut last_toggled_row = None;
10369            let snapshot = this.buffer.read(cx).read(cx);
10370            let empty_str: Arc<str> = Arc::default();
10371            let mut suffixes_inserted = Vec::new();
10372            let ignore_indent = action.ignore_indent;
10373
10374            fn comment_prefix_range(
10375                snapshot: &MultiBufferSnapshot,
10376                row: MultiBufferRow,
10377                comment_prefix: &str,
10378                comment_prefix_whitespace: &str,
10379                ignore_indent: bool,
10380            ) -> Range<Point> {
10381                let indent_size = if ignore_indent {
10382                    0
10383                } else {
10384                    snapshot.indent_size_for_line(row).len
10385                };
10386
10387                let start = Point::new(row.0, indent_size);
10388
10389                let mut line_bytes = snapshot
10390                    .bytes_in_range(start..snapshot.max_point())
10391                    .flatten()
10392                    .copied();
10393
10394                // If this line currently begins with the line comment prefix, then record
10395                // the range containing the prefix.
10396                if line_bytes
10397                    .by_ref()
10398                    .take(comment_prefix.len())
10399                    .eq(comment_prefix.bytes())
10400                {
10401                    // Include any whitespace that matches the comment prefix.
10402                    let matching_whitespace_len = line_bytes
10403                        .zip(comment_prefix_whitespace.bytes())
10404                        .take_while(|(a, b)| a == b)
10405                        .count() as u32;
10406                    let end = Point::new(
10407                        start.row,
10408                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10409                    );
10410                    start..end
10411                } else {
10412                    start..start
10413                }
10414            }
10415
10416            fn comment_suffix_range(
10417                snapshot: &MultiBufferSnapshot,
10418                row: MultiBufferRow,
10419                comment_suffix: &str,
10420                comment_suffix_has_leading_space: bool,
10421            ) -> Range<Point> {
10422                let end = Point::new(row.0, snapshot.line_len(row));
10423                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10424
10425                let mut line_end_bytes = snapshot
10426                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10427                    .flatten()
10428                    .copied();
10429
10430                let leading_space_len = if suffix_start_column > 0
10431                    && line_end_bytes.next() == Some(b' ')
10432                    && comment_suffix_has_leading_space
10433                {
10434                    1
10435                } else {
10436                    0
10437                };
10438
10439                // If this line currently begins with the line comment prefix, then record
10440                // the range containing the prefix.
10441                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10442                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10443                    start..end
10444                } else {
10445                    end..end
10446                }
10447            }
10448
10449            // TODO: Handle selections that cross excerpts
10450            for selection in &mut selections {
10451                let start_column = snapshot
10452                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10453                    .len;
10454                let language = if let Some(language) =
10455                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10456                {
10457                    language
10458                } else {
10459                    continue;
10460                };
10461
10462                selection_edit_ranges.clear();
10463
10464                // If multiple selections contain a given row, avoid processing that
10465                // row more than once.
10466                let mut start_row = MultiBufferRow(selection.start.row);
10467                if last_toggled_row == Some(start_row) {
10468                    start_row = start_row.next_row();
10469                }
10470                let end_row =
10471                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10472                        MultiBufferRow(selection.end.row - 1)
10473                    } else {
10474                        MultiBufferRow(selection.end.row)
10475                    };
10476                last_toggled_row = Some(end_row);
10477
10478                if start_row > end_row {
10479                    continue;
10480                }
10481
10482                // If the language has line comments, toggle those.
10483                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10484
10485                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10486                if ignore_indent {
10487                    full_comment_prefixes = full_comment_prefixes
10488                        .into_iter()
10489                        .map(|s| Arc::from(s.trim_end()))
10490                        .collect();
10491                }
10492
10493                if !full_comment_prefixes.is_empty() {
10494                    let first_prefix = full_comment_prefixes
10495                        .first()
10496                        .expect("prefixes is non-empty");
10497                    let prefix_trimmed_lengths = full_comment_prefixes
10498                        .iter()
10499                        .map(|p| p.trim_end_matches(' ').len())
10500                        .collect::<SmallVec<[usize; 4]>>();
10501
10502                    let mut all_selection_lines_are_comments = true;
10503
10504                    for row in start_row.0..=end_row.0 {
10505                        let row = MultiBufferRow(row);
10506                        if start_row < end_row && snapshot.is_line_blank(row) {
10507                            continue;
10508                        }
10509
10510                        let prefix_range = full_comment_prefixes
10511                            .iter()
10512                            .zip(prefix_trimmed_lengths.iter().copied())
10513                            .map(|(prefix, trimmed_prefix_len)| {
10514                                comment_prefix_range(
10515                                    snapshot.deref(),
10516                                    row,
10517                                    &prefix[..trimmed_prefix_len],
10518                                    &prefix[trimmed_prefix_len..],
10519                                    ignore_indent,
10520                                )
10521                            })
10522                            .max_by_key(|range| range.end.column - range.start.column)
10523                            .expect("prefixes is non-empty");
10524
10525                        if prefix_range.is_empty() {
10526                            all_selection_lines_are_comments = false;
10527                        }
10528
10529                        selection_edit_ranges.push(prefix_range);
10530                    }
10531
10532                    if all_selection_lines_are_comments {
10533                        edits.extend(
10534                            selection_edit_ranges
10535                                .iter()
10536                                .cloned()
10537                                .map(|range| (range, empty_str.clone())),
10538                        );
10539                    } else {
10540                        let min_column = selection_edit_ranges
10541                            .iter()
10542                            .map(|range| range.start.column)
10543                            .min()
10544                            .unwrap_or(0);
10545                        edits.extend(selection_edit_ranges.iter().map(|range| {
10546                            let position = Point::new(range.start.row, min_column);
10547                            (position..position, first_prefix.clone())
10548                        }));
10549                    }
10550                } else if let Some((full_comment_prefix, comment_suffix)) =
10551                    language.block_comment_delimiters()
10552                {
10553                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10554                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10555                    let prefix_range = comment_prefix_range(
10556                        snapshot.deref(),
10557                        start_row,
10558                        comment_prefix,
10559                        comment_prefix_whitespace,
10560                        ignore_indent,
10561                    );
10562                    let suffix_range = comment_suffix_range(
10563                        snapshot.deref(),
10564                        end_row,
10565                        comment_suffix.trim_start_matches(' '),
10566                        comment_suffix.starts_with(' '),
10567                    );
10568
10569                    if prefix_range.is_empty() || suffix_range.is_empty() {
10570                        edits.push((
10571                            prefix_range.start..prefix_range.start,
10572                            full_comment_prefix.clone(),
10573                        ));
10574                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10575                        suffixes_inserted.push((end_row, comment_suffix.len()));
10576                    } else {
10577                        edits.push((prefix_range, empty_str.clone()));
10578                        edits.push((suffix_range, empty_str.clone()));
10579                    }
10580                } else {
10581                    continue;
10582                }
10583            }
10584
10585            drop(snapshot);
10586            this.buffer.update(cx, |buffer, cx| {
10587                buffer.edit(edits, None, cx);
10588            });
10589
10590            // Adjust selections so that they end before any comment suffixes that
10591            // were inserted.
10592            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10593            let mut selections = this.selections.all::<Point>(cx);
10594            let snapshot = this.buffer.read(cx).read(cx);
10595            for selection in &mut selections {
10596                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10597                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10598                        Ordering::Less => {
10599                            suffixes_inserted.next();
10600                            continue;
10601                        }
10602                        Ordering::Greater => break,
10603                        Ordering::Equal => {
10604                            if selection.end.column == snapshot.line_len(row) {
10605                                if selection.is_empty() {
10606                                    selection.start.column -= suffix_len as u32;
10607                                }
10608                                selection.end.column -= suffix_len as u32;
10609                            }
10610                            break;
10611                        }
10612                    }
10613                }
10614            }
10615
10616            drop(snapshot);
10617            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10618                s.select(selections)
10619            });
10620
10621            let selections = this.selections.all::<Point>(cx);
10622            let selections_on_single_row = selections.windows(2).all(|selections| {
10623                selections[0].start.row == selections[1].start.row
10624                    && selections[0].end.row == selections[1].end.row
10625                    && selections[0].start.row == selections[0].end.row
10626            });
10627            let selections_selecting = selections
10628                .iter()
10629                .any(|selection| selection.start != selection.end);
10630            let advance_downwards = action.advance_downwards
10631                && selections_on_single_row
10632                && !selections_selecting
10633                && !matches!(this.mode, EditorMode::SingleLine { .. });
10634
10635            if advance_downwards {
10636                let snapshot = this.buffer.read(cx).snapshot(cx);
10637
10638                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10639                    s.move_cursors_with(|display_snapshot, display_point, _| {
10640                        let mut point = display_point.to_point(display_snapshot);
10641                        point.row += 1;
10642                        point = snapshot.clip_point(point, Bias::Left);
10643                        let display_point = point.to_display_point(display_snapshot);
10644                        let goal = SelectionGoal::HorizontalPosition(
10645                            display_snapshot
10646                                .x_for_display_point(display_point, text_layout_details)
10647                                .into(),
10648                        );
10649                        (display_point, goal)
10650                    })
10651                });
10652            }
10653        });
10654    }
10655
10656    pub fn select_enclosing_symbol(
10657        &mut self,
10658        _: &SelectEnclosingSymbol,
10659        window: &mut Window,
10660        cx: &mut Context<Self>,
10661    ) {
10662        let buffer = self.buffer.read(cx).snapshot(cx);
10663        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10664
10665        fn update_selection(
10666            selection: &Selection<usize>,
10667            buffer_snap: &MultiBufferSnapshot,
10668        ) -> Option<Selection<usize>> {
10669            let cursor = selection.head();
10670            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10671            for symbol in symbols.iter().rev() {
10672                let start = symbol.range.start.to_offset(buffer_snap);
10673                let end = symbol.range.end.to_offset(buffer_snap);
10674                let new_range = start..end;
10675                if start < selection.start || end > selection.end {
10676                    return Some(Selection {
10677                        id: selection.id,
10678                        start: new_range.start,
10679                        end: new_range.end,
10680                        goal: SelectionGoal::None,
10681                        reversed: selection.reversed,
10682                    });
10683                }
10684            }
10685            None
10686        }
10687
10688        let mut selected_larger_symbol = false;
10689        let new_selections = old_selections
10690            .iter()
10691            .map(|selection| match update_selection(selection, &buffer) {
10692                Some(new_selection) => {
10693                    if new_selection.range() != selection.range() {
10694                        selected_larger_symbol = true;
10695                    }
10696                    new_selection
10697                }
10698                None => selection.clone(),
10699            })
10700            .collect::<Vec<_>>();
10701
10702        if selected_larger_symbol {
10703            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10704                s.select(new_selections);
10705            });
10706        }
10707    }
10708
10709    pub fn select_larger_syntax_node(
10710        &mut self,
10711        _: &SelectLargerSyntaxNode,
10712        window: &mut Window,
10713        cx: &mut Context<Self>,
10714    ) {
10715        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10716        let buffer = self.buffer.read(cx).snapshot(cx);
10717        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10718
10719        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10720        let mut selected_larger_node = false;
10721        let new_selections = old_selections
10722            .iter()
10723            .map(|selection| {
10724                let old_range = selection.start..selection.end;
10725                let mut new_range = old_range.clone();
10726                let mut new_node = None;
10727                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10728                {
10729                    new_node = Some(node);
10730                    new_range = containing_range;
10731                    if !display_map.intersects_fold(new_range.start)
10732                        && !display_map.intersects_fold(new_range.end)
10733                    {
10734                        break;
10735                    }
10736                }
10737
10738                if let Some(node) = new_node {
10739                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10740                    // nodes. Parent and grandparent are also logged because this operation will not
10741                    // visit nodes that have the same range as their parent.
10742                    log::info!("Node: {node:?}");
10743                    let parent = node.parent();
10744                    log::info!("Parent: {parent:?}");
10745                    let grandparent = parent.and_then(|x| x.parent());
10746                    log::info!("Grandparent: {grandparent:?}");
10747                }
10748
10749                selected_larger_node |= new_range != old_range;
10750                Selection {
10751                    id: selection.id,
10752                    start: new_range.start,
10753                    end: new_range.end,
10754                    goal: SelectionGoal::None,
10755                    reversed: selection.reversed,
10756                }
10757            })
10758            .collect::<Vec<_>>();
10759
10760        if selected_larger_node {
10761            stack.push(old_selections);
10762            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10763                s.select(new_selections);
10764            });
10765        }
10766        self.select_larger_syntax_node_stack = stack;
10767    }
10768
10769    pub fn select_smaller_syntax_node(
10770        &mut self,
10771        _: &SelectSmallerSyntaxNode,
10772        window: &mut Window,
10773        cx: &mut Context<Self>,
10774    ) {
10775        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10776        if let Some(selections) = stack.pop() {
10777            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10778                s.select(selections.to_vec());
10779            });
10780        }
10781        self.select_larger_syntax_node_stack = stack;
10782    }
10783
10784    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10785        if !EditorSettings::get_global(cx).gutter.runnables {
10786            self.clear_tasks();
10787            return Task::ready(());
10788        }
10789        let project = self.project.as_ref().map(Entity::downgrade);
10790        cx.spawn_in(window, |this, mut cx| async move {
10791            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10792            let Some(project) = project.and_then(|p| p.upgrade()) else {
10793                return;
10794            };
10795            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10796                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10797            }) else {
10798                return;
10799            };
10800
10801            let hide_runnables = project
10802                .update(&mut cx, |project, cx| {
10803                    // Do not display any test indicators in non-dev server remote projects.
10804                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10805                })
10806                .unwrap_or(true);
10807            if hide_runnables {
10808                return;
10809            }
10810            let new_rows =
10811                cx.background_spawn({
10812                    let snapshot = display_snapshot.clone();
10813                    async move {
10814                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10815                    }
10816                })
10817                    .await;
10818
10819            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10820            this.update(&mut cx, |this, _| {
10821                this.clear_tasks();
10822                for (key, value) in rows {
10823                    this.insert_tasks(key, value);
10824                }
10825            })
10826            .ok();
10827        })
10828    }
10829    fn fetch_runnable_ranges(
10830        snapshot: &DisplaySnapshot,
10831        range: Range<Anchor>,
10832    ) -> Vec<language::RunnableRange> {
10833        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10834    }
10835
10836    fn runnable_rows(
10837        project: Entity<Project>,
10838        snapshot: DisplaySnapshot,
10839        runnable_ranges: Vec<RunnableRange>,
10840        mut cx: AsyncWindowContext,
10841    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10842        runnable_ranges
10843            .into_iter()
10844            .filter_map(|mut runnable| {
10845                let tasks = cx
10846                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10847                    .ok()?;
10848                if tasks.is_empty() {
10849                    return None;
10850                }
10851
10852                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10853
10854                let row = snapshot
10855                    .buffer_snapshot
10856                    .buffer_line_for_row(MultiBufferRow(point.row))?
10857                    .1
10858                    .start
10859                    .row;
10860
10861                let context_range =
10862                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10863                Some((
10864                    (runnable.buffer_id, row),
10865                    RunnableTasks {
10866                        templates: tasks,
10867                        offset: snapshot
10868                            .buffer_snapshot
10869                            .anchor_before(runnable.run_range.start),
10870                        context_range,
10871                        column: point.column,
10872                        extra_variables: runnable.extra_captures,
10873                    },
10874                ))
10875            })
10876            .collect()
10877    }
10878
10879    fn templates_with_tags(
10880        project: &Entity<Project>,
10881        runnable: &mut Runnable,
10882        cx: &mut App,
10883    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10884        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10885            let (worktree_id, file) = project
10886                .buffer_for_id(runnable.buffer, cx)
10887                .and_then(|buffer| buffer.read(cx).file())
10888                .map(|file| (file.worktree_id(cx), file.clone()))
10889                .unzip();
10890
10891            (
10892                project.task_store().read(cx).task_inventory().cloned(),
10893                worktree_id,
10894                file,
10895            )
10896        });
10897
10898        let tags = mem::take(&mut runnable.tags);
10899        let mut tags: Vec<_> = tags
10900            .into_iter()
10901            .flat_map(|tag| {
10902                let tag = tag.0.clone();
10903                inventory
10904                    .as_ref()
10905                    .into_iter()
10906                    .flat_map(|inventory| {
10907                        inventory.read(cx).list_tasks(
10908                            file.clone(),
10909                            Some(runnable.language.clone()),
10910                            worktree_id,
10911                            cx,
10912                        )
10913                    })
10914                    .filter(move |(_, template)| {
10915                        template.tags.iter().any(|source_tag| source_tag == &tag)
10916                    })
10917            })
10918            .sorted_by_key(|(kind, _)| kind.to_owned())
10919            .collect();
10920        if let Some((leading_tag_source, _)) = tags.first() {
10921            // Strongest source wins; if we have worktree tag binding, prefer that to
10922            // global and language bindings;
10923            // if we have a global binding, prefer that to language binding.
10924            let first_mismatch = tags
10925                .iter()
10926                .position(|(tag_source, _)| tag_source != leading_tag_source);
10927            if let Some(index) = first_mismatch {
10928                tags.truncate(index);
10929            }
10930        }
10931
10932        tags
10933    }
10934
10935    pub fn move_to_enclosing_bracket(
10936        &mut self,
10937        _: &MoveToEnclosingBracket,
10938        window: &mut Window,
10939        cx: &mut Context<Self>,
10940    ) {
10941        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10942            s.move_offsets_with(|snapshot, selection| {
10943                let Some(enclosing_bracket_ranges) =
10944                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10945                else {
10946                    return;
10947                };
10948
10949                let mut best_length = usize::MAX;
10950                let mut best_inside = false;
10951                let mut best_in_bracket_range = false;
10952                let mut best_destination = None;
10953                for (open, close) in enclosing_bracket_ranges {
10954                    let close = close.to_inclusive();
10955                    let length = close.end() - open.start;
10956                    let inside = selection.start >= open.end && selection.end <= *close.start();
10957                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10958                        || close.contains(&selection.head());
10959
10960                    // If best is next to a bracket and current isn't, skip
10961                    if !in_bracket_range && best_in_bracket_range {
10962                        continue;
10963                    }
10964
10965                    // Prefer smaller lengths unless best is inside and current isn't
10966                    if length > best_length && (best_inside || !inside) {
10967                        continue;
10968                    }
10969
10970                    best_length = length;
10971                    best_inside = inside;
10972                    best_in_bracket_range = in_bracket_range;
10973                    best_destination = Some(
10974                        if close.contains(&selection.start) && close.contains(&selection.end) {
10975                            if inside {
10976                                open.end
10977                            } else {
10978                                open.start
10979                            }
10980                        } else if inside {
10981                            *close.start()
10982                        } else {
10983                            *close.end()
10984                        },
10985                    );
10986                }
10987
10988                if let Some(destination) = best_destination {
10989                    selection.collapse_to(destination, SelectionGoal::None);
10990                }
10991            })
10992        });
10993    }
10994
10995    pub fn undo_selection(
10996        &mut self,
10997        _: &UndoSelection,
10998        window: &mut Window,
10999        cx: &mut Context<Self>,
11000    ) {
11001        self.end_selection(window, cx);
11002        self.selection_history.mode = SelectionHistoryMode::Undoing;
11003        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11004            self.change_selections(None, window, cx, |s| {
11005                s.select_anchors(entry.selections.to_vec())
11006            });
11007            self.select_next_state = entry.select_next_state;
11008            self.select_prev_state = entry.select_prev_state;
11009            self.add_selections_state = entry.add_selections_state;
11010            self.request_autoscroll(Autoscroll::newest(), cx);
11011        }
11012        self.selection_history.mode = SelectionHistoryMode::Normal;
11013    }
11014
11015    pub fn redo_selection(
11016        &mut self,
11017        _: &RedoSelection,
11018        window: &mut Window,
11019        cx: &mut Context<Self>,
11020    ) {
11021        self.end_selection(window, cx);
11022        self.selection_history.mode = SelectionHistoryMode::Redoing;
11023        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11024            self.change_selections(None, window, cx, |s| {
11025                s.select_anchors(entry.selections.to_vec())
11026            });
11027            self.select_next_state = entry.select_next_state;
11028            self.select_prev_state = entry.select_prev_state;
11029            self.add_selections_state = entry.add_selections_state;
11030            self.request_autoscroll(Autoscroll::newest(), cx);
11031        }
11032        self.selection_history.mode = SelectionHistoryMode::Normal;
11033    }
11034
11035    pub fn expand_excerpts(
11036        &mut self,
11037        action: &ExpandExcerpts,
11038        _: &mut Window,
11039        cx: &mut Context<Self>,
11040    ) {
11041        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11042    }
11043
11044    pub fn expand_excerpts_down(
11045        &mut self,
11046        action: &ExpandExcerptsDown,
11047        _: &mut Window,
11048        cx: &mut Context<Self>,
11049    ) {
11050        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11051    }
11052
11053    pub fn expand_excerpts_up(
11054        &mut self,
11055        action: &ExpandExcerptsUp,
11056        _: &mut Window,
11057        cx: &mut Context<Self>,
11058    ) {
11059        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11060    }
11061
11062    pub fn expand_excerpts_for_direction(
11063        &mut self,
11064        lines: u32,
11065        direction: ExpandExcerptDirection,
11066
11067        cx: &mut Context<Self>,
11068    ) {
11069        let selections = self.selections.disjoint_anchors();
11070
11071        let lines = if lines == 0 {
11072            EditorSettings::get_global(cx).expand_excerpt_lines
11073        } else {
11074            lines
11075        };
11076
11077        self.buffer.update(cx, |buffer, cx| {
11078            let snapshot = buffer.snapshot(cx);
11079            let mut excerpt_ids = selections
11080                .iter()
11081                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11082                .collect::<Vec<_>>();
11083            excerpt_ids.sort();
11084            excerpt_ids.dedup();
11085            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11086        })
11087    }
11088
11089    pub fn expand_excerpt(
11090        &mut self,
11091        excerpt: ExcerptId,
11092        direction: ExpandExcerptDirection,
11093        cx: &mut Context<Self>,
11094    ) {
11095        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11096        self.buffer.update(cx, |buffer, cx| {
11097            buffer.expand_excerpts([excerpt], lines, direction, cx)
11098        })
11099    }
11100
11101    pub fn go_to_singleton_buffer_point(
11102        &mut self,
11103        point: Point,
11104        window: &mut Window,
11105        cx: &mut Context<Self>,
11106    ) {
11107        self.go_to_singleton_buffer_range(point..point, window, cx);
11108    }
11109
11110    pub fn go_to_singleton_buffer_range(
11111        &mut self,
11112        range: Range<Point>,
11113        window: &mut Window,
11114        cx: &mut Context<Self>,
11115    ) {
11116        let multibuffer = self.buffer().read(cx);
11117        let Some(buffer) = multibuffer.as_singleton() else {
11118            return;
11119        };
11120        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11121            return;
11122        };
11123        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11124            return;
11125        };
11126        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11127            s.select_anchor_ranges([start..end])
11128        });
11129    }
11130
11131    fn go_to_diagnostic(
11132        &mut self,
11133        _: &GoToDiagnostic,
11134        window: &mut Window,
11135        cx: &mut Context<Self>,
11136    ) {
11137        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11138    }
11139
11140    fn go_to_prev_diagnostic(
11141        &mut self,
11142        _: &GoToPrevDiagnostic,
11143        window: &mut Window,
11144        cx: &mut Context<Self>,
11145    ) {
11146        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11147    }
11148
11149    pub fn go_to_diagnostic_impl(
11150        &mut self,
11151        direction: Direction,
11152        window: &mut Window,
11153        cx: &mut Context<Self>,
11154    ) {
11155        let buffer = self.buffer.read(cx).snapshot(cx);
11156        let selection = self.selections.newest::<usize>(cx);
11157
11158        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11159        if direction == Direction::Next {
11160            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11161                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11162                    return;
11163                };
11164                self.activate_diagnostics(
11165                    buffer_id,
11166                    popover.local_diagnostic.diagnostic.group_id,
11167                    window,
11168                    cx,
11169                );
11170                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11171                    let primary_range_start = active_diagnostics.primary_range.start;
11172                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11173                        let mut new_selection = s.newest_anchor().clone();
11174                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11175                        s.select_anchors(vec![new_selection.clone()]);
11176                    });
11177                    self.refresh_inline_completion(false, true, window, cx);
11178                }
11179                return;
11180            }
11181        }
11182
11183        let active_group_id = self
11184            .active_diagnostics
11185            .as_ref()
11186            .map(|active_group| active_group.group_id);
11187        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11188            active_diagnostics
11189                .primary_range
11190                .to_offset(&buffer)
11191                .to_inclusive()
11192        });
11193        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11194            if active_primary_range.contains(&selection.head()) {
11195                *active_primary_range.start()
11196            } else {
11197                selection.head()
11198            }
11199        } else {
11200            selection.head()
11201        };
11202
11203        let snapshot = self.snapshot(window, cx);
11204        let primary_diagnostics_before = buffer
11205            .diagnostics_in_range::<usize>(0..search_start)
11206            .filter(|entry| entry.diagnostic.is_primary)
11207            .filter(|entry| entry.range.start != entry.range.end)
11208            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11209            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11210            .collect::<Vec<_>>();
11211        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11212            primary_diagnostics_before
11213                .iter()
11214                .position(|entry| entry.diagnostic.group_id == active_group_id)
11215        });
11216
11217        let primary_diagnostics_after = buffer
11218            .diagnostics_in_range::<usize>(search_start..buffer.len())
11219            .filter(|entry| entry.diagnostic.is_primary)
11220            .filter(|entry| entry.range.start != entry.range.end)
11221            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11222            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11223            .collect::<Vec<_>>();
11224        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11225            primary_diagnostics_after
11226                .iter()
11227                .enumerate()
11228                .rev()
11229                .find_map(|(i, entry)| {
11230                    if entry.diagnostic.group_id == active_group_id {
11231                        Some(i)
11232                    } else {
11233                        None
11234                    }
11235                })
11236        });
11237
11238        let next_primary_diagnostic = match direction {
11239            Direction::Prev => primary_diagnostics_before
11240                .iter()
11241                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11242                .rev()
11243                .next(),
11244            Direction::Next => primary_diagnostics_after
11245                .iter()
11246                .skip(
11247                    last_same_group_diagnostic_after
11248                        .map(|index| index + 1)
11249                        .unwrap_or(0),
11250                )
11251                .next(),
11252        };
11253
11254        // Cycle around to the start of the buffer, potentially moving back to the start of
11255        // the currently active diagnostic.
11256        let cycle_around = || match direction {
11257            Direction::Prev => primary_diagnostics_after
11258                .iter()
11259                .rev()
11260                .chain(primary_diagnostics_before.iter().rev())
11261                .next(),
11262            Direction::Next => primary_diagnostics_before
11263                .iter()
11264                .chain(primary_diagnostics_after.iter())
11265                .next(),
11266        };
11267
11268        if let Some((primary_range, group_id)) = next_primary_diagnostic
11269            .or_else(cycle_around)
11270            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11271        {
11272            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11273                return;
11274            };
11275            self.activate_diagnostics(buffer_id, group_id, window, cx);
11276            if self.active_diagnostics.is_some() {
11277                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11278                    s.select(vec![Selection {
11279                        id: selection.id,
11280                        start: primary_range.start,
11281                        end: primary_range.start,
11282                        reversed: false,
11283                        goal: SelectionGoal::None,
11284                    }]);
11285                });
11286                self.refresh_inline_completion(false, true, window, cx);
11287            }
11288        }
11289    }
11290
11291    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11292        let snapshot = self.snapshot(window, cx);
11293        let selection = self.selections.newest::<Point>(cx);
11294        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
11295    }
11296
11297    fn go_to_hunk_after_position(
11298        &mut self,
11299        snapshot: &EditorSnapshot,
11300        position: Point,
11301        window: &mut Window,
11302        cx: &mut Context<Editor>,
11303    ) -> Option<MultiBufferDiffHunk> {
11304        let mut hunk = snapshot
11305            .buffer_snapshot
11306            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11307            .find(|hunk| hunk.row_range.start.0 > position.row);
11308        if hunk.is_none() {
11309            hunk = snapshot
11310                .buffer_snapshot
11311                .diff_hunks_in_range(Point::zero()..position)
11312                .find(|hunk| hunk.row_range.end.0 < position.row)
11313        }
11314        if let Some(hunk) = &hunk {
11315            let destination = Point::new(hunk.row_range.start.0, 0);
11316            self.unfold_ranges(&[destination..destination], false, false, cx);
11317            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11318                s.select_ranges(vec![destination..destination]);
11319            });
11320        }
11321
11322        hunk
11323    }
11324
11325    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
11326        let snapshot = self.snapshot(window, cx);
11327        let selection = self.selections.newest::<Point>(cx);
11328        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
11329    }
11330
11331    fn go_to_hunk_before_position(
11332        &mut self,
11333        snapshot: &EditorSnapshot,
11334        position: Point,
11335        window: &mut Window,
11336        cx: &mut Context<Editor>,
11337    ) -> Option<MultiBufferDiffHunk> {
11338        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
11339        if hunk.is_none() {
11340            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
11341        }
11342        if let Some(hunk) = &hunk {
11343            let destination = Point::new(hunk.row_range.start.0, 0);
11344            self.unfold_ranges(&[destination..destination], false, false, cx);
11345            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11346                s.select_ranges(vec![destination..destination]);
11347            });
11348        }
11349
11350        hunk
11351    }
11352
11353    pub fn go_to_definition(
11354        &mut self,
11355        _: &GoToDefinition,
11356        window: &mut Window,
11357        cx: &mut Context<Self>,
11358    ) -> Task<Result<Navigated>> {
11359        let definition =
11360            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11361        cx.spawn_in(window, |editor, mut cx| async move {
11362            if definition.await? == Navigated::Yes {
11363                return Ok(Navigated::Yes);
11364            }
11365            match editor.update_in(&mut cx, |editor, window, cx| {
11366                editor.find_all_references(&FindAllReferences, window, cx)
11367            })? {
11368                Some(references) => references.await,
11369                None => Ok(Navigated::No),
11370            }
11371        })
11372    }
11373
11374    pub fn go_to_declaration(
11375        &mut self,
11376        _: &GoToDeclaration,
11377        window: &mut Window,
11378        cx: &mut Context<Self>,
11379    ) -> Task<Result<Navigated>> {
11380        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11381    }
11382
11383    pub fn go_to_declaration_split(
11384        &mut self,
11385        _: &GoToDeclaration,
11386        window: &mut Window,
11387        cx: &mut Context<Self>,
11388    ) -> Task<Result<Navigated>> {
11389        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11390    }
11391
11392    pub fn go_to_implementation(
11393        &mut self,
11394        _: &GoToImplementation,
11395        window: &mut Window,
11396        cx: &mut Context<Self>,
11397    ) -> Task<Result<Navigated>> {
11398        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11399    }
11400
11401    pub fn go_to_implementation_split(
11402        &mut self,
11403        _: &GoToImplementationSplit,
11404        window: &mut Window,
11405        cx: &mut Context<Self>,
11406    ) -> Task<Result<Navigated>> {
11407        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11408    }
11409
11410    pub fn go_to_type_definition(
11411        &mut self,
11412        _: &GoToTypeDefinition,
11413        window: &mut Window,
11414        cx: &mut Context<Self>,
11415    ) -> Task<Result<Navigated>> {
11416        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11417    }
11418
11419    pub fn go_to_definition_split(
11420        &mut self,
11421        _: &GoToDefinitionSplit,
11422        window: &mut Window,
11423        cx: &mut Context<Self>,
11424    ) -> Task<Result<Navigated>> {
11425        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11426    }
11427
11428    pub fn go_to_type_definition_split(
11429        &mut self,
11430        _: &GoToTypeDefinitionSplit,
11431        window: &mut Window,
11432        cx: &mut Context<Self>,
11433    ) -> Task<Result<Navigated>> {
11434        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11435    }
11436
11437    fn go_to_definition_of_kind(
11438        &mut self,
11439        kind: GotoDefinitionKind,
11440        split: bool,
11441        window: &mut Window,
11442        cx: &mut Context<Self>,
11443    ) -> Task<Result<Navigated>> {
11444        let Some(provider) = self.semantics_provider.clone() else {
11445            return Task::ready(Ok(Navigated::No));
11446        };
11447        let head = self.selections.newest::<usize>(cx).head();
11448        let buffer = self.buffer.read(cx);
11449        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11450            text_anchor
11451        } else {
11452            return Task::ready(Ok(Navigated::No));
11453        };
11454
11455        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11456            return Task::ready(Ok(Navigated::No));
11457        };
11458
11459        cx.spawn_in(window, |editor, mut cx| async move {
11460            let definitions = definitions.await?;
11461            let navigated = editor
11462                .update_in(&mut cx, |editor, window, cx| {
11463                    editor.navigate_to_hover_links(
11464                        Some(kind),
11465                        definitions
11466                            .into_iter()
11467                            .filter(|location| {
11468                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11469                            })
11470                            .map(HoverLink::Text)
11471                            .collect::<Vec<_>>(),
11472                        split,
11473                        window,
11474                        cx,
11475                    )
11476                })?
11477                .await?;
11478            anyhow::Ok(navigated)
11479        })
11480    }
11481
11482    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11483        let selection = self.selections.newest_anchor();
11484        let head = selection.head();
11485        let tail = selection.tail();
11486
11487        let Some((buffer, start_position)) =
11488            self.buffer.read(cx).text_anchor_for_position(head, cx)
11489        else {
11490            return;
11491        };
11492
11493        let end_position = if head != tail {
11494            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11495                return;
11496            };
11497            Some(pos)
11498        } else {
11499            None
11500        };
11501
11502        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11503            let url = if let Some(end_pos) = end_position {
11504                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11505            } else {
11506                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11507            };
11508
11509            if let Some(url) = url {
11510                editor.update(&mut cx, |_, cx| {
11511                    cx.open_url(&url);
11512                })
11513            } else {
11514                Ok(())
11515            }
11516        });
11517
11518        url_finder.detach();
11519    }
11520
11521    pub fn open_selected_filename(
11522        &mut self,
11523        _: &OpenSelectedFilename,
11524        window: &mut Window,
11525        cx: &mut Context<Self>,
11526    ) {
11527        let Some(workspace) = self.workspace() else {
11528            return;
11529        };
11530
11531        let position = self.selections.newest_anchor().head();
11532
11533        let Some((buffer, buffer_position)) =
11534            self.buffer.read(cx).text_anchor_for_position(position, cx)
11535        else {
11536            return;
11537        };
11538
11539        let project = self.project.clone();
11540
11541        cx.spawn_in(window, |_, mut cx| async move {
11542            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11543
11544            if let Some((_, path)) = result {
11545                workspace
11546                    .update_in(&mut cx, |workspace, window, cx| {
11547                        workspace.open_resolved_path(path, window, cx)
11548                    })?
11549                    .await?;
11550            }
11551            anyhow::Ok(())
11552        })
11553        .detach();
11554    }
11555
11556    pub(crate) fn navigate_to_hover_links(
11557        &mut self,
11558        kind: Option<GotoDefinitionKind>,
11559        mut definitions: Vec<HoverLink>,
11560        split: bool,
11561        window: &mut Window,
11562        cx: &mut Context<Editor>,
11563    ) -> Task<Result<Navigated>> {
11564        // If there is one definition, just open it directly
11565        if definitions.len() == 1 {
11566            let definition = definitions.pop().unwrap();
11567
11568            enum TargetTaskResult {
11569                Location(Option<Location>),
11570                AlreadyNavigated,
11571            }
11572
11573            let target_task = match definition {
11574                HoverLink::Text(link) => {
11575                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11576                }
11577                HoverLink::InlayHint(lsp_location, server_id) => {
11578                    let computation =
11579                        self.compute_target_location(lsp_location, server_id, window, cx);
11580                    cx.background_spawn(async move {
11581                        let location = computation.await?;
11582                        Ok(TargetTaskResult::Location(location))
11583                    })
11584                }
11585                HoverLink::Url(url) => {
11586                    cx.open_url(&url);
11587                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11588                }
11589                HoverLink::File(path) => {
11590                    if let Some(workspace) = self.workspace() {
11591                        cx.spawn_in(window, |_, mut cx| async move {
11592                            workspace
11593                                .update_in(&mut cx, |workspace, window, cx| {
11594                                    workspace.open_resolved_path(path, window, cx)
11595                                })?
11596                                .await
11597                                .map(|_| TargetTaskResult::AlreadyNavigated)
11598                        })
11599                    } else {
11600                        Task::ready(Ok(TargetTaskResult::Location(None)))
11601                    }
11602                }
11603            };
11604            cx.spawn_in(window, |editor, mut cx| async move {
11605                let target = match target_task.await.context("target resolution task")? {
11606                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11607                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11608                    TargetTaskResult::Location(Some(target)) => target,
11609                };
11610
11611                editor.update_in(&mut cx, |editor, window, cx| {
11612                    let Some(workspace) = editor.workspace() else {
11613                        return Navigated::No;
11614                    };
11615                    let pane = workspace.read(cx).active_pane().clone();
11616
11617                    let range = target.range.to_point(target.buffer.read(cx));
11618                    let range = editor.range_for_match(&range);
11619                    let range = collapse_multiline_range(range);
11620
11621                    if !split
11622                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11623                    {
11624                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11625                    } else {
11626                        window.defer(cx, move |window, cx| {
11627                            let target_editor: Entity<Self> =
11628                                workspace.update(cx, |workspace, cx| {
11629                                    let pane = if split {
11630                                        workspace.adjacent_pane(window, cx)
11631                                    } else {
11632                                        workspace.active_pane().clone()
11633                                    };
11634
11635                                    workspace.open_project_item(
11636                                        pane,
11637                                        target.buffer.clone(),
11638                                        true,
11639                                        true,
11640                                        window,
11641                                        cx,
11642                                    )
11643                                });
11644                            target_editor.update(cx, |target_editor, cx| {
11645                                // When selecting a definition in a different buffer, disable the nav history
11646                                // to avoid creating a history entry at the previous cursor location.
11647                                pane.update(cx, |pane, _| pane.disable_history());
11648                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11649                                pane.update(cx, |pane, _| pane.enable_history());
11650                            });
11651                        });
11652                    }
11653                    Navigated::Yes
11654                })
11655            })
11656        } else if !definitions.is_empty() {
11657            cx.spawn_in(window, |editor, mut cx| async move {
11658                let (title, location_tasks, workspace) = editor
11659                    .update_in(&mut cx, |editor, window, cx| {
11660                        let tab_kind = match kind {
11661                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11662                            _ => "Definitions",
11663                        };
11664                        let title = definitions
11665                            .iter()
11666                            .find_map(|definition| match definition {
11667                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11668                                    let buffer = origin.buffer.read(cx);
11669                                    format!(
11670                                        "{} for {}",
11671                                        tab_kind,
11672                                        buffer
11673                                            .text_for_range(origin.range.clone())
11674                                            .collect::<String>()
11675                                    )
11676                                }),
11677                                HoverLink::InlayHint(_, _) => None,
11678                                HoverLink::Url(_) => None,
11679                                HoverLink::File(_) => None,
11680                            })
11681                            .unwrap_or(tab_kind.to_string());
11682                        let location_tasks = definitions
11683                            .into_iter()
11684                            .map(|definition| match definition {
11685                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11686                                HoverLink::InlayHint(lsp_location, server_id) => editor
11687                                    .compute_target_location(lsp_location, server_id, window, cx),
11688                                HoverLink::Url(_) => Task::ready(Ok(None)),
11689                                HoverLink::File(_) => Task::ready(Ok(None)),
11690                            })
11691                            .collect::<Vec<_>>();
11692                        (title, location_tasks, editor.workspace().clone())
11693                    })
11694                    .context("location tasks preparation")?;
11695
11696                let locations = future::join_all(location_tasks)
11697                    .await
11698                    .into_iter()
11699                    .filter_map(|location| location.transpose())
11700                    .collect::<Result<_>>()
11701                    .context("location tasks")?;
11702
11703                let Some(workspace) = workspace else {
11704                    return Ok(Navigated::No);
11705                };
11706                let opened = workspace
11707                    .update_in(&mut cx, |workspace, window, cx| {
11708                        Self::open_locations_in_multibuffer(
11709                            workspace,
11710                            locations,
11711                            title,
11712                            split,
11713                            MultibufferSelectionMode::First,
11714                            window,
11715                            cx,
11716                        )
11717                    })
11718                    .ok();
11719
11720                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11721            })
11722        } else {
11723            Task::ready(Ok(Navigated::No))
11724        }
11725    }
11726
11727    fn compute_target_location(
11728        &self,
11729        lsp_location: lsp::Location,
11730        server_id: LanguageServerId,
11731        window: &mut Window,
11732        cx: &mut Context<Self>,
11733    ) -> Task<anyhow::Result<Option<Location>>> {
11734        let Some(project) = self.project.clone() else {
11735            return Task::ready(Ok(None));
11736        };
11737
11738        cx.spawn_in(window, move |editor, mut cx| async move {
11739            let location_task = editor.update(&mut cx, |_, cx| {
11740                project.update(cx, |project, cx| {
11741                    let language_server_name = project
11742                        .language_server_statuses(cx)
11743                        .find(|(id, _)| server_id == *id)
11744                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11745                    language_server_name.map(|language_server_name| {
11746                        project.open_local_buffer_via_lsp(
11747                            lsp_location.uri.clone(),
11748                            server_id,
11749                            language_server_name,
11750                            cx,
11751                        )
11752                    })
11753                })
11754            })?;
11755            let location = match location_task {
11756                Some(task) => Some({
11757                    let target_buffer_handle = task.await.context("open local buffer")?;
11758                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11759                        let target_start = target_buffer
11760                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11761                        let target_end = target_buffer
11762                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11763                        target_buffer.anchor_after(target_start)
11764                            ..target_buffer.anchor_before(target_end)
11765                    })?;
11766                    Location {
11767                        buffer: target_buffer_handle,
11768                        range,
11769                    }
11770                }),
11771                None => None,
11772            };
11773            Ok(location)
11774        })
11775    }
11776
11777    pub fn find_all_references(
11778        &mut self,
11779        _: &FindAllReferences,
11780        window: &mut Window,
11781        cx: &mut Context<Self>,
11782    ) -> Option<Task<Result<Navigated>>> {
11783        let selection = self.selections.newest::<usize>(cx);
11784        let multi_buffer = self.buffer.read(cx);
11785        let head = selection.head();
11786
11787        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11788        let head_anchor = multi_buffer_snapshot.anchor_at(
11789            head,
11790            if head < selection.tail() {
11791                Bias::Right
11792            } else {
11793                Bias::Left
11794            },
11795        );
11796
11797        match self
11798            .find_all_references_task_sources
11799            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11800        {
11801            Ok(_) => {
11802                log::info!(
11803                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11804                );
11805                return None;
11806            }
11807            Err(i) => {
11808                self.find_all_references_task_sources.insert(i, head_anchor);
11809            }
11810        }
11811
11812        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11813        let workspace = self.workspace()?;
11814        let project = workspace.read(cx).project().clone();
11815        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11816        Some(cx.spawn_in(window, |editor, mut cx| async move {
11817            let _cleanup = defer({
11818                let mut cx = cx.clone();
11819                move || {
11820                    let _ = editor.update(&mut cx, |editor, _| {
11821                        if let Ok(i) =
11822                            editor
11823                                .find_all_references_task_sources
11824                                .binary_search_by(|anchor| {
11825                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11826                                })
11827                        {
11828                            editor.find_all_references_task_sources.remove(i);
11829                        }
11830                    });
11831                }
11832            });
11833
11834            let locations = references.await?;
11835            if locations.is_empty() {
11836                return anyhow::Ok(Navigated::No);
11837            }
11838
11839            workspace.update_in(&mut cx, |workspace, window, cx| {
11840                let title = locations
11841                    .first()
11842                    .as_ref()
11843                    .map(|location| {
11844                        let buffer = location.buffer.read(cx);
11845                        format!(
11846                            "References to `{}`",
11847                            buffer
11848                                .text_for_range(location.range.clone())
11849                                .collect::<String>()
11850                        )
11851                    })
11852                    .unwrap();
11853                Self::open_locations_in_multibuffer(
11854                    workspace,
11855                    locations,
11856                    title,
11857                    false,
11858                    MultibufferSelectionMode::First,
11859                    window,
11860                    cx,
11861                );
11862                Navigated::Yes
11863            })
11864        }))
11865    }
11866
11867    /// Opens a multibuffer with the given project locations in it
11868    pub fn open_locations_in_multibuffer(
11869        workspace: &mut Workspace,
11870        mut locations: Vec<Location>,
11871        title: String,
11872        split: bool,
11873        multibuffer_selection_mode: MultibufferSelectionMode,
11874        window: &mut Window,
11875        cx: &mut Context<Workspace>,
11876    ) {
11877        // If there are multiple definitions, open them in a multibuffer
11878        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11879        let mut locations = locations.into_iter().peekable();
11880        let mut ranges = Vec::new();
11881        let capability = workspace.project().read(cx).capability();
11882
11883        let excerpt_buffer = cx.new(|cx| {
11884            let mut multibuffer = MultiBuffer::new(capability);
11885            while let Some(location) = locations.next() {
11886                let buffer = location.buffer.read(cx);
11887                let mut ranges_for_buffer = Vec::new();
11888                let range = location.range.to_offset(buffer);
11889                ranges_for_buffer.push(range.clone());
11890
11891                while let Some(next_location) = locations.peek() {
11892                    if next_location.buffer == location.buffer {
11893                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11894                        locations.next();
11895                    } else {
11896                        break;
11897                    }
11898                }
11899
11900                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11901                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11902                    location.buffer.clone(),
11903                    ranges_for_buffer,
11904                    DEFAULT_MULTIBUFFER_CONTEXT,
11905                    cx,
11906                ))
11907            }
11908
11909            multibuffer.with_title(title)
11910        });
11911
11912        let editor = cx.new(|cx| {
11913            Editor::for_multibuffer(
11914                excerpt_buffer,
11915                Some(workspace.project().clone()),
11916                true,
11917                window,
11918                cx,
11919            )
11920        });
11921        editor.update(cx, |editor, cx| {
11922            match multibuffer_selection_mode {
11923                MultibufferSelectionMode::First => {
11924                    if let Some(first_range) = ranges.first() {
11925                        editor.change_selections(None, window, cx, |selections| {
11926                            selections.clear_disjoint();
11927                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11928                        });
11929                    }
11930                    editor.highlight_background::<Self>(
11931                        &ranges,
11932                        |theme| theme.editor_highlighted_line_background,
11933                        cx,
11934                    );
11935                }
11936                MultibufferSelectionMode::All => {
11937                    editor.change_selections(None, window, cx, |selections| {
11938                        selections.clear_disjoint();
11939                        selections.select_anchor_ranges(ranges);
11940                    });
11941                }
11942            }
11943            editor.register_buffers_with_language_servers(cx);
11944        });
11945
11946        let item = Box::new(editor);
11947        let item_id = item.item_id();
11948
11949        if split {
11950            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11951        } else {
11952            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11953                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11954                    pane.close_current_preview_item(window, cx)
11955                } else {
11956                    None
11957                }
11958            });
11959            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11960        }
11961        workspace.active_pane().update(cx, |pane, cx| {
11962            pane.set_preview_item_id(Some(item_id), cx);
11963        });
11964    }
11965
11966    pub fn rename(
11967        &mut self,
11968        _: &Rename,
11969        window: &mut Window,
11970        cx: &mut Context<Self>,
11971    ) -> Option<Task<Result<()>>> {
11972        use language::ToOffset as _;
11973
11974        let provider = self.semantics_provider.clone()?;
11975        let selection = self.selections.newest_anchor().clone();
11976        let (cursor_buffer, cursor_buffer_position) = self
11977            .buffer
11978            .read(cx)
11979            .text_anchor_for_position(selection.head(), cx)?;
11980        let (tail_buffer, cursor_buffer_position_end) = self
11981            .buffer
11982            .read(cx)
11983            .text_anchor_for_position(selection.tail(), cx)?;
11984        if tail_buffer != cursor_buffer {
11985            return None;
11986        }
11987
11988        let snapshot = cursor_buffer.read(cx).snapshot();
11989        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11990        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11991        let prepare_rename = provider
11992            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11993            .unwrap_or_else(|| Task::ready(Ok(None)));
11994        drop(snapshot);
11995
11996        Some(cx.spawn_in(window, |this, mut cx| async move {
11997            let rename_range = if let Some(range) = prepare_rename.await? {
11998                Some(range)
11999            } else {
12000                this.update(&mut cx, |this, cx| {
12001                    let buffer = this.buffer.read(cx).snapshot(cx);
12002                    let mut buffer_highlights = this
12003                        .document_highlights_for_position(selection.head(), &buffer)
12004                        .filter(|highlight| {
12005                            highlight.start.excerpt_id == selection.head().excerpt_id
12006                                && highlight.end.excerpt_id == selection.head().excerpt_id
12007                        });
12008                    buffer_highlights
12009                        .next()
12010                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12011                })?
12012            };
12013            if let Some(rename_range) = rename_range {
12014                this.update_in(&mut cx, |this, window, cx| {
12015                    let snapshot = cursor_buffer.read(cx).snapshot();
12016                    let rename_buffer_range = rename_range.to_offset(&snapshot);
12017                    let cursor_offset_in_rename_range =
12018                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12019                    let cursor_offset_in_rename_range_end =
12020                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12021
12022                    this.take_rename(false, window, cx);
12023                    let buffer = this.buffer.read(cx).read(cx);
12024                    let cursor_offset = selection.head().to_offset(&buffer);
12025                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12026                    let rename_end = rename_start + rename_buffer_range.len();
12027                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12028                    let mut old_highlight_id = None;
12029                    let old_name: Arc<str> = buffer
12030                        .chunks(rename_start..rename_end, true)
12031                        .map(|chunk| {
12032                            if old_highlight_id.is_none() {
12033                                old_highlight_id = chunk.syntax_highlight_id;
12034                            }
12035                            chunk.text
12036                        })
12037                        .collect::<String>()
12038                        .into();
12039
12040                    drop(buffer);
12041
12042                    // Position the selection in the rename editor so that it matches the current selection.
12043                    this.show_local_selections = false;
12044                    let rename_editor = cx.new(|cx| {
12045                        let mut editor = Editor::single_line(window, cx);
12046                        editor.buffer.update(cx, |buffer, cx| {
12047                            buffer.edit([(0..0, old_name.clone())], None, cx)
12048                        });
12049                        let rename_selection_range = match cursor_offset_in_rename_range
12050                            .cmp(&cursor_offset_in_rename_range_end)
12051                        {
12052                            Ordering::Equal => {
12053                                editor.select_all(&SelectAll, window, cx);
12054                                return editor;
12055                            }
12056                            Ordering::Less => {
12057                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12058                            }
12059                            Ordering::Greater => {
12060                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12061                            }
12062                        };
12063                        if rename_selection_range.end > old_name.len() {
12064                            editor.select_all(&SelectAll, window, cx);
12065                        } else {
12066                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12067                                s.select_ranges([rename_selection_range]);
12068                            });
12069                        }
12070                        editor
12071                    });
12072                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12073                        if e == &EditorEvent::Focused {
12074                            cx.emit(EditorEvent::FocusedIn)
12075                        }
12076                    })
12077                    .detach();
12078
12079                    let write_highlights =
12080                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12081                    let read_highlights =
12082                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12083                    let ranges = write_highlights
12084                        .iter()
12085                        .flat_map(|(_, ranges)| ranges.iter())
12086                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12087                        .cloned()
12088                        .collect();
12089
12090                    this.highlight_text::<Rename>(
12091                        ranges,
12092                        HighlightStyle {
12093                            fade_out: Some(0.6),
12094                            ..Default::default()
12095                        },
12096                        cx,
12097                    );
12098                    let rename_focus_handle = rename_editor.focus_handle(cx);
12099                    window.focus(&rename_focus_handle);
12100                    let block_id = this.insert_blocks(
12101                        [BlockProperties {
12102                            style: BlockStyle::Flex,
12103                            placement: BlockPlacement::Below(range.start),
12104                            height: 1,
12105                            render: Arc::new({
12106                                let rename_editor = rename_editor.clone();
12107                                move |cx: &mut BlockContext| {
12108                                    let mut text_style = cx.editor_style.text.clone();
12109                                    if let Some(highlight_style) = old_highlight_id
12110                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12111                                    {
12112                                        text_style = text_style.highlight(highlight_style);
12113                                    }
12114                                    div()
12115                                        .block_mouse_down()
12116                                        .pl(cx.anchor_x)
12117                                        .child(EditorElement::new(
12118                                            &rename_editor,
12119                                            EditorStyle {
12120                                                background: cx.theme().system().transparent,
12121                                                local_player: cx.editor_style.local_player,
12122                                                text: text_style,
12123                                                scrollbar_width: cx.editor_style.scrollbar_width,
12124                                                syntax: cx.editor_style.syntax.clone(),
12125                                                status: cx.editor_style.status.clone(),
12126                                                inlay_hints_style: HighlightStyle {
12127                                                    font_weight: Some(FontWeight::BOLD),
12128                                                    ..make_inlay_hints_style(cx.app)
12129                                                },
12130                                                inline_completion_styles: make_suggestion_styles(
12131                                                    cx.app,
12132                                                ),
12133                                                ..EditorStyle::default()
12134                                            },
12135                                        ))
12136                                        .into_any_element()
12137                                }
12138                            }),
12139                            priority: 0,
12140                        }],
12141                        Some(Autoscroll::fit()),
12142                        cx,
12143                    )[0];
12144                    this.pending_rename = Some(RenameState {
12145                        range,
12146                        old_name,
12147                        editor: rename_editor,
12148                        block_id,
12149                    });
12150                })?;
12151            }
12152
12153            Ok(())
12154        }))
12155    }
12156
12157    pub fn confirm_rename(
12158        &mut self,
12159        _: &ConfirmRename,
12160        window: &mut Window,
12161        cx: &mut Context<Self>,
12162    ) -> Option<Task<Result<()>>> {
12163        let rename = self.take_rename(false, window, cx)?;
12164        let workspace = self.workspace()?.downgrade();
12165        let (buffer, start) = self
12166            .buffer
12167            .read(cx)
12168            .text_anchor_for_position(rename.range.start, cx)?;
12169        let (end_buffer, _) = self
12170            .buffer
12171            .read(cx)
12172            .text_anchor_for_position(rename.range.end, cx)?;
12173        if buffer != end_buffer {
12174            return None;
12175        }
12176
12177        let old_name = rename.old_name;
12178        let new_name = rename.editor.read(cx).text(cx);
12179
12180        let rename = self.semantics_provider.as_ref()?.perform_rename(
12181            &buffer,
12182            start,
12183            new_name.clone(),
12184            cx,
12185        )?;
12186
12187        Some(cx.spawn_in(window, |editor, mut cx| async move {
12188            let project_transaction = rename.await?;
12189            Self::open_project_transaction(
12190                &editor,
12191                workspace,
12192                project_transaction,
12193                format!("Rename: {}{}", old_name, new_name),
12194                cx.clone(),
12195            )
12196            .await?;
12197
12198            editor.update(&mut cx, |editor, cx| {
12199                editor.refresh_document_highlights(cx);
12200            })?;
12201            Ok(())
12202        }))
12203    }
12204
12205    fn take_rename(
12206        &mut self,
12207        moving_cursor: bool,
12208        window: &mut Window,
12209        cx: &mut Context<Self>,
12210    ) -> Option<RenameState> {
12211        let rename = self.pending_rename.take()?;
12212        if rename.editor.focus_handle(cx).is_focused(window) {
12213            window.focus(&self.focus_handle);
12214        }
12215
12216        self.remove_blocks(
12217            [rename.block_id].into_iter().collect(),
12218            Some(Autoscroll::fit()),
12219            cx,
12220        );
12221        self.clear_highlights::<Rename>(cx);
12222        self.show_local_selections = true;
12223
12224        if moving_cursor {
12225            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12226                editor.selections.newest::<usize>(cx).head()
12227            });
12228
12229            // Update the selection to match the position of the selection inside
12230            // the rename editor.
12231            let snapshot = self.buffer.read(cx).read(cx);
12232            let rename_range = rename.range.to_offset(&snapshot);
12233            let cursor_in_editor = snapshot
12234                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12235                .min(rename_range.end);
12236            drop(snapshot);
12237
12238            self.change_selections(None, window, cx, |s| {
12239                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12240            });
12241        } else {
12242            self.refresh_document_highlights(cx);
12243        }
12244
12245        Some(rename)
12246    }
12247
12248    pub fn pending_rename(&self) -> Option<&RenameState> {
12249        self.pending_rename.as_ref()
12250    }
12251
12252    fn format(
12253        &mut self,
12254        _: &Format,
12255        window: &mut Window,
12256        cx: &mut Context<Self>,
12257    ) -> Option<Task<Result<()>>> {
12258        let project = match &self.project {
12259            Some(project) => project.clone(),
12260            None => return None,
12261        };
12262
12263        Some(self.perform_format(
12264            project,
12265            FormatTrigger::Manual,
12266            FormatTarget::Buffers,
12267            window,
12268            cx,
12269        ))
12270    }
12271
12272    fn format_selections(
12273        &mut self,
12274        _: &FormatSelections,
12275        window: &mut Window,
12276        cx: &mut Context<Self>,
12277    ) -> Option<Task<Result<()>>> {
12278        let project = match &self.project {
12279            Some(project) => project.clone(),
12280            None => return None,
12281        };
12282
12283        let ranges = self
12284            .selections
12285            .all_adjusted(cx)
12286            .into_iter()
12287            .map(|selection| selection.range())
12288            .collect_vec();
12289
12290        Some(self.perform_format(
12291            project,
12292            FormatTrigger::Manual,
12293            FormatTarget::Ranges(ranges),
12294            window,
12295            cx,
12296        ))
12297    }
12298
12299    fn perform_format(
12300        &mut self,
12301        project: Entity<Project>,
12302        trigger: FormatTrigger,
12303        target: FormatTarget,
12304        window: &mut Window,
12305        cx: &mut Context<Self>,
12306    ) -> Task<Result<()>> {
12307        let buffer = self.buffer.clone();
12308        let (buffers, target) = match target {
12309            FormatTarget::Buffers => {
12310                let mut buffers = buffer.read(cx).all_buffers();
12311                if trigger == FormatTrigger::Save {
12312                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12313                }
12314                (buffers, LspFormatTarget::Buffers)
12315            }
12316            FormatTarget::Ranges(selection_ranges) => {
12317                let multi_buffer = buffer.read(cx);
12318                let snapshot = multi_buffer.read(cx);
12319                let mut buffers = HashSet::default();
12320                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12321                    BTreeMap::new();
12322                for selection_range in selection_ranges {
12323                    for (buffer, buffer_range, _) in
12324                        snapshot.range_to_buffer_ranges(selection_range)
12325                    {
12326                        let buffer_id = buffer.remote_id();
12327                        let start = buffer.anchor_before(buffer_range.start);
12328                        let end = buffer.anchor_after(buffer_range.end);
12329                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12330                        buffer_id_to_ranges
12331                            .entry(buffer_id)
12332                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12333                            .or_insert_with(|| vec![start..end]);
12334                    }
12335                }
12336                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12337            }
12338        };
12339
12340        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12341        let format = project.update(cx, |project, cx| {
12342            project.format(buffers, target, true, trigger, cx)
12343        });
12344
12345        cx.spawn_in(window, |_, mut cx| async move {
12346            let transaction = futures::select_biased! {
12347                () = timeout => {
12348                    log::warn!("timed out waiting for formatting");
12349                    None
12350                }
12351                transaction = format.log_err().fuse() => transaction,
12352            };
12353
12354            buffer
12355                .update(&mut cx, |buffer, cx| {
12356                    if let Some(transaction) = transaction {
12357                        if !buffer.is_singleton() {
12358                            buffer.push_transaction(&transaction.0, cx);
12359                        }
12360                    }
12361
12362                    cx.notify();
12363                })
12364                .ok();
12365
12366            Ok(())
12367        })
12368    }
12369
12370    fn restart_language_server(
12371        &mut self,
12372        _: &RestartLanguageServer,
12373        _: &mut Window,
12374        cx: &mut Context<Self>,
12375    ) {
12376        if let Some(project) = self.project.clone() {
12377            self.buffer.update(cx, |multi_buffer, cx| {
12378                project.update(cx, |project, cx| {
12379                    project.restart_language_servers_for_buffers(
12380                        multi_buffer.all_buffers().into_iter().collect(),
12381                        cx,
12382                    );
12383                });
12384            })
12385        }
12386    }
12387
12388    fn cancel_language_server_work(
12389        workspace: &mut Workspace,
12390        _: &actions::CancelLanguageServerWork,
12391        _: &mut Window,
12392        cx: &mut Context<Workspace>,
12393    ) {
12394        let project = workspace.project();
12395        let buffers = workspace
12396            .active_item(cx)
12397            .and_then(|item| item.act_as::<Editor>(cx))
12398            .map_or(HashSet::default(), |editor| {
12399                editor.read(cx).buffer.read(cx).all_buffers()
12400            });
12401        project.update(cx, |project, cx| {
12402            project.cancel_language_server_work_for_buffers(buffers, cx);
12403        });
12404    }
12405
12406    fn show_character_palette(
12407        &mut self,
12408        _: &ShowCharacterPalette,
12409        window: &mut Window,
12410        _: &mut Context<Self>,
12411    ) {
12412        window.show_character_palette();
12413    }
12414
12415    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12416        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12417            let buffer = self.buffer.read(cx).snapshot(cx);
12418            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12419            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12420            let is_valid = buffer
12421                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12422                .any(|entry| {
12423                    entry.diagnostic.is_primary
12424                        && !entry.range.is_empty()
12425                        && entry.range.start == primary_range_start
12426                        && entry.diagnostic.message == active_diagnostics.primary_message
12427                });
12428
12429            if is_valid != active_diagnostics.is_valid {
12430                active_diagnostics.is_valid = is_valid;
12431                let mut new_styles = HashMap::default();
12432                for (block_id, diagnostic) in &active_diagnostics.blocks {
12433                    new_styles.insert(
12434                        *block_id,
12435                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
12436                    );
12437                }
12438                self.display_map.update(cx, |display_map, _cx| {
12439                    display_map.replace_blocks(new_styles)
12440                });
12441            }
12442        }
12443    }
12444
12445    fn activate_diagnostics(
12446        &mut self,
12447        buffer_id: BufferId,
12448        group_id: usize,
12449        window: &mut Window,
12450        cx: &mut Context<Self>,
12451    ) {
12452        self.dismiss_diagnostics(cx);
12453        let snapshot = self.snapshot(window, cx);
12454        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12455            let buffer = self.buffer.read(cx).snapshot(cx);
12456
12457            let mut primary_range = None;
12458            let mut primary_message = None;
12459            let diagnostic_group = buffer
12460                .diagnostic_group(buffer_id, group_id)
12461                .filter_map(|entry| {
12462                    let start = entry.range.start;
12463                    let end = entry.range.end;
12464                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12465                        && (start.row == end.row
12466                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12467                    {
12468                        return None;
12469                    }
12470                    if entry.diagnostic.is_primary {
12471                        primary_range = Some(entry.range.clone());
12472                        primary_message = Some(entry.diagnostic.message.clone());
12473                    }
12474                    Some(entry)
12475                })
12476                .collect::<Vec<_>>();
12477            let primary_range = primary_range?;
12478            let primary_message = primary_message?;
12479
12480            let blocks = display_map
12481                .insert_blocks(
12482                    diagnostic_group.iter().map(|entry| {
12483                        let diagnostic = entry.diagnostic.clone();
12484                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12485                        BlockProperties {
12486                            style: BlockStyle::Fixed,
12487                            placement: BlockPlacement::Below(
12488                                buffer.anchor_after(entry.range.start),
12489                            ),
12490                            height: message_height,
12491                            render: diagnostic_block_renderer(diagnostic, None, true, true),
12492                            priority: 0,
12493                        }
12494                    }),
12495                    cx,
12496                )
12497                .into_iter()
12498                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12499                .collect();
12500
12501            Some(ActiveDiagnosticGroup {
12502                primary_range: buffer.anchor_before(primary_range.start)
12503                    ..buffer.anchor_after(primary_range.end),
12504                primary_message,
12505                group_id,
12506                blocks,
12507                is_valid: true,
12508            })
12509        });
12510    }
12511
12512    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12513        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12514            self.display_map.update(cx, |display_map, cx| {
12515                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12516            });
12517            cx.notify();
12518        }
12519    }
12520
12521    /// Disable inline diagnostics rendering for this editor.
12522    pub fn disable_inline_diagnostics(&mut self) {
12523        self.inline_diagnostics_enabled = false;
12524        self.inline_diagnostics_update = Task::ready(());
12525        self.inline_diagnostics.clear();
12526    }
12527
12528    pub fn inline_diagnostics_enabled(&self) -> bool {
12529        self.inline_diagnostics_enabled
12530    }
12531
12532    pub fn show_inline_diagnostics(&self) -> bool {
12533        self.show_inline_diagnostics
12534    }
12535
12536    pub fn toggle_inline_diagnostics(
12537        &mut self,
12538        _: &ToggleInlineDiagnostics,
12539        window: &mut Window,
12540        cx: &mut Context<'_, Editor>,
12541    ) {
12542        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12543        self.refresh_inline_diagnostics(false, window, cx);
12544    }
12545
12546    fn refresh_inline_diagnostics(
12547        &mut self,
12548        debounce: bool,
12549        window: &mut Window,
12550        cx: &mut Context<Self>,
12551    ) {
12552        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12553            self.inline_diagnostics_update = Task::ready(());
12554            self.inline_diagnostics.clear();
12555            return;
12556        }
12557
12558        let debounce_ms = ProjectSettings::get_global(cx)
12559            .diagnostics
12560            .inline
12561            .update_debounce_ms;
12562        let debounce = if debounce && debounce_ms > 0 {
12563            Some(Duration::from_millis(debounce_ms))
12564        } else {
12565            None
12566        };
12567        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12568            if let Some(debounce) = debounce {
12569                cx.background_executor().timer(debounce).await;
12570            }
12571            let Some(snapshot) = editor
12572                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12573                .ok()
12574            else {
12575                return;
12576            };
12577
12578            let new_inline_diagnostics = cx
12579                .background_spawn(async move {
12580                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12581                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12582                        let message = diagnostic_entry
12583                            .diagnostic
12584                            .message
12585                            .split_once('\n')
12586                            .map(|(line, _)| line)
12587                            .map(SharedString::new)
12588                            .unwrap_or_else(|| {
12589                                SharedString::from(diagnostic_entry.diagnostic.message)
12590                            });
12591                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12592                        let (Ok(i) | Err(i)) = inline_diagnostics
12593                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12594                        inline_diagnostics.insert(
12595                            i,
12596                            (
12597                                start_anchor,
12598                                InlineDiagnostic {
12599                                    message,
12600                                    group_id: diagnostic_entry.diagnostic.group_id,
12601                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12602                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12603                                    severity: diagnostic_entry.diagnostic.severity,
12604                                },
12605                            ),
12606                        );
12607                    }
12608                    inline_diagnostics
12609                })
12610                .await;
12611
12612            editor
12613                .update(&mut cx, |editor, cx| {
12614                    editor.inline_diagnostics = new_inline_diagnostics;
12615                    cx.notify();
12616                })
12617                .ok();
12618        });
12619    }
12620
12621    pub fn set_selections_from_remote(
12622        &mut self,
12623        selections: Vec<Selection<Anchor>>,
12624        pending_selection: Option<Selection<Anchor>>,
12625        window: &mut Window,
12626        cx: &mut Context<Self>,
12627    ) {
12628        let old_cursor_position = self.selections.newest_anchor().head();
12629        self.selections.change_with(cx, |s| {
12630            s.select_anchors(selections);
12631            if let Some(pending_selection) = pending_selection {
12632                s.set_pending(pending_selection, SelectMode::Character);
12633            } else {
12634                s.clear_pending();
12635            }
12636        });
12637        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12638    }
12639
12640    fn push_to_selection_history(&mut self) {
12641        self.selection_history.push(SelectionHistoryEntry {
12642            selections: self.selections.disjoint_anchors(),
12643            select_next_state: self.select_next_state.clone(),
12644            select_prev_state: self.select_prev_state.clone(),
12645            add_selections_state: self.add_selections_state.clone(),
12646        });
12647    }
12648
12649    pub fn transact(
12650        &mut self,
12651        window: &mut Window,
12652        cx: &mut Context<Self>,
12653        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12654    ) -> Option<TransactionId> {
12655        self.start_transaction_at(Instant::now(), window, cx);
12656        update(self, window, cx);
12657        self.end_transaction_at(Instant::now(), cx)
12658    }
12659
12660    pub fn start_transaction_at(
12661        &mut self,
12662        now: Instant,
12663        window: &mut Window,
12664        cx: &mut Context<Self>,
12665    ) {
12666        self.end_selection(window, cx);
12667        if let Some(tx_id) = self
12668            .buffer
12669            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12670        {
12671            self.selection_history
12672                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12673            cx.emit(EditorEvent::TransactionBegun {
12674                transaction_id: tx_id,
12675            })
12676        }
12677    }
12678
12679    pub fn end_transaction_at(
12680        &mut self,
12681        now: Instant,
12682        cx: &mut Context<Self>,
12683    ) -> Option<TransactionId> {
12684        if let Some(transaction_id) = self
12685            .buffer
12686            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12687        {
12688            if let Some((_, end_selections)) =
12689                self.selection_history.transaction_mut(transaction_id)
12690            {
12691                *end_selections = Some(self.selections.disjoint_anchors());
12692            } else {
12693                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12694            }
12695
12696            cx.emit(EditorEvent::Edited { transaction_id });
12697            Some(transaction_id)
12698        } else {
12699            None
12700        }
12701    }
12702
12703    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12704        if self.selection_mark_mode {
12705            self.change_selections(None, window, cx, |s| {
12706                s.move_with(|_, sel| {
12707                    sel.collapse_to(sel.head(), SelectionGoal::None);
12708                });
12709            })
12710        }
12711        self.selection_mark_mode = true;
12712        cx.notify();
12713    }
12714
12715    pub fn swap_selection_ends(
12716        &mut self,
12717        _: &actions::SwapSelectionEnds,
12718        window: &mut Window,
12719        cx: &mut Context<Self>,
12720    ) {
12721        self.change_selections(None, window, cx, |s| {
12722            s.move_with(|_, sel| {
12723                if sel.start != sel.end {
12724                    sel.reversed = !sel.reversed
12725                }
12726            });
12727        });
12728        self.request_autoscroll(Autoscroll::newest(), cx);
12729        cx.notify();
12730    }
12731
12732    pub fn toggle_fold(
12733        &mut self,
12734        _: &actions::ToggleFold,
12735        window: &mut Window,
12736        cx: &mut Context<Self>,
12737    ) {
12738        if self.is_singleton(cx) {
12739            let selection = self.selections.newest::<Point>(cx);
12740
12741            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12742            let range = if selection.is_empty() {
12743                let point = selection.head().to_display_point(&display_map);
12744                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12745                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12746                    .to_point(&display_map);
12747                start..end
12748            } else {
12749                selection.range()
12750            };
12751            if display_map.folds_in_range(range).next().is_some() {
12752                self.unfold_lines(&Default::default(), window, cx)
12753            } else {
12754                self.fold(&Default::default(), window, cx)
12755            }
12756        } else {
12757            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12758            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12759                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12760                .map(|(snapshot, _, _)| snapshot.remote_id())
12761                .collect();
12762
12763            for buffer_id in buffer_ids {
12764                if self.is_buffer_folded(buffer_id, cx) {
12765                    self.unfold_buffer(buffer_id, cx);
12766                } else {
12767                    self.fold_buffer(buffer_id, cx);
12768                }
12769            }
12770        }
12771    }
12772
12773    pub fn toggle_fold_recursive(
12774        &mut self,
12775        _: &actions::ToggleFoldRecursive,
12776        window: &mut Window,
12777        cx: &mut Context<Self>,
12778    ) {
12779        let selection = self.selections.newest::<Point>(cx);
12780
12781        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12782        let range = if selection.is_empty() {
12783            let point = selection.head().to_display_point(&display_map);
12784            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12785            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12786                .to_point(&display_map);
12787            start..end
12788        } else {
12789            selection.range()
12790        };
12791        if display_map.folds_in_range(range).next().is_some() {
12792            self.unfold_recursive(&Default::default(), window, cx)
12793        } else {
12794            self.fold_recursive(&Default::default(), window, cx)
12795        }
12796    }
12797
12798    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12799        if self.is_singleton(cx) {
12800            let mut to_fold = Vec::new();
12801            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12802            let selections = self.selections.all_adjusted(cx);
12803
12804            for selection in selections {
12805                let range = selection.range().sorted();
12806                let buffer_start_row = range.start.row;
12807
12808                if range.start.row != range.end.row {
12809                    let mut found = false;
12810                    let mut row = range.start.row;
12811                    while row <= range.end.row {
12812                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12813                        {
12814                            found = true;
12815                            row = crease.range().end.row + 1;
12816                            to_fold.push(crease);
12817                        } else {
12818                            row += 1
12819                        }
12820                    }
12821                    if found {
12822                        continue;
12823                    }
12824                }
12825
12826                for row in (0..=range.start.row).rev() {
12827                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12828                        if crease.range().end.row >= buffer_start_row {
12829                            to_fold.push(crease);
12830                            if row <= range.start.row {
12831                                break;
12832                            }
12833                        }
12834                    }
12835                }
12836            }
12837
12838            self.fold_creases(to_fold, true, window, cx);
12839        } else {
12840            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12841
12842            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12843                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12844                .map(|(snapshot, _, _)| snapshot.remote_id())
12845                .collect();
12846            for buffer_id in buffer_ids {
12847                self.fold_buffer(buffer_id, cx);
12848            }
12849        }
12850    }
12851
12852    fn fold_at_level(
12853        &mut self,
12854        fold_at: &FoldAtLevel,
12855        window: &mut Window,
12856        cx: &mut Context<Self>,
12857    ) {
12858        if !self.buffer.read(cx).is_singleton() {
12859            return;
12860        }
12861
12862        let fold_at_level = fold_at.0;
12863        let snapshot = self.buffer.read(cx).snapshot(cx);
12864        let mut to_fold = Vec::new();
12865        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12866
12867        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12868            while start_row < end_row {
12869                match self
12870                    .snapshot(window, cx)
12871                    .crease_for_buffer_row(MultiBufferRow(start_row))
12872                {
12873                    Some(crease) => {
12874                        let nested_start_row = crease.range().start.row + 1;
12875                        let nested_end_row = crease.range().end.row;
12876
12877                        if current_level < fold_at_level {
12878                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12879                        } else if current_level == fold_at_level {
12880                            to_fold.push(crease);
12881                        }
12882
12883                        start_row = nested_end_row + 1;
12884                    }
12885                    None => start_row += 1,
12886                }
12887            }
12888        }
12889
12890        self.fold_creases(to_fold, true, window, cx);
12891    }
12892
12893    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12894        if self.buffer.read(cx).is_singleton() {
12895            let mut fold_ranges = Vec::new();
12896            let snapshot = self.buffer.read(cx).snapshot(cx);
12897
12898            for row in 0..snapshot.max_row().0 {
12899                if let Some(foldable_range) = self
12900                    .snapshot(window, cx)
12901                    .crease_for_buffer_row(MultiBufferRow(row))
12902                {
12903                    fold_ranges.push(foldable_range);
12904                }
12905            }
12906
12907            self.fold_creases(fold_ranges, true, window, cx);
12908        } else {
12909            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12910                editor
12911                    .update_in(&mut cx, |editor, _, cx| {
12912                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12913                            editor.fold_buffer(buffer_id, cx);
12914                        }
12915                    })
12916                    .ok();
12917            });
12918        }
12919    }
12920
12921    pub fn fold_function_bodies(
12922        &mut self,
12923        _: &actions::FoldFunctionBodies,
12924        window: &mut Window,
12925        cx: &mut Context<Self>,
12926    ) {
12927        let snapshot = self.buffer.read(cx).snapshot(cx);
12928
12929        let ranges = snapshot
12930            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12931            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12932            .collect::<Vec<_>>();
12933
12934        let creases = ranges
12935            .into_iter()
12936            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12937            .collect();
12938
12939        self.fold_creases(creases, true, window, cx);
12940    }
12941
12942    pub fn fold_recursive(
12943        &mut self,
12944        _: &actions::FoldRecursive,
12945        window: &mut Window,
12946        cx: &mut Context<Self>,
12947    ) {
12948        let mut to_fold = Vec::new();
12949        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12950        let selections = self.selections.all_adjusted(cx);
12951
12952        for selection in selections {
12953            let range = selection.range().sorted();
12954            let buffer_start_row = range.start.row;
12955
12956            if range.start.row != range.end.row {
12957                let mut found = false;
12958                for row in range.start.row..=range.end.row {
12959                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12960                        found = true;
12961                        to_fold.push(crease);
12962                    }
12963                }
12964                if found {
12965                    continue;
12966                }
12967            }
12968
12969            for row in (0..=range.start.row).rev() {
12970                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12971                    if crease.range().end.row >= buffer_start_row {
12972                        to_fold.push(crease);
12973                    } else {
12974                        break;
12975                    }
12976                }
12977            }
12978        }
12979
12980        self.fold_creases(to_fold, true, window, cx);
12981    }
12982
12983    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12984        let buffer_row = fold_at.buffer_row;
12985        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12986
12987        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12988            let autoscroll = self
12989                .selections
12990                .all::<Point>(cx)
12991                .iter()
12992                .any(|selection| crease.range().overlaps(&selection.range()));
12993
12994            self.fold_creases(vec![crease], autoscroll, window, cx);
12995        }
12996    }
12997
12998    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12999        if self.is_singleton(cx) {
13000            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13001            let buffer = &display_map.buffer_snapshot;
13002            let selections = self.selections.all::<Point>(cx);
13003            let ranges = selections
13004                .iter()
13005                .map(|s| {
13006                    let range = s.display_range(&display_map).sorted();
13007                    let mut start = range.start.to_point(&display_map);
13008                    let mut end = range.end.to_point(&display_map);
13009                    start.column = 0;
13010                    end.column = buffer.line_len(MultiBufferRow(end.row));
13011                    start..end
13012                })
13013                .collect::<Vec<_>>();
13014
13015            self.unfold_ranges(&ranges, true, true, cx);
13016        } else {
13017            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13018            let buffer_ids: HashSet<_> = multi_buffer_snapshot
13019                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
13020                .map(|(snapshot, _, _)| snapshot.remote_id())
13021                .collect();
13022            for buffer_id in buffer_ids {
13023                self.unfold_buffer(buffer_id, cx);
13024            }
13025        }
13026    }
13027
13028    pub fn unfold_recursive(
13029        &mut self,
13030        _: &UnfoldRecursive,
13031        _window: &mut Window,
13032        cx: &mut Context<Self>,
13033    ) {
13034        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13035        let selections = self.selections.all::<Point>(cx);
13036        let ranges = selections
13037            .iter()
13038            .map(|s| {
13039                let mut range = s.display_range(&display_map).sorted();
13040                *range.start.column_mut() = 0;
13041                *range.end.column_mut() = display_map.line_len(range.end.row());
13042                let start = range.start.to_point(&display_map);
13043                let end = range.end.to_point(&display_map);
13044                start..end
13045            })
13046            .collect::<Vec<_>>();
13047
13048        self.unfold_ranges(&ranges, true, true, cx);
13049    }
13050
13051    pub fn unfold_at(
13052        &mut self,
13053        unfold_at: &UnfoldAt,
13054        _window: &mut Window,
13055        cx: &mut Context<Self>,
13056    ) {
13057        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13058
13059        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13060            ..Point::new(
13061                unfold_at.buffer_row.0,
13062                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13063            );
13064
13065        let autoscroll = self
13066            .selections
13067            .all::<Point>(cx)
13068            .iter()
13069            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13070
13071        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13072    }
13073
13074    pub fn unfold_all(
13075        &mut self,
13076        _: &actions::UnfoldAll,
13077        _window: &mut Window,
13078        cx: &mut Context<Self>,
13079    ) {
13080        if self.buffer.read(cx).is_singleton() {
13081            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13082            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13083        } else {
13084            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13085                editor
13086                    .update(&mut cx, |editor, cx| {
13087                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13088                            editor.unfold_buffer(buffer_id, cx);
13089                        }
13090                    })
13091                    .ok();
13092            });
13093        }
13094    }
13095
13096    pub fn fold_selected_ranges(
13097        &mut self,
13098        _: &FoldSelectedRanges,
13099        window: &mut Window,
13100        cx: &mut Context<Self>,
13101    ) {
13102        let selections = self.selections.all::<Point>(cx);
13103        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13104        let line_mode = self.selections.line_mode;
13105        let ranges = selections
13106            .into_iter()
13107            .map(|s| {
13108                if line_mode {
13109                    let start = Point::new(s.start.row, 0);
13110                    let end = Point::new(
13111                        s.end.row,
13112                        display_map
13113                            .buffer_snapshot
13114                            .line_len(MultiBufferRow(s.end.row)),
13115                    );
13116                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13117                } else {
13118                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13119                }
13120            })
13121            .collect::<Vec<_>>();
13122        self.fold_creases(ranges, true, window, cx);
13123    }
13124
13125    pub fn fold_ranges<T: ToOffset + Clone>(
13126        &mut self,
13127        ranges: Vec<Range<T>>,
13128        auto_scroll: bool,
13129        window: &mut Window,
13130        cx: &mut Context<Self>,
13131    ) {
13132        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13133        let ranges = ranges
13134            .into_iter()
13135            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13136            .collect::<Vec<_>>();
13137        self.fold_creases(ranges, auto_scroll, window, cx);
13138    }
13139
13140    pub fn fold_creases<T: ToOffset + Clone>(
13141        &mut self,
13142        creases: Vec<Crease<T>>,
13143        auto_scroll: bool,
13144        window: &mut Window,
13145        cx: &mut Context<Self>,
13146    ) {
13147        if creases.is_empty() {
13148            return;
13149        }
13150
13151        let mut buffers_affected = HashSet::default();
13152        let multi_buffer = self.buffer().read(cx);
13153        for crease in &creases {
13154            if let Some((_, buffer, _)) =
13155                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13156            {
13157                buffers_affected.insert(buffer.read(cx).remote_id());
13158            };
13159        }
13160
13161        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13162
13163        if auto_scroll {
13164            self.request_autoscroll(Autoscroll::fit(), cx);
13165        }
13166
13167        cx.notify();
13168
13169        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13170            // Clear diagnostics block when folding a range that contains it.
13171            let snapshot = self.snapshot(window, cx);
13172            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13173                drop(snapshot);
13174                self.active_diagnostics = Some(active_diagnostics);
13175                self.dismiss_diagnostics(cx);
13176            } else {
13177                self.active_diagnostics = Some(active_diagnostics);
13178            }
13179        }
13180
13181        self.scrollbar_marker_state.dirty = true;
13182    }
13183
13184    /// Removes any folds whose ranges intersect any of the given ranges.
13185    pub fn unfold_ranges<T: ToOffset + Clone>(
13186        &mut self,
13187        ranges: &[Range<T>],
13188        inclusive: bool,
13189        auto_scroll: bool,
13190        cx: &mut Context<Self>,
13191    ) {
13192        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13193            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13194        });
13195    }
13196
13197    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13198        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13199            return;
13200        }
13201        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13202        self.display_map
13203            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13204        cx.emit(EditorEvent::BufferFoldToggled {
13205            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13206            folded: true,
13207        });
13208        cx.notify();
13209    }
13210
13211    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13212        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13213            return;
13214        }
13215        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13216        self.display_map.update(cx, |display_map, cx| {
13217            display_map.unfold_buffer(buffer_id, cx);
13218        });
13219        cx.emit(EditorEvent::BufferFoldToggled {
13220            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13221            folded: false,
13222        });
13223        cx.notify();
13224    }
13225
13226    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13227        self.display_map.read(cx).is_buffer_folded(buffer)
13228    }
13229
13230    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13231        self.display_map.read(cx).folded_buffers()
13232    }
13233
13234    /// Removes any folds with the given ranges.
13235    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13236        &mut self,
13237        ranges: &[Range<T>],
13238        type_id: TypeId,
13239        auto_scroll: bool,
13240        cx: &mut Context<Self>,
13241    ) {
13242        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13243            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13244        });
13245    }
13246
13247    fn remove_folds_with<T: ToOffset + Clone>(
13248        &mut self,
13249        ranges: &[Range<T>],
13250        auto_scroll: bool,
13251        cx: &mut Context<Self>,
13252        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13253    ) {
13254        if ranges.is_empty() {
13255            return;
13256        }
13257
13258        let mut buffers_affected = HashSet::default();
13259        let multi_buffer = self.buffer().read(cx);
13260        for range in ranges {
13261            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13262                buffers_affected.insert(buffer.read(cx).remote_id());
13263            };
13264        }
13265
13266        self.display_map.update(cx, update);
13267
13268        if auto_scroll {
13269            self.request_autoscroll(Autoscroll::fit(), cx);
13270        }
13271
13272        cx.notify();
13273        self.scrollbar_marker_state.dirty = true;
13274        self.active_indent_guides_state.dirty = true;
13275    }
13276
13277    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13278        self.display_map.read(cx).fold_placeholder.clone()
13279    }
13280
13281    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13282        self.buffer.update(cx, |buffer, cx| {
13283            buffer.set_all_diff_hunks_expanded(cx);
13284        });
13285    }
13286
13287    pub fn expand_all_diff_hunks(
13288        &mut self,
13289        _: &ExpandAllDiffHunks,
13290        _window: &mut Window,
13291        cx: &mut Context<Self>,
13292    ) {
13293        self.buffer.update(cx, |buffer, cx| {
13294            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13295        });
13296    }
13297
13298    pub fn toggle_selected_diff_hunks(
13299        &mut self,
13300        _: &ToggleSelectedDiffHunks,
13301        _window: &mut Window,
13302        cx: &mut Context<Self>,
13303    ) {
13304        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13305        self.toggle_diff_hunks_in_ranges(ranges, cx);
13306    }
13307
13308    pub fn diff_hunks_in_ranges<'a>(
13309        &'a self,
13310        ranges: &'a [Range<Anchor>],
13311        buffer: &'a MultiBufferSnapshot,
13312    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13313        ranges.iter().flat_map(move |range| {
13314            let end_excerpt_id = range.end.excerpt_id;
13315            let range = range.to_point(buffer);
13316            let mut peek_end = range.end;
13317            if range.end.row < buffer.max_row().0 {
13318                peek_end = Point::new(range.end.row + 1, 0);
13319            }
13320            buffer
13321                .diff_hunks_in_range(range.start..peek_end)
13322                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13323        })
13324    }
13325
13326    pub fn has_stageable_diff_hunks_in_ranges(
13327        &self,
13328        ranges: &[Range<Anchor>],
13329        snapshot: &MultiBufferSnapshot,
13330    ) -> bool {
13331        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13332        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
13333    }
13334
13335    pub fn toggle_staged_selected_diff_hunks(
13336        &mut self,
13337        _: &::git::ToggleStaged,
13338        _window: &mut Window,
13339        cx: &mut Context<Self>,
13340    ) {
13341        let snapshot = self.buffer.read(cx).snapshot(cx);
13342        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13343        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13344        self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
13345    }
13346
13347    pub fn stage_and_next(
13348        &mut self,
13349        _: &::git::StageAndNext,
13350        window: &mut Window,
13351        cx: &mut Context<Self>,
13352    ) {
13353        self.do_stage_or_unstage_and_next(true, window, cx);
13354    }
13355
13356    pub fn unstage_and_next(
13357        &mut self,
13358        _: &::git::UnstageAndNext,
13359        window: &mut Window,
13360        cx: &mut Context<Self>,
13361    ) {
13362        self.do_stage_or_unstage_and_next(false, window, cx);
13363    }
13364
13365    pub fn stage_or_unstage_diff_hunks(
13366        &mut self,
13367        stage: bool,
13368        ranges: &[Range<Anchor>],
13369        cx: &mut Context<Self>,
13370    ) {
13371        let snapshot = self.buffer.read(cx).snapshot(cx);
13372        let Some(project) = &self.project else {
13373            return;
13374        };
13375
13376        let chunk_by = self
13377            .diff_hunks_in_ranges(&ranges, &snapshot)
13378            .chunk_by(|hunk| hunk.buffer_id);
13379        for (buffer_id, hunks) in &chunk_by {
13380            Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
13381        }
13382    }
13383
13384    fn do_stage_or_unstage_and_next(
13385        &mut self,
13386        stage: bool,
13387        window: &mut Window,
13388        cx: &mut Context<Self>,
13389    ) {
13390        let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13391        if ranges.iter().any(|range| range.start != range.end) {
13392            self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13393            return;
13394        }
13395
13396        if !self.buffer().read(cx).is_singleton() {
13397            if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13398                if buffer.read(cx).is_empty() {
13399                    let buffer = buffer.read(cx);
13400                    let Some(file) = buffer.file() else {
13401                        return;
13402                    };
13403                    let project_path = project::ProjectPath {
13404                        worktree_id: file.worktree_id(cx),
13405                        path: file.path().clone(),
13406                    };
13407                    let Some(project) = self.project.as_ref() else {
13408                        return;
13409                    };
13410                    let project = project.read(cx);
13411
13412                    let Some(repo) = project.git_store().read(cx).active_repository() else {
13413                        return;
13414                    };
13415
13416                    repo.update(cx, |repo, cx| {
13417                        let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13418                            return;
13419                        };
13420                        let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13421                            return;
13422                        };
13423                        if stage && status.status == FileStatus::Untracked {
13424                            repo.stage_entries(vec![repo_path], cx)
13425                                .detach_and_log_err(cx);
13426                            return;
13427                        }
13428                    })
13429                }
13430                ranges = vec![multi_buffer::Anchor::range_in_buffer(
13431                    excerpt_id,
13432                    buffer.read(cx).remote_id(),
13433                    range,
13434                )];
13435                self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13436                let snapshot = self.buffer().read(cx).snapshot(cx);
13437                let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13438                if point.row < snapshot.max_row().0 {
13439                    point.row += 1;
13440                    point.column = 0;
13441                    point = snapshot.clip_point(point, Bias::Right);
13442                    self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13443                        s.select_ranges([point..point]);
13444                    })
13445                }
13446                return;
13447            }
13448        }
13449        self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13450        self.go_to_next_hunk(&Default::default(), window, cx);
13451    }
13452
13453    fn do_stage_or_unstage(
13454        project: &Entity<Project>,
13455        stage: bool,
13456        buffer_id: BufferId,
13457        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13458        snapshot: &MultiBufferSnapshot,
13459        cx: &mut Context<Self>,
13460    ) {
13461        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13462            log::debug!("no buffer for id");
13463            return;
13464        };
13465        let buffer_snapshot = buffer.read(cx).snapshot();
13466        let Some((repo, path)) = project
13467            .read(cx)
13468            .repository_and_path_for_buffer_id(buffer_id, cx)
13469        else {
13470            log::debug!("no git repo for buffer id");
13471            return;
13472        };
13473        let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13474            log::debug!("no diff for buffer id");
13475            return;
13476        };
13477        let Some(secondary_diff) = diff.secondary_diff() else {
13478            log::debug!("no secondary diff for buffer id");
13479            return;
13480        };
13481
13482        let edits = diff.secondary_edits_for_stage_or_unstage(
13483            stage,
13484            hunks.filter_map(|hunk| {
13485                if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13486                    return None;
13487                } else if !stage
13488                    && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13489                {
13490                    return None;
13491                }
13492                Some((
13493                    hunk.diff_base_byte_range.clone(),
13494                    hunk.secondary_diff_base_byte_range.clone(),
13495                    hunk.buffer_range.clone(),
13496                ))
13497            }),
13498            &buffer_snapshot,
13499        );
13500
13501        let Some(index_base) = secondary_diff
13502            .base_text()
13503            .map(|snapshot| snapshot.text.as_rope().clone())
13504        else {
13505            log::debug!("no index base");
13506            return;
13507        };
13508        let index_buffer = cx.new(|cx| {
13509            Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
13510        });
13511        let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
13512            index_buffer.edit(edits, None, cx);
13513            index_buffer.snapshot().as_rope().to_string()
13514        });
13515        let new_index_text = if new_index_text.is_empty()
13516            && !stage
13517            && (diff.is_single_insertion
13518                || buffer_snapshot
13519                    .file()
13520                    .map_or(false, |file| file.disk_state() == DiskState::New))
13521        {
13522            log::debug!("removing from index");
13523            None
13524        } else {
13525            Some(new_index_text)
13526        };
13527        let buffer_store = project.read(cx).buffer_store().clone();
13528        buffer_store
13529            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13530            .detach_and_log_err(cx);
13531
13532        cx.background_spawn(
13533            repo.read(cx)
13534                .set_index_text(&path, new_index_text)
13535                .log_err(),
13536        )
13537        .detach();
13538    }
13539
13540    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13541        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13542        self.buffer
13543            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13544    }
13545
13546    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13547        self.buffer.update(cx, |buffer, cx| {
13548            let ranges = vec![Anchor::min()..Anchor::max()];
13549            if !buffer.all_diff_hunks_expanded()
13550                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13551            {
13552                buffer.collapse_diff_hunks(ranges, cx);
13553                true
13554            } else {
13555                false
13556            }
13557        })
13558    }
13559
13560    fn toggle_diff_hunks_in_ranges(
13561        &mut self,
13562        ranges: Vec<Range<Anchor>>,
13563        cx: &mut Context<'_, Editor>,
13564    ) {
13565        self.buffer.update(cx, |buffer, cx| {
13566            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13567            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13568        })
13569    }
13570
13571    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13572        self.buffer.update(cx, |buffer, cx| {
13573            let snapshot = buffer.snapshot(cx);
13574            let excerpt_id = range.end.excerpt_id;
13575            let point_range = range.to_point(&snapshot);
13576            let expand = !buffer.single_hunk_is_expanded(range, cx);
13577            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13578        })
13579    }
13580
13581    pub(crate) fn apply_all_diff_hunks(
13582        &mut self,
13583        _: &ApplyAllDiffHunks,
13584        window: &mut Window,
13585        cx: &mut Context<Self>,
13586    ) {
13587        let buffers = self.buffer.read(cx).all_buffers();
13588        for branch_buffer in buffers {
13589            branch_buffer.update(cx, |branch_buffer, cx| {
13590                branch_buffer.merge_into_base(Vec::new(), cx);
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(crate) fn apply_selected_diff_hunks(
13600        &mut self,
13601        _: &ApplyDiffHunk,
13602        window: &mut Window,
13603        cx: &mut Context<Self>,
13604    ) {
13605        let snapshot = self.snapshot(window, cx);
13606        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13607        let mut ranges_by_buffer = HashMap::default();
13608        self.transact(window, cx, |editor, _window, cx| {
13609            for hunk in hunks {
13610                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13611                    ranges_by_buffer
13612                        .entry(buffer.clone())
13613                        .or_insert_with(Vec::new)
13614                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13615                }
13616            }
13617
13618            for (buffer, ranges) in ranges_by_buffer {
13619                buffer.update(cx, |buffer, cx| {
13620                    buffer.merge_into_base(ranges, cx);
13621                });
13622            }
13623        });
13624
13625        if let Some(project) = self.project.clone() {
13626            self.save(true, project, window, cx).detach_and_log_err(cx);
13627        }
13628    }
13629
13630    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13631        if hovered != self.gutter_hovered {
13632            self.gutter_hovered = hovered;
13633            cx.notify();
13634        }
13635    }
13636
13637    pub fn insert_blocks(
13638        &mut self,
13639        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13640        autoscroll: Option<Autoscroll>,
13641        cx: &mut Context<Self>,
13642    ) -> Vec<CustomBlockId> {
13643        let blocks = self
13644            .display_map
13645            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13646        if let Some(autoscroll) = autoscroll {
13647            self.request_autoscroll(autoscroll, cx);
13648        }
13649        cx.notify();
13650        blocks
13651    }
13652
13653    pub fn resize_blocks(
13654        &mut self,
13655        heights: HashMap<CustomBlockId, u32>,
13656        autoscroll: Option<Autoscroll>,
13657        cx: &mut Context<Self>,
13658    ) {
13659        self.display_map
13660            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13661        if let Some(autoscroll) = autoscroll {
13662            self.request_autoscroll(autoscroll, cx);
13663        }
13664        cx.notify();
13665    }
13666
13667    pub fn replace_blocks(
13668        &mut self,
13669        renderers: HashMap<CustomBlockId, RenderBlock>,
13670        autoscroll: Option<Autoscroll>,
13671        cx: &mut Context<Self>,
13672    ) {
13673        self.display_map
13674            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13675        if let Some(autoscroll) = autoscroll {
13676            self.request_autoscroll(autoscroll, cx);
13677        }
13678        cx.notify();
13679    }
13680
13681    pub fn remove_blocks(
13682        &mut self,
13683        block_ids: HashSet<CustomBlockId>,
13684        autoscroll: Option<Autoscroll>,
13685        cx: &mut Context<Self>,
13686    ) {
13687        self.display_map.update(cx, |display_map, cx| {
13688            display_map.remove_blocks(block_ids, cx)
13689        });
13690        if let Some(autoscroll) = autoscroll {
13691            self.request_autoscroll(autoscroll, cx);
13692        }
13693        cx.notify();
13694    }
13695
13696    pub fn row_for_block(
13697        &self,
13698        block_id: CustomBlockId,
13699        cx: &mut Context<Self>,
13700    ) -> Option<DisplayRow> {
13701        self.display_map
13702            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13703    }
13704
13705    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13706        self.focused_block = Some(focused_block);
13707    }
13708
13709    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13710        self.focused_block.take()
13711    }
13712
13713    pub fn insert_creases(
13714        &mut self,
13715        creases: impl IntoIterator<Item = Crease<Anchor>>,
13716        cx: &mut Context<Self>,
13717    ) -> Vec<CreaseId> {
13718        self.display_map
13719            .update(cx, |map, cx| map.insert_creases(creases, cx))
13720    }
13721
13722    pub fn remove_creases(
13723        &mut self,
13724        ids: impl IntoIterator<Item = CreaseId>,
13725        cx: &mut Context<Self>,
13726    ) {
13727        self.display_map
13728            .update(cx, |map, cx| map.remove_creases(ids, cx));
13729    }
13730
13731    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13732        self.display_map
13733            .update(cx, |map, cx| map.snapshot(cx))
13734            .longest_row()
13735    }
13736
13737    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13738        self.display_map
13739            .update(cx, |map, cx| map.snapshot(cx))
13740            .max_point()
13741    }
13742
13743    pub fn text(&self, cx: &App) -> String {
13744        self.buffer.read(cx).read(cx).text()
13745    }
13746
13747    pub fn is_empty(&self, cx: &App) -> bool {
13748        self.buffer.read(cx).read(cx).is_empty()
13749    }
13750
13751    pub fn text_option(&self, cx: &App) -> Option<String> {
13752        let text = self.text(cx);
13753        let text = text.trim();
13754
13755        if text.is_empty() {
13756            return None;
13757        }
13758
13759        Some(text.to_string())
13760    }
13761
13762    pub fn set_text(
13763        &mut self,
13764        text: impl Into<Arc<str>>,
13765        window: &mut Window,
13766        cx: &mut Context<Self>,
13767    ) {
13768        self.transact(window, cx, |this, _, cx| {
13769            this.buffer
13770                .read(cx)
13771                .as_singleton()
13772                .expect("you can only call set_text on editors for singleton buffers")
13773                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13774        });
13775    }
13776
13777    pub fn display_text(&self, cx: &mut App) -> String {
13778        self.display_map
13779            .update(cx, |map, cx| map.snapshot(cx))
13780            .text()
13781    }
13782
13783    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13784        let mut wrap_guides = smallvec::smallvec![];
13785
13786        if self.show_wrap_guides == Some(false) {
13787            return wrap_guides;
13788        }
13789
13790        let settings = self.buffer.read(cx).settings_at(0, cx);
13791        if settings.show_wrap_guides {
13792            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13793                wrap_guides.push((soft_wrap as usize, true));
13794            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13795                wrap_guides.push((soft_wrap as usize, true));
13796            }
13797            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13798        }
13799
13800        wrap_guides
13801    }
13802
13803    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13804        let settings = self.buffer.read(cx).settings_at(0, cx);
13805        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13806        match mode {
13807            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13808                SoftWrap::None
13809            }
13810            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13811            language_settings::SoftWrap::PreferredLineLength => {
13812                SoftWrap::Column(settings.preferred_line_length)
13813            }
13814            language_settings::SoftWrap::Bounded => {
13815                SoftWrap::Bounded(settings.preferred_line_length)
13816            }
13817        }
13818    }
13819
13820    pub fn set_soft_wrap_mode(
13821        &mut self,
13822        mode: language_settings::SoftWrap,
13823
13824        cx: &mut Context<Self>,
13825    ) {
13826        self.soft_wrap_mode_override = Some(mode);
13827        cx.notify();
13828    }
13829
13830    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13831        self.text_style_refinement = Some(style);
13832    }
13833
13834    /// called by the Element so we know what style we were most recently rendered with.
13835    pub(crate) fn set_style(
13836        &mut self,
13837        style: EditorStyle,
13838        window: &mut Window,
13839        cx: &mut Context<Self>,
13840    ) {
13841        let rem_size = window.rem_size();
13842        self.display_map.update(cx, |map, cx| {
13843            map.set_font(
13844                style.text.font(),
13845                style.text.font_size.to_pixels(rem_size),
13846                cx,
13847            )
13848        });
13849        self.style = Some(style);
13850    }
13851
13852    pub fn style(&self) -> Option<&EditorStyle> {
13853        self.style.as_ref()
13854    }
13855
13856    // Called by the element. This method is not designed to be called outside of the editor
13857    // element's layout code because it does not notify when rewrapping is computed synchronously.
13858    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13859        self.display_map
13860            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13861    }
13862
13863    pub fn set_soft_wrap(&mut self) {
13864        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13865    }
13866
13867    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13868        if self.soft_wrap_mode_override.is_some() {
13869            self.soft_wrap_mode_override.take();
13870        } else {
13871            let soft_wrap = match self.soft_wrap_mode(cx) {
13872                SoftWrap::GitDiff => return,
13873                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13874                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13875                    language_settings::SoftWrap::None
13876                }
13877            };
13878            self.soft_wrap_mode_override = Some(soft_wrap);
13879        }
13880        cx.notify();
13881    }
13882
13883    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13884        let Some(workspace) = self.workspace() else {
13885            return;
13886        };
13887        let fs = workspace.read(cx).app_state().fs.clone();
13888        let current_show = TabBarSettings::get_global(cx).show;
13889        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13890            setting.show = Some(!current_show);
13891        });
13892    }
13893
13894    pub fn toggle_indent_guides(
13895        &mut self,
13896        _: &ToggleIndentGuides,
13897        _: &mut Window,
13898        cx: &mut Context<Self>,
13899    ) {
13900        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13901            self.buffer
13902                .read(cx)
13903                .settings_at(0, cx)
13904                .indent_guides
13905                .enabled
13906        });
13907        self.show_indent_guides = Some(!currently_enabled);
13908        cx.notify();
13909    }
13910
13911    fn should_show_indent_guides(&self) -> Option<bool> {
13912        self.show_indent_guides
13913    }
13914
13915    pub fn toggle_line_numbers(
13916        &mut self,
13917        _: &ToggleLineNumbers,
13918        _: &mut Window,
13919        cx: &mut Context<Self>,
13920    ) {
13921        let mut editor_settings = EditorSettings::get_global(cx).clone();
13922        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13923        EditorSettings::override_global(editor_settings, cx);
13924    }
13925
13926    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13927        self.use_relative_line_numbers
13928            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13929    }
13930
13931    pub fn toggle_relative_line_numbers(
13932        &mut self,
13933        _: &ToggleRelativeLineNumbers,
13934        _: &mut Window,
13935        cx: &mut Context<Self>,
13936    ) {
13937        let is_relative = self.should_use_relative_line_numbers(cx);
13938        self.set_relative_line_number(Some(!is_relative), cx)
13939    }
13940
13941    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13942        self.use_relative_line_numbers = is_relative;
13943        cx.notify();
13944    }
13945
13946    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13947        self.show_gutter = show_gutter;
13948        cx.notify();
13949    }
13950
13951    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13952        self.show_scrollbars = show_scrollbars;
13953        cx.notify();
13954    }
13955
13956    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13957        self.show_line_numbers = Some(show_line_numbers);
13958        cx.notify();
13959    }
13960
13961    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13962        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13963        cx.notify();
13964    }
13965
13966    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13967        self.show_code_actions = Some(show_code_actions);
13968        cx.notify();
13969    }
13970
13971    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13972        self.show_runnables = Some(show_runnables);
13973        cx.notify();
13974    }
13975
13976    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13977        if self.display_map.read(cx).masked != masked {
13978            self.display_map.update(cx, |map, _| map.masked = masked);
13979        }
13980        cx.notify()
13981    }
13982
13983    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13984        self.show_wrap_guides = Some(show_wrap_guides);
13985        cx.notify();
13986    }
13987
13988    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13989        self.show_indent_guides = Some(show_indent_guides);
13990        cx.notify();
13991    }
13992
13993    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13994        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13995            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13996                if let Some(dir) = file.abs_path(cx).parent() {
13997                    return Some(dir.to_owned());
13998                }
13999            }
14000
14001            if let Some(project_path) = buffer.read(cx).project_path(cx) {
14002                return Some(project_path.path.to_path_buf());
14003            }
14004        }
14005
14006        None
14007    }
14008
14009    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14010        self.active_excerpt(cx)?
14011            .1
14012            .read(cx)
14013            .file()
14014            .and_then(|f| f.as_local())
14015    }
14016
14017    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14018        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14019            let buffer = buffer.read(cx);
14020            if let Some(project_path) = buffer.project_path(cx) {
14021                let project = self.project.as_ref()?.read(cx);
14022                project.absolute_path(&project_path, cx)
14023            } else {
14024                buffer
14025                    .file()
14026                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14027            }
14028        })
14029    }
14030
14031    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14032        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14033            let project_path = buffer.read(cx).project_path(cx)?;
14034            let project = self.project.as_ref()?.read(cx);
14035            let entry = project.entry_for_path(&project_path, cx)?;
14036            let path = entry.path.to_path_buf();
14037            Some(path)
14038        })
14039    }
14040
14041    pub fn reveal_in_finder(
14042        &mut self,
14043        _: &RevealInFileManager,
14044        _window: &mut Window,
14045        cx: &mut Context<Self>,
14046    ) {
14047        if let Some(target) = self.target_file(cx) {
14048            cx.reveal_path(&target.abs_path(cx));
14049        }
14050    }
14051
14052    pub fn copy_path(
14053        &mut self,
14054        _: &zed_actions::workspace::CopyPath,
14055        _window: &mut Window,
14056        cx: &mut Context<Self>,
14057    ) {
14058        if let Some(path) = self.target_file_abs_path(cx) {
14059            if let Some(path) = path.to_str() {
14060                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14061            }
14062        }
14063    }
14064
14065    pub fn copy_relative_path(
14066        &mut self,
14067        _: &zed_actions::workspace::CopyRelativePath,
14068        _window: &mut Window,
14069        cx: &mut Context<Self>,
14070    ) {
14071        if let Some(path) = self.target_file_path(cx) {
14072            if let Some(path) = path.to_str() {
14073                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14074            }
14075        }
14076    }
14077
14078    pub fn copy_file_name_without_extension(
14079        &mut self,
14080        _: &CopyFileNameWithoutExtension,
14081        _: &mut Window,
14082        cx: &mut Context<Self>,
14083    ) {
14084        if let Some(file) = self.target_file(cx) {
14085            if let Some(file_stem) = file.path().file_stem() {
14086                if let Some(name) = file_stem.to_str() {
14087                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14088                }
14089            }
14090        }
14091    }
14092
14093    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14094        if let Some(file) = self.target_file(cx) {
14095            if let Some(file_name) = file.path().file_name() {
14096                if let Some(name) = file_name.to_str() {
14097                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14098                }
14099            }
14100        }
14101    }
14102
14103    pub fn toggle_git_blame(
14104        &mut self,
14105        _: &ToggleGitBlame,
14106        window: &mut Window,
14107        cx: &mut Context<Self>,
14108    ) {
14109        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14110
14111        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14112            self.start_git_blame(true, window, cx);
14113        }
14114
14115        cx.notify();
14116    }
14117
14118    pub fn toggle_git_blame_inline(
14119        &mut self,
14120        _: &ToggleGitBlameInline,
14121        window: &mut Window,
14122        cx: &mut Context<Self>,
14123    ) {
14124        self.toggle_git_blame_inline_internal(true, window, cx);
14125        cx.notify();
14126    }
14127
14128    pub fn git_blame_inline_enabled(&self) -> bool {
14129        self.git_blame_inline_enabled
14130    }
14131
14132    pub fn toggle_selection_menu(
14133        &mut self,
14134        _: &ToggleSelectionMenu,
14135        _: &mut Window,
14136        cx: &mut Context<Self>,
14137    ) {
14138        self.show_selection_menu = self
14139            .show_selection_menu
14140            .map(|show_selections_menu| !show_selections_menu)
14141            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14142
14143        cx.notify();
14144    }
14145
14146    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14147        self.show_selection_menu
14148            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14149    }
14150
14151    fn start_git_blame(
14152        &mut self,
14153        user_triggered: bool,
14154        window: &mut Window,
14155        cx: &mut Context<Self>,
14156    ) {
14157        if let Some(project) = self.project.as_ref() {
14158            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14159                return;
14160            };
14161
14162            if buffer.read(cx).file().is_none() {
14163                return;
14164            }
14165
14166            let focused = self.focus_handle(cx).contains_focused(window, cx);
14167
14168            let project = project.clone();
14169            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14170            self.blame_subscription =
14171                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14172            self.blame = Some(blame);
14173        }
14174    }
14175
14176    fn toggle_git_blame_inline_internal(
14177        &mut self,
14178        user_triggered: bool,
14179        window: &mut Window,
14180        cx: &mut Context<Self>,
14181    ) {
14182        if self.git_blame_inline_enabled {
14183            self.git_blame_inline_enabled = false;
14184            self.show_git_blame_inline = false;
14185            self.show_git_blame_inline_delay_task.take();
14186        } else {
14187            self.git_blame_inline_enabled = true;
14188            self.start_git_blame_inline(user_triggered, window, cx);
14189        }
14190
14191        cx.notify();
14192    }
14193
14194    fn start_git_blame_inline(
14195        &mut self,
14196        user_triggered: bool,
14197        window: &mut Window,
14198        cx: &mut Context<Self>,
14199    ) {
14200        self.start_git_blame(user_triggered, window, cx);
14201
14202        if ProjectSettings::get_global(cx)
14203            .git
14204            .inline_blame_delay()
14205            .is_some()
14206        {
14207            self.start_inline_blame_timer(window, cx);
14208        } else {
14209            self.show_git_blame_inline = true
14210        }
14211    }
14212
14213    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14214        self.blame.as_ref()
14215    }
14216
14217    pub fn show_git_blame_gutter(&self) -> bool {
14218        self.show_git_blame_gutter
14219    }
14220
14221    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14222        self.show_git_blame_gutter && self.has_blame_entries(cx)
14223    }
14224
14225    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14226        self.show_git_blame_inline
14227            && (self.focus_handle.is_focused(window)
14228                || self
14229                    .git_blame_inline_tooltip
14230                    .as_ref()
14231                    .and_then(|t| t.upgrade())
14232                    .is_some())
14233            && !self.newest_selection_head_on_empty_line(cx)
14234            && self.has_blame_entries(cx)
14235    }
14236
14237    fn has_blame_entries(&self, cx: &App) -> bool {
14238        self.blame()
14239            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14240    }
14241
14242    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14243        let cursor_anchor = self.selections.newest_anchor().head();
14244
14245        let snapshot = self.buffer.read(cx).snapshot(cx);
14246        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14247
14248        snapshot.line_len(buffer_row) == 0
14249    }
14250
14251    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14252        let buffer_and_selection = maybe!({
14253            let selection = self.selections.newest::<Point>(cx);
14254            let selection_range = selection.range();
14255
14256            let multi_buffer = self.buffer().read(cx);
14257            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14258            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14259
14260            let (buffer, range, _) = if selection.reversed {
14261                buffer_ranges.first()
14262            } else {
14263                buffer_ranges.last()
14264            }?;
14265
14266            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14267                ..text::ToPoint::to_point(&range.end, &buffer).row;
14268            Some((
14269                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14270                selection,
14271            ))
14272        });
14273
14274        let Some((buffer, selection)) = buffer_and_selection else {
14275            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14276        };
14277
14278        let Some(project) = self.project.as_ref() else {
14279            return Task::ready(Err(anyhow!("editor does not have project")));
14280        };
14281
14282        project.update(cx, |project, cx| {
14283            project.get_permalink_to_line(&buffer, selection, cx)
14284        })
14285    }
14286
14287    pub fn copy_permalink_to_line(
14288        &mut self,
14289        _: &CopyPermalinkToLine,
14290        window: &mut Window,
14291        cx: &mut Context<Self>,
14292    ) {
14293        let permalink_task = self.get_permalink_to_line(cx);
14294        let workspace = self.workspace();
14295
14296        cx.spawn_in(window, |_, mut cx| async move {
14297            match permalink_task.await {
14298                Ok(permalink) => {
14299                    cx.update(|_, cx| {
14300                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14301                    })
14302                    .ok();
14303                }
14304                Err(err) => {
14305                    let message = format!("Failed to copy permalink: {err}");
14306
14307                    Err::<(), anyhow::Error>(err).log_err();
14308
14309                    if let Some(workspace) = workspace {
14310                        workspace
14311                            .update_in(&mut cx, |workspace, _, cx| {
14312                                struct CopyPermalinkToLine;
14313
14314                                workspace.show_toast(
14315                                    Toast::new(
14316                                        NotificationId::unique::<CopyPermalinkToLine>(),
14317                                        message,
14318                                    ),
14319                                    cx,
14320                                )
14321                            })
14322                            .ok();
14323                    }
14324                }
14325            }
14326        })
14327        .detach();
14328    }
14329
14330    pub fn copy_file_location(
14331        &mut self,
14332        _: &CopyFileLocation,
14333        _: &mut Window,
14334        cx: &mut Context<Self>,
14335    ) {
14336        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14337        if let Some(file) = self.target_file(cx) {
14338            if let Some(path) = file.path().to_str() {
14339                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14340            }
14341        }
14342    }
14343
14344    pub fn open_permalink_to_line(
14345        &mut self,
14346        _: &OpenPermalinkToLine,
14347        window: &mut Window,
14348        cx: &mut Context<Self>,
14349    ) {
14350        let permalink_task = self.get_permalink_to_line(cx);
14351        let workspace = self.workspace();
14352
14353        cx.spawn_in(window, |_, mut cx| async move {
14354            match permalink_task.await {
14355                Ok(permalink) => {
14356                    cx.update(|_, cx| {
14357                        cx.open_url(permalink.as_ref());
14358                    })
14359                    .ok();
14360                }
14361                Err(err) => {
14362                    let message = format!("Failed to open permalink: {err}");
14363
14364                    Err::<(), anyhow::Error>(err).log_err();
14365
14366                    if let Some(workspace) = workspace {
14367                        workspace
14368                            .update(&mut cx, |workspace, cx| {
14369                                struct OpenPermalinkToLine;
14370
14371                                workspace.show_toast(
14372                                    Toast::new(
14373                                        NotificationId::unique::<OpenPermalinkToLine>(),
14374                                        message,
14375                                    ),
14376                                    cx,
14377                                )
14378                            })
14379                            .ok();
14380                    }
14381                }
14382            }
14383        })
14384        .detach();
14385    }
14386
14387    pub fn insert_uuid_v4(
14388        &mut self,
14389        _: &InsertUuidV4,
14390        window: &mut Window,
14391        cx: &mut Context<Self>,
14392    ) {
14393        self.insert_uuid(UuidVersion::V4, window, cx);
14394    }
14395
14396    pub fn insert_uuid_v7(
14397        &mut self,
14398        _: &InsertUuidV7,
14399        window: &mut Window,
14400        cx: &mut Context<Self>,
14401    ) {
14402        self.insert_uuid(UuidVersion::V7, window, cx);
14403    }
14404
14405    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14406        self.transact(window, cx, |this, window, cx| {
14407            let edits = this
14408                .selections
14409                .all::<Point>(cx)
14410                .into_iter()
14411                .map(|selection| {
14412                    let uuid = match version {
14413                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14414                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14415                    };
14416
14417                    (selection.range(), uuid.to_string())
14418                });
14419            this.edit(edits, cx);
14420            this.refresh_inline_completion(true, false, window, cx);
14421        });
14422    }
14423
14424    pub fn open_selections_in_multibuffer(
14425        &mut self,
14426        _: &OpenSelectionsInMultibuffer,
14427        window: &mut Window,
14428        cx: &mut Context<Self>,
14429    ) {
14430        let multibuffer = self.buffer.read(cx);
14431
14432        let Some(buffer) = multibuffer.as_singleton() else {
14433            return;
14434        };
14435
14436        let Some(workspace) = self.workspace() else {
14437            return;
14438        };
14439
14440        let locations = self
14441            .selections
14442            .disjoint_anchors()
14443            .iter()
14444            .map(|range| Location {
14445                buffer: buffer.clone(),
14446                range: range.start.text_anchor..range.end.text_anchor,
14447            })
14448            .collect::<Vec<_>>();
14449
14450        let title = multibuffer.title(cx).to_string();
14451
14452        cx.spawn_in(window, |_, mut cx| async move {
14453            workspace.update_in(&mut cx, |workspace, window, cx| {
14454                Self::open_locations_in_multibuffer(
14455                    workspace,
14456                    locations,
14457                    format!("Selections for '{title}'"),
14458                    false,
14459                    MultibufferSelectionMode::All,
14460                    window,
14461                    cx,
14462                );
14463            })
14464        })
14465        .detach();
14466    }
14467
14468    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14469    /// last highlight added will be used.
14470    ///
14471    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14472    pub fn highlight_rows<T: 'static>(
14473        &mut self,
14474        range: Range<Anchor>,
14475        color: Hsla,
14476        should_autoscroll: bool,
14477        cx: &mut Context<Self>,
14478    ) {
14479        let snapshot = self.buffer().read(cx).snapshot(cx);
14480        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14481        let ix = row_highlights.binary_search_by(|highlight| {
14482            Ordering::Equal
14483                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14484                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14485        });
14486
14487        if let Err(mut ix) = ix {
14488            let index = post_inc(&mut self.highlight_order);
14489
14490            // If this range intersects with the preceding highlight, then merge it with
14491            // the preceding highlight. Otherwise insert a new highlight.
14492            let mut merged = false;
14493            if ix > 0 {
14494                let prev_highlight = &mut row_highlights[ix - 1];
14495                if prev_highlight
14496                    .range
14497                    .end
14498                    .cmp(&range.start, &snapshot)
14499                    .is_ge()
14500                {
14501                    ix -= 1;
14502                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14503                        prev_highlight.range.end = range.end;
14504                    }
14505                    merged = true;
14506                    prev_highlight.index = index;
14507                    prev_highlight.color = color;
14508                    prev_highlight.should_autoscroll = should_autoscroll;
14509                }
14510            }
14511
14512            if !merged {
14513                row_highlights.insert(
14514                    ix,
14515                    RowHighlight {
14516                        range: range.clone(),
14517                        index,
14518                        color,
14519                        should_autoscroll,
14520                    },
14521                );
14522            }
14523
14524            // If any of the following highlights intersect with this one, merge them.
14525            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14526                let highlight = &row_highlights[ix];
14527                if next_highlight
14528                    .range
14529                    .start
14530                    .cmp(&highlight.range.end, &snapshot)
14531                    .is_le()
14532                {
14533                    if next_highlight
14534                        .range
14535                        .end
14536                        .cmp(&highlight.range.end, &snapshot)
14537                        .is_gt()
14538                    {
14539                        row_highlights[ix].range.end = next_highlight.range.end;
14540                    }
14541                    row_highlights.remove(ix + 1);
14542                } else {
14543                    break;
14544                }
14545            }
14546        }
14547    }
14548
14549    /// Remove any highlighted row ranges of the given type that intersect the
14550    /// given ranges.
14551    pub fn remove_highlighted_rows<T: 'static>(
14552        &mut self,
14553        ranges_to_remove: Vec<Range<Anchor>>,
14554        cx: &mut Context<Self>,
14555    ) {
14556        let snapshot = self.buffer().read(cx).snapshot(cx);
14557        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14558        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14559        row_highlights.retain(|highlight| {
14560            while let Some(range_to_remove) = ranges_to_remove.peek() {
14561                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14562                    Ordering::Less | Ordering::Equal => {
14563                        ranges_to_remove.next();
14564                    }
14565                    Ordering::Greater => {
14566                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14567                            Ordering::Less | Ordering::Equal => {
14568                                return false;
14569                            }
14570                            Ordering::Greater => break,
14571                        }
14572                    }
14573                }
14574            }
14575
14576            true
14577        })
14578    }
14579
14580    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14581    pub fn clear_row_highlights<T: 'static>(&mut self) {
14582        self.highlighted_rows.remove(&TypeId::of::<T>());
14583    }
14584
14585    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14586    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14587        self.highlighted_rows
14588            .get(&TypeId::of::<T>())
14589            .map_or(&[] as &[_], |vec| vec.as_slice())
14590            .iter()
14591            .map(|highlight| (highlight.range.clone(), highlight.color))
14592    }
14593
14594    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14595    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14596    /// Allows to ignore certain kinds of highlights.
14597    pub fn highlighted_display_rows(
14598        &self,
14599        window: &mut Window,
14600        cx: &mut App,
14601    ) -> BTreeMap<DisplayRow, Background> {
14602        let snapshot = self.snapshot(window, cx);
14603        let mut used_highlight_orders = HashMap::default();
14604        self.highlighted_rows
14605            .iter()
14606            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14607            .fold(
14608                BTreeMap::<DisplayRow, Background>::new(),
14609                |mut unique_rows, highlight| {
14610                    let start = highlight.range.start.to_display_point(&snapshot);
14611                    let end = highlight.range.end.to_display_point(&snapshot);
14612                    let start_row = start.row().0;
14613                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14614                        && end.column() == 0
14615                    {
14616                        end.row().0.saturating_sub(1)
14617                    } else {
14618                        end.row().0
14619                    };
14620                    for row in start_row..=end_row {
14621                        let used_index =
14622                            used_highlight_orders.entry(row).or_insert(highlight.index);
14623                        if highlight.index >= *used_index {
14624                            *used_index = highlight.index;
14625                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14626                        }
14627                    }
14628                    unique_rows
14629                },
14630            )
14631    }
14632
14633    pub fn highlighted_display_row_for_autoscroll(
14634        &self,
14635        snapshot: &DisplaySnapshot,
14636    ) -> Option<DisplayRow> {
14637        self.highlighted_rows
14638            .values()
14639            .flat_map(|highlighted_rows| highlighted_rows.iter())
14640            .filter_map(|highlight| {
14641                if highlight.should_autoscroll {
14642                    Some(highlight.range.start.to_display_point(snapshot).row())
14643                } else {
14644                    None
14645                }
14646            })
14647            .min()
14648    }
14649
14650    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14651        self.highlight_background::<SearchWithinRange>(
14652            ranges,
14653            |colors| colors.editor_document_highlight_read_background,
14654            cx,
14655        )
14656    }
14657
14658    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14659        self.breadcrumb_header = Some(new_header);
14660    }
14661
14662    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14663        self.clear_background_highlights::<SearchWithinRange>(cx);
14664    }
14665
14666    pub fn highlight_background<T: 'static>(
14667        &mut self,
14668        ranges: &[Range<Anchor>],
14669        color_fetcher: fn(&ThemeColors) -> Hsla,
14670        cx: &mut Context<Self>,
14671    ) {
14672        self.background_highlights
14673            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14674        self.scrollbar_marker_state.dirty = true;
14675        cx.notify();
14676    }
14677
14678    pub fn clear_background_highlights<T: 'static>(
14679        &mut self,
14680        cx: &mut Context<Self>,
14681    ) -> Option<BackgroundHighlight> {
14682        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14683        if !text_highlights.1.is_empty() {
14684            self.scrollbar_marker_state.dirty = true;
14685            cx.notify();
14686        }
14687        Some(text_highlights)
14688    }
14689
14690    pub fn highlight_gutter<T: 'static>(
14691        &mut self,
14692        ranges: &[Range<Anchor>],
14693        color_fetcher: fn(&App) -> Hsla,
14694        cx: &mut Context<Self>,
14695    ) {
14696        self.gutter_highlights
14697            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14698        cx.notify();
14699    }
14700
14701    pub fn clear_gutter_highlights<T: 'static>(
14702        &mut self,
14703        cx: &mut Context<Self>,
14704    ) -> Option<GutterHighlight> {
14705        cx.notify();
14706        self.gutter_highlights.remove(&TypeId::of::<T>())
14707    }
14708
14709    #[cfg(feature = "test-support")]
14710    pub fn all_text_background_highlights(
14711        &self,
14712        window: &mut Window,
14713        cx: &mut Context<Self>,
14714    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14715        let snapshot = self.snapshot(window, cx);
14716        let buffer = &snapshot.buffer_snapshot;
14717        let start = buffer.anchor_before(0);
14718        let end = buffer.anchor_after(buffer.len());
14719        let theme = cx.theme().colors();
14720        self.background_highlights_in_range(start..end, &snapshot, theme)
14721    }
14722
14723    #[cfg(feature = "test-support")]
14724    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14725        let snapshot = self.buffer().read(cx).snapshot(cx);
14726
14727        let highlights = self
14728            .background_highlights
14729            .get(&TypeId::of::<items::BufferSearchHighlights>());
14730
14731        if let Some((_color, ranges)) = highlights {
14732            ranges
14733                .iter()
14734                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14735                .collect_vec()
14736        } else {
14737            vec![]
14738        }
14739    }
14740
14741    fn document_highlights_for_position<'a>(
14742        &'a self,
14743        position: Anchor,
14744        buffer: &'a MultiBufferSnapshot,
14745    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14746        let read_highlights = self
14747            .background_highlights
14748            .get(&TypeId::of::<DocumentHighlightRead>())
14749            .map(|h| &h.1);
14750        let write_highlights = self
14751            .background_highlights
14752            .get(&TypeId::of::<DocumentHighlightWrite>())
14753            .map(|h| &h.1);
14754        let left_position = position.bias_left(buffer);
14755        let right_position = position.bias_right(buffer);
14756        read_highlights
14757            .into_iter()
14758            .chain(write_highlights)
14759            .flat_map(move |ranges| {
14760                let start_ix = match ranges.binary_search_by(|probe| {
14761                    let cmp = probe.end.cmp(&left_position, buffer);
14762                    if cmp.is_ge() {
14763                        Ordering::Greater
14764                    } else {
14765                        Ordering::Less
14766                    }
14767                }) {
14768                    Ok(i) | Err(i) => i,
14769                };
14770
14771                ranges[start_ix..]
14772                    .iter()
14773                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14774            })
14775    }
14776
14777    pub fn has_background_highlights<T: 'static>(&self) -> bool {
14778        self.background_highlights
14779            .get(&TypeId::of::<T>())
14780            .map_or(false, |(_, highlights)| !highlights.is_empty())
14781    }
14782
14783    pub fn background_highlights_in_range(
14784        &self,
14785        search_range: Range<Anchor>,
14786        display_snapshot: &DisplaySnapshot,
14787        theme: &ThemeColors,
14788    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14789        let mut results = Vec::new();
14790        for (color_fetcher, ranges) in self.background_highlights.values() {
14791            let color = color_fetcher(theme);
14792            let start_ix = match ranges.binary_search_by(|probe| {
14793                let cmp = probe
14794                    .end
14795                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14796                if cmp.is_gt() {
14797                    Ordering::Greater
14798                } else {
14799                    Ordering::Less
14800                }
14801            }) {
14802                Ok(i) | Err(i) => i,
14803            };
14804            for range in &ranges[start_ix..] {
14805                if range
14806                    .start
14807                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14808                    .is_ge()
14809                {
14810                    break;
14811                }
14812
14813                let start = range.start.to_display_point(display_snapshot);
14814                let end = range.end.to_display_point(display_snapshot);
14815                results.push((start..end, color))
14816            }
14817        }
14818        results
14819    }
14820
14821    pub fn background_highlight_row_ranges<T: 'static>(
14822        &self,
14823        search_range: Range<Anchor>,
14824        display_snapshot: &DisplaySnapshot,
14825        count: usize,
14826    ) -> Vec<RangeInclusive<DisplayPoint>> {
14827        let mut results = Vec::new();
14828        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14829            return vec![];
14830        };
14831
14832        let start_ix = match ranges.binary_search_by(|probe| {
14833            let cmp = probe
14834                .end
14835                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14836            if cmp.is_gt() {
14837                Ordering::Greater
14838            } else {
14839                Ordering::Less
14840            }
14841        }) {
14842            Ok(i) | Err(i) => i,
14843        };
14844        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14845            if let (Some(start_display), Some(end_display)) = (start, end) {
14846                results.push(
14847                    start_display.to_display_point(display_snapshot)
14848                        ..=end_display.to_display_point(display_snapshot),
14849                );
14850            }
14851        };
14852        let mut start_row: Option<Point> = None;
14853        let mut end_row: Option<Point> = None;
14854        if ranges.len() > count {
14855            return Vec::new();
14856        }
14857        for range in &ranges[start_ix..] {
14858            if range
14859                .start
14860                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14861                .is_ge()
14862            {
14863                break;
14864            }
14865            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14866            if let Some(current_row) = &end_row {
14867                if end.row == current_row.row {
14868                    continue;
14869                }
14870            }
14871            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14872            if start_row.is_none() {
14873                assert_eq!(end_row, None);
14874                start_row = Some(start);
14875                end_row = Some(end);
14876                continue;
14877            }
14878            if let Some(current_end) = end_row.as_mut() {
14879                if start.row > current_end.row + 1 {
14880                    push_region(start_row, end_row);
14881                    start_row = Some(start);
14882                    end_row = Some(end);
14883                } else {
14884                    // Merge two hunks.
14885                    *current_end = end;
14886                }
14887            } else {
14888                unreachable!();
14889            }
14890        }
14891        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14892        push_region(start_row, end_row);
14893        results
14894    }
14895
14896    pub fn gutter_highlights_in_range(
14897        &self,
14898        search_range: Range<Anchor>,
14899        display_snapshot: &DisplaySnapshot,
14900        cx: &App,
14901    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14902        let mut results = Vec::new();
14903        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14904            let color = color_fetcher(cx);
14905            let start_ix = match ranges.binary_search_by(|probe| {
14906                let cmp = probe
14907                    .end
14908                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14909                if cmp.is_gt() {
14910                    Ordering::Greater
14911                } else {
14912                    Ordering::Less
14913                }
14914            }) {
14915                Ok(i) | Err(i) => i,
14916            };
14917            for range in &ranges[start_ix..] {
14918                if range
14919                    .start
14920                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14921                    .is_ge()
14922                {
14923                    break;
14924                }
14925
14926                let start = range.start.to_display_point(display_snapshot);
14927                let end = range.end.to_display_point(display_snapshot);
14928                results.push((start..end, color))
14929            }
14930        }
14931        results
14932    }
14933
14934    /// Get the text ranges corresponding to the redaction query
14935    pub fn redacted_ranges(
14936        &self,
14937        search_range: Range<Anchor>,
14938        display_snapshot: &DisplaySnapshot,
14939        cx: &App,
14940    ) -> Vec<Range<DisplayPoint>> {
14941        display_snapshot
14942            .buffer_snapshot
14943            .redacted_ranges(search_range, |file| {
14944                if let Some(file) = file {
14945                    file.is_private()
14946                        && EditorSettings::get(
14947                            Some(SettingsLocation {
14948                                worktree_id: file.worktree_id(cx),
14949                                path: file.path().as_ref(),
14950                            }),
14951                            cx,
14952                        )
14953                        .redact_private_values
14954                } else {
14955                    false
14956                }
14957            })
14958            .map(|range| {
14959                range.start.to_display_point(display_snapshot)
14960                    ..range.end.to_display_point(display_snapshot)
14961            })
14962            .collect()
14963    }
14964
14965    pub fn highlight_text<T: 'static>(
14966        &mut self,
14967        ranges: Vec<Range<Anchor>>,
14968        style: HighlightStyle,
14969        cx: &mut Context<Self>,
14970    ) {
14971        self.display_map.update(cx, |map, _| {
14972            map.highlight_text(TypeId::of::<T>(), ranges, style)
14973        });
14974        cx.notify();
14975    }
14976
14977    pub(crate) fn highlight_inlays<T: 'static>(
14978        &mut self,
14979        highlights: Vec<InlayHighlight>,
14980        style: HighlightStyle,
14981        cx: &mut Context<Self>,
14982    ) {
14983        self.display_map.update(cx, |map, _| {
14984            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14985        });
14986        cx.notify();
14987    }
14988
14989    pub fn text_highlights<'a, T: 'static>(
14990        &'a self,
14991        cx: &'a App,
14992    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14993        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14994    }
14995
14996    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14997        let cleared = self
14998            .display_map
14999            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15000        if cleared {
15001            cx.notify();
15002        }
15003    }
15004
15005    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15006        (self.read_only(cx) || self.blink_manager.read(cx).visible())
15007            && self.focus_handle.is_focused(window)
15008    }
15009
15010    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15011        self.show_cursor_when_unfocused = is_enabled;
15012        cx.notify();
15013    }
15014
15015    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15016        cx.notify();
15017    }
15018
15019    fn on_buffer_event(
15020        &mut self,
15021        multibuffer: &Entity<MultiBuffer>,
15022        event: &multi_buffer::Event,
15023        window: &mut Window,
15024        cx: &mut Context<Self>,
15025    ) {
15026        match event {
15027            multi_buffer::Event::Edited {
15028                singleton_buffer_edited,
15029                edited_buffer: buffer_edited,
15030            } => {
15031                self.scrollbar_marker_state.dirty = true;
15032                self.active_indent_guides_state.dirty = true;
15033                self.refresh_active_diagnostics(cx);
15034                self.refresh_code_actions(window, cx);
15035                if self.has_active_inline_completion() {
15036                    self.update_visible_inline_completion(window, cx);
15037                }
15038                if let Some(buffer) = buffer_edited {
15039                    let buffer_id = buffer.read(cx).remote_id();
15040                    if !self.registered_buffers.contains_key(&buffer_id) {
15041                        if let Some(project) = self.project.as_ref() {
15042                            project.update(cx, |project, cx| {
15043                                self.registered_buffers.insert(
15044                                    buffer_id,
15045                                    project.register_buffer_with_language_servers(&buffer, cx),
15046                                );
15047                            })
15048                        }
15049                    }
15050                }
15051                cx.emit(EditorEvent::BufferEdited);
15052                cx.emit(SearchEvent::MatchesInvalidated);
15053                if *singleton_buffer_edited {
15054                    if let Some(project) = &self.project {
15055                        #[allow(clippy::mutable_key_type)]
15056                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15057                            multibuffer
15058                                .all_buffers()
15059                                .into_iter()
15060                                .filter_map(|buffer| {
15061                                    buffer.update(cx, |buffer, cx| {
15062                                        let language = buffer.language()?;
15063                                        let should_discard = project.update(cx, |project, cx| {
15064                                            project.is_local()
15065                                                && !project.has_language_servers_for(buffer, cx)
15066                                        });
15067                                        should_discard.not().then_some(language.clone())
15068                                    })
15069                                })
15070                                .collect::<HashSet<_>>()
15071                        });
15072                        if !languages_affected.is_empty() {
15073                            self.refresh_inlay_hints(
15074                                InlayHintRefreshReason::BufferEdited(languages_affected),
15075                                cx,
15076                            );
15077                        }
15078                    }
15079                }
15080
15081                let Some(project) = &self.project else { return };
15082                let (telemetry, is_via_ssh) = {
15083                    let project = project.read(cx);
15084                    let telemetry = project.client().telemetry().clone();
15085                    let is_via_ssh = project.is_via_ssh();
15086                    (telemetry, is_via_ssh)
15087                };
15088                refresh_linked_ranges(self, window, cx);
15089                telemetry.log_edit_event("editor", is_via_ssh);
15090            }
15091            multi_buffer::Event::ExcerptsAdded {
15092                buffer,
15093                predecessor,
15094                excerpts,
15095            } => {
15096                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15097                let buffer_id = buffer.read(cx).remote_id();
15098                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15099                    if let Some(project) = &self.project {
15100                        get_uncommitted_diff_for_buffer(
15101                            project,
15102                            [buffer.clone()],
15103                            self.buffer.clone(),
15104                            cx,
15105                        )
15106                        .detach();
15107                    }
15108                }
15109                cx.emit(EditorEvent::ExcerptsAdded {
15110                    buffer: buffer.clone(),
15111                    predecessor: *predecessor,
15112                    excerpts: excerpts.clone(),
15113                });
15114                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15115            }
15116            multi_buffer::Event::ExcerptsRemoved { ids } => {
15117                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15118                let buffer = self.buffer.read(cx);
15119                self.registered_buffers
15120                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15121                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15122            }
15123            multi_buffer::Event::ExcerptsEdited { ids } => {
15124                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15125            }
15126            multi_buffer::Event::ExcerptsExpanded { ids } => {
15127                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15128                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15129            }
15130            multi_buffer::Event::Reparsed(buffer_id) => {
15131                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15132
15133                cx.emit(EditorEvent::Reparsed(*buffer_id));
15134            }
15135            multi_buffer::Event::DiffHunksToggled => {
15136                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15137            }
15138            multi_buffer::Event::LanguageChanged(buffer_id) => {
15139                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15140                cx.emit(EditorEvent::Reparsed(*buffer_id));
15141                cx.notify();
15142            }
15143            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15144            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15145            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15146                cx.emit(EditorEvent::TitleChanged)
15147            }
15148            // multi_buffer::Event::DiffBaseChanged => {
15149            //     self.scrollbar_marker_state.dirty = true;
15150            //     cx.emit(EditorEvent::DiffBaseChanged);
15151            //     cx.notify();
15152            // }
15153            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15154            multi_buffer::Event::DiagnosticsUpdated => {
15155                self.refresh_active_diagnostics(cx);
15156                self.refresh_inline_diagnostics(true, window, cx);
15157                self.scrollbar_marker_state.dirty = true;
15158                cx.notify();
15159            }
15160            _ => {}
15161        };
15162    }
15163
15164    fn on_display_map_changed(
15165        &mut self,
15166        _: Entity<DisplayMap>,
15167        _: &mut Window,
15168        cx: &mut Context<Self>,
15169    ) {
15170        cx.notify();
15171    }
15172
15173    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15174        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15175        self.update_edit_prediction_settings(cx);
15176        self.refresh_inline_completion(true, false, window, cx);
15177        self.refresh_inlay_hints(
15178            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15179                self.selections.newest_anchor().head(),
15180                &self.buffer.read(cx).snapshot(cx),
15181                cx,
15182            )),
15183            cx,
15184        );
15185
15186        let old_cursor_shape = self.cursor_shape;
15187
15188        {
15189            let editor_settings = EditorSettings::get_global(cx);
15190            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15191            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15192            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15193        }
15194
15195        if old_cursor_shape != self.cursor_shape {
15196            cx.emit(EditorEvent::CursorShapeChanged);
15197        }
15198
15199        let project_settings = ProjectSettings::get_global(cx);
15200        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15201
15202        if self.mode == EditorMode::Full {
15203            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15204            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15205            if self.show_inline_diagnostics != show_inline_diagnostics {
15206                self.show_inline_diagnostics = show_inline_diagnostics;
15207                self.refresh_inline_diagnostics(false, window, cx);
15208            }
15209
15210            if self.git_blame_inline_enabled != inline_blame_enabled {
15211                self.toggle_git_blame_inline_internal(false, window, cx);
15212            }
15213        }
15214
15215        cx.notify();
15216    }
15217
15218    pub fn set_searchable(&mut self, searchable: bool) {
15219        self.searchable = searchable;
15220    }
15221
15222    pub fn searchable(&self) -> bool {
15223        self.searchable
15224    }
15225
15226    fn open_proposed_changes_editor(
15227        &mut self,
15228        _: &OpenProposedChangesEditor,
15229        window: &mut Window,
15230        cx: &mut Context<Self>,
15231    ) {
15232        let Some(workspace) = self.workspace() else {
15233            cx.propagate();
15234            return;
15235        };
15236
15237        let selections = self.selections.all::<usize>(cx);
15238        let multi_buffer = self.buffer.read(cx);
15239        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15240        let mut new_selections_by_buffer = HashMap::default();
15241        for selection in selections {
15242            for (buffer, range, _) in
15243                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15244            {
15245                let mut range = range.to_point(buffer);
15246                range.start.column = 0;
15247                range.end.column = buffer.line_len(range.end.row);
15248                new_selections_by_buffer
15249                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15250                    .or_insert(Vec::new())
15251                    .push(range)
15252            }
15253        }
15254
15255        let proposed_changes_buffers = new_selections_by_buffer
15256            .into_iter()
15257            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15258            .collect::<Vec<_>>();
15259        let proposed_changes_editor = cx.new(|cx| {
15260            ProposedChangesEditor::new(
15261                "Proposed changes",
15262                proposed_changes_buffers,
15263                self.project.clone(),
15264                window,
15265                cx,
15266            )
15267        });
15268
15269        window.defer(cx, move |window, cx| {
15270            workspace.update(cx, |workspace, cx| {
15271                workspace.active_pane().update(cx, |pane, cx| {
15272                    pane.add_item(
15273                        Box::new(proposed_changes_editor),
15274                        true,
15275                        true,
15276                        None,
15277                        window,
15278                        cx,
15279                    );
15280                });
15281            });
15282        });
15283    }
15284
15285    pub fn open_excerpts_in_split(
15286        &mut self,
15287        _: &OpenExcerptsSplit,
15288        window: &mut Window,
15289        cx: &mut Context<Self>,
15290    ) {
15291        self.open_excerpts_common(None, true, window, cx)
15292    }
15293
15294    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15295        self.open_excerpts_common(None, false, window, cx)
15296    }
15297
15298    fn open_excerpts_common(
15299        &mut self,
15300        jump_data: Option<JumpData>,
15301        split: bool,
15302        window: &mut Window,
15303        cx: &mut Context<Self>,
15304    ) {
15305        let Some(workspace) = self.workspace() else {
15306            cx.propagate();
15307            return;
15308        };
15309
15310        if self.buffer.read(cx).is_singleton() {
15311            cx.propagate();
15312            return;
15313        }
15314
15315        let mut new_selections_by_buffer = HashMap::default();
15316        match &jump_data {
15317            Some(JumpData::MultiBufferPoint {
15318                excerpt_id,
15319                position,
15320                anchor,
15321                line_offset_from_top,
15322            }) => {
15323                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15324                if let Some(buffer) = multi_buffer_snapshot
15325                    .buffer_id_for_excerpt(*excerpt_id)
15326                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15327                {
15328                    let buffer_snapshot = buffer.read(cx).snapshot();
15329                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15330                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15331                    } else {
15332                        buffer_snapshot.clip_point(*position, Bias::Left)
15333                    };
15334                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15335                    new_selections_by_buffer.insert(
15336                        buffer,
15337                        (
15338                            vec![jump_to_offset..jump_to_offset],
15339                            Some(*line_offset_from_top),
15340                        ),
15341                    );
15342                }
15343            }
15344            Some(JumpData::MultiBufferRow {
15345                row,
15346                line_offset_from_top,
15347            }) => {
15348                let point = MultiBufferPoint::new(row.0, 0);
15349                if let Some((buffer, buffer_point, _)) =
15350                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15351                {
15352                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15353                    new_selections_by_buffer
15354                        .entry(buffer)
15355                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15356                        .0
15357                        .push(buffer_offset..buffer_offset)
15358                }
15359            }
15360            None => {
15361                let selections = self.selections.all::<usize>(cx);
15362                let multi_buffer = self.buffer.read(cx);
15363                for selection in selections {
15364                    for (snapshot, range, _, anchor) in multi_buffer
15365                        .snapshot(cx)
15366                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15367                    {
15368                        if let Some(anchor) = anchor {
15369                            // selection is in a deleted hunk
15370                            let Some(buffer_id) = anchor.buffer_id else {
15371                                continue;
15372                            };
15373                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15374                                continue;
15375                            };
15376                            let offset = text::ToOffset::to_offset(
15377                                &anchor.text_anchor,
15378                                &buffer_handle.read(cx).snapshot(),
15379                            );
15380                            let range = offset..offset;
15381                            new_selections_by_buffer
15382                                .entry(buffer_handle)
15383                                .or_insert((Vec::new(), None))
15384                                .0
15385                                .push(range)
15386                        } else {
15387                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15388                            else {
15389                                continue;
15390                            };
15391                            new_selections_by_buffer
15392                                .entry(buffer_handle)
15393                                .or_insert((Vec::new(), None))
15394                                .0
15395                                .push(range)
15396                        }
15397                    }
15398                }
15399            }
15400        }
15401
15402        if new_selections_by_buffer.is_empty() {
15403            return;
15404        }
15405
15406        // We defer the pane interaction because we ourselves are a workspace item
15407        // and activating a new item causes the pane to call a method on us reentrantly,
15408        // which panics if we're on the stack.
15409        window.defer(cx, move |window, cx| {
15410            workspace.update(cx, |workspace, cx| {
15411                let pane = if split {
15412                    workspace.adjacent_pane(window, cx)
15413                } else {
15414                    workspace.active_pane().clone()
15415                };
15416
15417                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15418                    let editor = buffer
15419                        .read(cx)
15420                        .file()
15421                        .is_none()
15422                        .then(|| {
15423                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15424                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15425                            // Instead, we try to activate the existing editor in the pane first.
15426                            let (editor, pane_item_index) =
15427                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15428                                    let editor = item.downcast::<Editor>()?;
15429                                    let singleton_buffer =
15430                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15431                                    if singleton_buffer == buffer {
15432                                        Some((editor, i))
15433                                    } else {
15434                                        None
15435                                    }
15436                                })?;
15437                            pane.update(cx, |pane, cx| {
15438                                pane.activate_item(pane_item_index, true, true, window, cx)
15439                            });
15440                            Some(editor)
15441                        })
15442                        .flatten()
15443                        .unwrap_or_else(|| {
15444                            workspace.open_project_item::<Self>(
15445                                pane.clone(),
15446                                buffer,
15447                                true,
15448                                true,
15449                                window,
15450                                cx,
15451                            )
15452                        });
15453
15454                    editor.update(cx, |editor, cx| {
15455                        let autoscroll = match scroll_offset {
15456                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15457                            None => Autoscroll::newest(),
15458                        };
15459                        let nav_history = editor.nav_history.take();
15460                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15461                            s.select_ranges(ranges);
15462                        });
15463                        editor.nav_history = nav_history;
15464                    });
15465                }
15466            })
15467        });
15468    }
15469
15470    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15471        let snapshot = self.buffer.read(cx).read(cx);
15472        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15473        Some(
15474            ranges
15475                .iter()
15476                .map(move |range| {
15477                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15478                })
15479                .collect(),
15480        )
15481    }
15482
15483    fn selection_replacement_ranges(
15484        &self,
15485        range: Range<OffsetUtf16>,
15486        cx: &mut App,
15487    ) -> Vec<Range<OffsetUtf16>> {
15488        let selections = self.selections.all::<OffsetUtf16>(cx);
15489        let newest_selection = selections
15490            .iter()
15491            .max_by_key(|selection| selection.id)
15492            .unwrap();
15493        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15494        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15495        let snapshot = self.buffer.read(cx).read(cx);
15496        selections
15497            .into_iter()
15498            .map(|mut selection| {
15499                selection.start.0 =
15500                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15501                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15502                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15503                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15504            })
15505            .collect()
15506    }
15507
15508    fn report_editor_event(
15509        &self,
15510        event_type: &'static str,
15511        file_extension: Option<String>,
15512        cx: &App,
15513    ) {
15514        if cfg!(any(test, feature = "test-support")) {
15515            return;
15516        }
15517
15518        let Some(project) = &self.project else { return };
15519
15520        // If None, we are in a file without an extension
15521        let file = self
15522            .buffer
15523            .read(cx)
15524            .as_singleton()
15525            .and_then(|b| b.read(cx).file());
15526        let file_extension = file_extension.or(file
15527            .as_ref()
15528            .and_then(|file| Path::new(file.file_name(cx)).extension())
15529            .and_then(|e| e.to_str())
15530            .map(|a| a.to_string()));
15531
15532        let vim_mode = cx
15533            .global::<SettingsStore>()
15534            .raw_user_settings()
15535            .get("vim_mode")
15536            == Some(&serde_json::Value::Bool(true));
15537
15538        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15539        let copilot_enabled = edit_predictions_provider
15540            == language::language_settings::EditPredictionProvider::Copilot;
15541        let copilot_enabled_for_language = self
15542            .buffer
15543            .read(cx)
15544            .settings_at(0, cx)
15545            .show_edit_predictions;
15546
15547        let project = project.read(cx);
15548        telemetry::event!(
15549            event_type,
15550            file_extension,
15551            vim_mode,
15552            copilot_enabled,
15553            copilot_enabled_for_language,
15554            edit_predictions_provider,
15555            is_via_ssh = project.is_via_ssh(),
15556        );
15557    }
15558
15559    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15560    /// with each line being an array of {text, highlight} objects.
15561    fn copy_highlight_json(
15562        &mut self,
15563        _: &CopyHighlightJson,
15564        window: &mut Window,
15565        cx: &mut Context<Self>,
15566    ) {
15567        #[derive(Serialize)]
15568        struct Chunk<'a> {
15569            text: String,
15570            highlight: Option<&'a str>,
15571        }
15572
15573        let snapshot = self.buffer.read(cx).snapshot(cx);
15574        let range = self
15575            .selected_text_range(false, window, cx)
15576            .and_then(|selection| {
15577                if selection.range.is_empty() {
15578                    None
15579                } else {
15580                    Some(selection.range)
15581                }
15582            })
15583            .unwrap_or_else(|| 0..snapshot.len());
15584
15585        let chunks = snapshot.chunks(range, true);
15586        let mut lines = Vec::new();
15587        let mut line: VecDeque<Chunk> = VecDeque::new();
15588
15589        let Some(style) = self.style.as_ref() else {
15590            return;
15591        };
15592
15593        for chunk in chunks {
15594            let highlight = chunk
15595                .syntax_highlight_id
15596                .and_then(|id| id.name(&style.syntax));
15597            let mut chunk_lines = chunk.text.split('\n').peekable();
15598            while let Some(text) = chunk_lines.next() {
15599                let mut merged_with_last_token = false;
15600                if let Some(last_token) = line.back_mut() {
15601                    if last_token.highlight == highlight {
15602                        last_token.text.push_str(text);
15603                        merged_with_last_token = true;
15604                    }
15605                }
15606
15607                if !merged_with_last_token {
15608                    line.push_back(Chunk {
15609                        text: text.into(),
15610                        highlight,
15611                    });
15612                }
15613
15614                if chunk_lines.peek().is_some() {
15615                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15616                        line.pop_front();
15617                    }
15618                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15619                        line.pop_back();
15620                    }
15621
15622                    lines.push(mem::take(&mut line));
15623                }
15624            }
15625        }
15626
15627        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15628            return;
15629        };
15630        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15631    }
15632
15633    pub fn open_context_menu(
15634        &mut self,
15635        _: &OpenContextMenu,
15636        window: &mut Window,
15637        cx: &mut Context<Self>,
15638    ) {
15639        self.request_autoscroll(Autoscroll::newest(), cx);
15640        let position = self.selections.newest_display(cx).start;
15641        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15642    }
15643
15644    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15645        &self.inlay_hint_cache
15646    }
15647
15648    pub fn replay_insert_event(
15649        &mut self,
15650        text: &str,
15651        relative_utf16_range: Option<Range<isize>>,
15652        window: &mut Window,
15653        cx: &mut Context<Self>,
15654    ) {
15655        if !self.input_enabled {
15656            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15657            return;
15658        }
15659        if let Some(relative_utf16_range) = relative_utf16_range {
15660            let selections = self.selections.all::<OffsetUtf16>(cx);
15661            self.change_selections(None, window, cx, |s| {
15662                let new_ranges = selections.into_iter().map(|range| {
15663                    let start = OffsetUtf16(
15664                        range
15665                            .head()
15666                            .0
15667                            .saturating_add_signed(relative_utf16_range.start),
15668                    );
15669                    let end = OffsetUtf16(
15670                        range
15671                            .head()
15672                            .0
15673                            .saturating_add_signed(relative_utf16_range.end),
15674                    );
15675                    start..end
15676                });
15677                s.select_ranges(new_ranges);
15678            });
15679        }
15680
15681        self.handle_input(text, window, cx);
15682    }
15683
15684    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15685        let Some(provider) = self.semantics_provider.as_ref() else {
15686            return false;
15687        };
15688
15689        let mut supports = false;
15690        self.buffer().update(cx, |this, cx| {
15691            this.for_each_buffer(|buffer| {
15692                supports |= provider.supports_inlay_hints(buffer, cx);
15693            });
15694        });
15695
15696        supports
15697    }
15698
15699    pub fn is_focused(&self, window: &Window) -> bool {
15700        self.focus_handle.is_focused(window)
15701    }
15702
15703    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15704        cx.emit(EditorEvent::Focused);
15705
15706        if let Some(descendant) = self
15707            .last_focused_descendant
15708            .take()
15709            .and_then(|descendant| descendant.upgrade())
15710        {
15711            window.focus(&descendant);
15712        } else {
15713            if let Some(blame) = self.blame.as_ref() {
15714                blame.update(cx, GitBlame::focus)
15715            }
15716
15717            self.blink_manager.update(cx, BlinkManager::enable);
15718            self.show_cursor_names(window, cx);
15719            self.buffer.update(cx, |buffer, cx| {
15720                buffer.finalize_last_transaction(cx);
15721                if self.leader_peer_id.is_none() {
15722                    buffer.set_active_selections(
15723                        &self.selections.disjoint_anchors(),
15724                        self.selections.line_mode,
15725                        self.cursor_shape,
15726                        cx,
15727                    );
15728                }
15729            });
15730        }
15731    }
15732
15733    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15734        cx.emit(EditorEvent::FocusedIn)
15735    }
15736
15737    fn handle_focus_out(
15738        &mut self,
15739        event: FocusOutEvent,
15740        _window: &mut Window,
15741        _cx: &mut Context<Self>,
15742    ) {
15743        if event.blurred != self.focus_handle {
15744            self.last_focused_descendant = Some(event.blurred);
15745        }
15746    }
15747
15748    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15749        self.blink_manager.update(cx, BlinkManager::disable);
15750        self.buffer
15751            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15752
15753        if let Some(blame) = self.blame.as_ref() {
15754            blame.update(cx, GitBlame::blur)
15755        }
15756        if !self.hover_state.focused(window, cx) {
15757            hide_hover(self, cx);
15758        }
15759        if !self
15760            .context_menu
15761            .borrow()
15762            .as_ref()
15763            .is_some_and(|context_menu| context_menu.focused(window, cx))
15764        {
15765            self.hide_context_menu(window, cx);
15766        }
15767        self.discard_inline_completion(false, cx);
15768        cx.emit(EditorEvent::Blurred);
15769        cx.notify();
15770    }
15771
15772    pub fn register_action<A: Action>(
15773        &mut self,
15774        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15775    ) -> Subscription {
15776        let id = self.next_editor_action_id.post_inc();
15777        let listener = Arc::new(listener);
15778        self.editor_actions.borrow_mut().insert(
15779            id,
15780            Box::new(move |window, _| {
15781                let listener = listener.clone();
15782                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15783                    let action = action.downcast_ref().unwrap();
15784                    if phase == DispatchPhase::Bubble {
15785                        listener(action, window, cx)
15786                    }
15787                })
15788            }),
15789        );
15790
15791        let editor_actions = self.editor_actions.clone();
15792        Subscription::new(move || {
15793            editor_actions.borrow_mut().remove(&id);
15794        })
15795    }
15796
15797    pub fn file_header_size(&self) -> u32 {
15798        FILE_HEADER_HEIGHT
15799    }
15800
15801    pub fn revert(
15802        &mut self,
15803        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15804        window: &mut Window,
15805        cx: &mut Context<Self>,
15806    ) {
15807        self.buffer().update(cx, |multi_buffer, cx| {
15808            for (buffer_id, changes) in revert_changes {
15809                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15810                    buffer.update(cx, |buffer, cx| {
15811                        buffer.edit(
15812                            changes.into_iter().map(|(range, text)| {
15813                                (range, text.to_string().map(Arc::<str>::from))
15814                            }),
15815                            None,
15816                            cx,
15817                        );
15818                    });
15819                }
15820            }
15821        });
15822        self.change_selections(None, window, cx, |selections| selections.refresh());
15823    }
15824
15825    pub fn to_pixel_point(
15826        &self,
15827        source: multi_buffer::Anchor,
15828        editor_snapshot: &EditorSnapshot,
15829        window: &mut Window,
15830    ) -> Option<gpui::Point<Pixels>> {
15831        let source_point = source.to_display_point(editor_snapshot);
15832        self.display_to_pixel_point(source_point, editor_snapshot, window)
15833    }
15834
15835    pub fn display_to_pixel_point(
15836        &self,
15837        source: DisplayPoint,
15838        editor_snapshot: &EditorSnapshot,
15839        window: &mut Window,
15840    ) -> Option<gpui::Point<Pixels>> {
15841        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15842        let text_layout_details = self.text_layout_details(window);
15843        let scroll_top = text_layout_details
15844            .scroll_anchor
15845            .scroll_position(editor_snapshot)
15846            .y;
15847
15848        if source.row().as_f32() < scroll_top.floor() {
15849            return None;
15850        }
15851        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15852        let source_y = line_height * (source.row().as_f32() - scroll_top);
15853        Some(gpui::Point::new(source_x, source_y))
15854    }
15855
15856    pub fn has_visible_completions_menu(&self) -> bool {
15857        !self.edit_prediction_preview_is_active()
15858            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15859                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15860            })
15861    }
15862
15863    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15864        self.addons
15865            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15866    }
15867
15868    pub fn unregister_addon<T: Addon>(&mut self) {
15869        self.addons.remove(&std::any::TypeId::of::<T>());
15870    }
15871
15872    pub fn addon<T: Addon>(&self) -> Option<&T> {
15873        let type_id = std::any::TypeId::of::<T>();
15874        self.addons
15875            .get(&type_id)
15876            .and_then(|item| item.to_any().downcast_ref::<T>())
15877    }
15878
15879    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15880        let text_layout_details = self.text_layout_details(window);
15881        let style = &text_layout_details.editor_style;
15882        let font_id = window.text_system().resolve_font(&style.text.font());
15883        let font_size = style.text.font_size.to_pixels(window.rem_size());
15884        let line_height = style.text.line_height_in_pixels(window.rem_size());
15885        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15886
15887        gpui::Size::new(em_width, line_height)
15888    }
15889
15890    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15891        self.load_diff_task.clone()
15892    }
15893
15894    fn read_selections_from_db(
15895        &mut self,
15896        item_id: u64,
15897        workspace_id: WorkspaceId,
15898        window: &mut Window,
15899        cx: &mut Context<Editor>,
15900    ) {
15901        if !self.is_singleton(cx)
15902            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15903        {
15904            return;
15905        }
15906        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15907            return;
15908        };
15909        if selections.is_empty() {
15910            return;
15911        }
15912
15913        let snapshot = self.buffer.read(cx).snapshot(cx);
15914        self.change_selections(None, window, cx, |s| {
15915            s.select_ranges(selections.into_iter().map(|(start, end)| {
15916                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15917            }));
15918        });
15919    }
15920}
15921
15922fn insert_extra_newline_brackets(
15923    buffer: &MultiBufferSnapshot,
15924    range: Range<usize>,
15925    language: &language::LanguageScope,
15926) -> bool {
15927    let leading_whitespace_len = buffer
15928        .reversed_chars_at(range.start)
15929        .take_while(|c| c.is_whitespace() && *c != '\n')
15930        .map(|c| c.len_utf8())
15931        .sum::<usize>();
15932    let trailing_whitespace_len = buffer
15933        .chars_at(range.end)
15934        .take_while(|c| c.is_whitespace() && *c != '\n')
15935        .map(|c| c.len_utf8())
15936        .sum::<usize>();
15937    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15938
15939    language.brackets().any(|(pair, enabled)| {
15940        let pair_start = pair.start.trim_end();
15941        let pair_end = pair.end.trim_start();
15942
15943        enabled
15944            && pair.newline
15945            && buffer.contains_str_at(range.end, pair_end)
15946            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15947    })
15948}
15949
15950fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15951    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15952        [(buffer, range, _)] => (*buffer, range.clone()),
15953        _ => return false,
15954    };
15955    let pair = {
15956        let mut result: Option<BracketMatch> = None;
15957
15958        for pair in buffer
15959            .all_bracket_ranges(range.clone())
15960            .filter(move |pair| {
15961                pair.open_range.start <= range.start && pair.close_range.end >= range.end
15962            })
15963        {
15964            let len = pair.close_range.end - pair.open_range.start;
15965
15966            if let Some(existing) = &result {
15967                let existing_len = existing.close_range.end - existing.open_range.start;
15968                if len > existing_len {
15969                    continue;
15970                }
15971            }
15972
15973            result = Some(pair);
15974        }
15975
15976        result
15977    };
15978    let Some(pair) = pair else {
15979        return false;
15980    };
15981    pair.newline_only
15982        && buffer
15983            .chars_for_range(pair.open_range.end..range.start)
15984            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15985            .all(|c| c.is_whitespace() && c != '\n')
15986}
15987
15988fn get_uncommitted_diff_for_buffer(
15989    project: &Entity<Project>,
15990    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15991    buffer: Entity<MultiBuffer>,
15992    cx: &mut App,
15993) -> Task<()> {
15994    let mut tasks = Vec::new();
15995    project.update(cx, |project, cx| {
15996        for buffer in buffers {
15997            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15998        }
15999    });
16000    cx.spawn(|mut cx| async move {
16001        let diffs = futures::future::join_all(tasks).await;
16002        buffer
16003            .update(&mut cx, |buffer, cx| {
16004                for diff in diffs.into_iter().flatten() {
16005                    buffer.add_diff(diff, cx);
16006                }
16007            })
16008            .ok();
16009    })
16010}
16011
16012fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16013    let tab_size = tab_size.get() as usize;
16014    let mut width = offset;
16015
16016    for ch in text.chars() {
16017        width += if ch == '\t' {
16018            tab_size - (width % tab_size)
16019        } else {
16020            1
16021        };
16022    }
16023
16024    width - offset
16025}
16026
16027#[cfg(test)]
16028mod tests {
16029    use super::*;
16030
16031    #[test]
16032    fn test_string_size_with_expanded_tabs() {
16033        let nz = |val| NonZeroU32::new(val).unwrap();
16034        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16035        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16036        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16037        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16038        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16039        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16040        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16041        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16042    }
16043}
16044
16045/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16046struct WordBreakingTokenizer<'a> {
16047    input: &'a str,
16048}
16049
16050impl<'a> WordBreakingTokenizer<'a> {
16051    fn new(input: &'a str) -> Self {
16052        Self { input }
16053    }
16054}
16055
16056fn is_char_ideographic(ch: char) -> bool {
16057    use unicode_script::Script::*;
16058    use unicode_script::UnicodeScript;
16059    matches!(ch.script(), Han | Tangut | Yi)
16060}
16061
16062fn is_grapheme_ideographic(text: &str) -> bool {
16063    text.chars().any(is_char_ideographic)
16064}
16065
16066fn is_grapheme_whitespace(text: &str) -> bool {
16067    text.chars().any(|x| x.is_whitespace())
16068}
16069
16070fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16071    text.chars().next().map_or(false, |ch| {
16072        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16073    })
16074}
16075
16076#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16077struct WordBreakToken<'a> {
16078    token: &'a str,
16079    grapheme_len: usize,
16080    is_whitespace: bool,
16081}
16082
16083impl<'a> Iterator for WordBreakingTokenizer<'a> {
16084    /// Yields a span, the count of graphemes in the token, and whether it was
16085    /// whitespace. Note that it also breaks at word boundaries.
16086    type Item = WordBreakToken<'a>;
16087
16088    fn next(&mut self) -> Option<Self::Item> {
16089        use unicode_segmentation::UnicodeSegmentation;
16090        if self.input.is_empty() {
16091            return None;
16092        }
16093
16094        let mut iter = self.input.graphemes(true).peekable();
16095        let mut offset = 0;
16096        let mut graphemes = 0;
16097        if let Some(first_grapheme) = iter.next() {
16098            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16099            offset += first_grapheme.len();
16100            graphemes += 1;
16101            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16102                if let Some(grapheme) = iter.peek().copied() {
16103                    if should_stay_with_preceding_ideograph(grapheme) {
16104                        offset += grapheme.len();
16105                        graphemes += 1;
16106                    }
16107                }
16108            } else {
16109                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16110                let mut next_word_bound = words.peek().copied();
16111                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16112                    next_word_bound = words.next();
16113                }
16114                while let Some(grapheme) = iter.peek().copied() {
16115                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16116                        break;
16117                    };
16118                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16119                        break;
16120                    };
16121                    offset += grapheme.len();
16122                    graphemes += 1;
16123                    iter.next();
16124                }
16125            }
16126            let token = &self.input[..offset];
16127            self.input = &self.input[offset..];
16128            if is_whitespace {
16129                Some(WordBreakToken {
16130                    token: " ",
16131                    grapheme_len: 1,
16132                    is_whitespace: true,
16133                })
16134            } else {
16135                Some(WordBreakToken {
16136                    token,
16137                    grapheme_len: graphemes,
16138                    is_whitespace: false,
16139                })
16140            }
16141        } else {
16142            None
16143        }
16144    }
16145}
16146
16147#[test]
16148fn test_word_breaking_tokenizer() {
16149    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16150        ("", &[]),
16151        ("  ", &[(" ", 1, true)]),
16152        ("Ʒ", &[("Ʒ", 1, false)]),
16153        ("Ǽ", &[("Ǽ", 1, false)]),
16154        ("", &[("", 1, false)]),
16155        ("⋑⋑", &[("⋑⋑", 2, false)]),
16156        (
16157            "原理,进而",
16158            &[
16159                ("", 1, false),
16160                ("理,", 2, false),
16161                ("", 1, false),
16162                ("", 1, false),
16163            ],
16164        ),
16165        (
16166            "hello world",
16167            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16168        ),
16169        (
16170            "hello, world",
16171            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16172        ),
16173        (
16174            "  hello world",
16175            &[
16176                (" ", 1, true),
16177                ("hello", 5, false),
16178                (" ", 1, true),
16179                ("world", 5, false),
16180            ],
16181        ),
16182        (
16183            "这是什么 \n 钢笔",
16184            &[
16185                ("", 1, false),
16186                ("", 1, false),
16187                ("", 1, false),
16188                ("", 1, false),
16189                (" ", 1, true),
16190                ("", 1, false),
16191                ("", 1, false),
16192            ],
16193        ),
16194        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16195    ];
16196
16197    for (input, result) in tests {
16198        assert_eq!(
16199            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16200            result
16201                .iter()
16202                .copied()
16203                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16204                    token,
16205                    grapheme_len,
16206                    is_whitespace,
16207                })
16208                .collect::<Vec<_>>()
16209        );
16210    }
16211}
16212
16213fn wrap_with_prefix(
16214    line_prefix: String,
16215    unwrapped_text: String,
16216    wrap_column: usize,
16217    tab_size: NonZeroU32,
16218) -> String {
16219    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16220    let mut wrapped_text = String::new();
16221    let mut current_line = line_prefix.clone();
16222
16223    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16224    let mut current_line_len = line_prefix_len;
16225    for WordBreakToken {
16226        token,
16227        grapheme_len,
16228        is_whitespace,
16229    } in tokenizer
16230    {
16231        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16232            wrapped_text.push_str(current_line.trim_end());
16233            wrapped_text.push('\n');
16234            current_line.truncate(line_prefix.len());
16235            current_line_len = line_prefix_len;
16236            if !is_whitespace {
16237                current_line.push_str(token);
16238                current_line_len += grapheme_len;
16239            }
16240        } else if !is_whitespace {
16241            current_line.push_str(token);
16242            current_line_len += grapheme_len;
16243        } else if current_line_len != line_prefix_len {
16244            current_line.push(' ');
16245            current_line_len += 1;
16246        }
16247    }
16248
16249    if !current_line.is_empty() {
16250        wrapped_text.push_str(&current_line);
16251    }
16252    wrapped_text
16253}
16254
16255#[test]
16256fn test_wrap_with_prefix() {
16257    assert_eq!(
16258        wrap_with_prefix(
16259            "# ".to_string(),
16260            "abcdefg".to_string(),
16261            4,
16262            NonZeroU32::new(4).unwrap()
16263        ),
16264        "# abcdefg"
16265    );
16266    assert_eq!(
16267        wrap_with_prefix(
16268            "".to_string(),
16269            "\thello world".to_string(),
16270            8,
16271            NonZeroU32::new(4).unwrap()
16272        ),
16273        "hello\nworld"
16274    );
16275    assert_eq!(
16276        wrap_with_prefix(
16277            "// ".to_string(),
16278            "xx \nyy zz aa bb cc".to_string(),
16279            12,
16280            NonZeroU32::new(4).unwrap()
16281        ),
16282        "// xx yy zz\n// aa bb cc"
16283    );
16284    assert_eq!(
16285        wrap_with_prefix(
16286            String::new(),
16287            "这是什么 \n 钢笔".to_string(),
16288            3,
16289            NonZeroU32::new(4).unwrap()
16290        ),
16291        "这是什\n么 钢\n"
16292    );
16293}
16294
16295pub trait CollaborationHub {
16296    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16297    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16298    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16299}
16300
16301impl CollaborationHub for Entity<Project> {
16302    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16303        self.read(cx).collaborators()
16304    }
16305
16306    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16307        self.read(cx).user_store().read(cx).participant_indices()
16308    }
16309
16310    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16311        let this = self.read(cx);
16312        let user_ids = this.collaborators().values().map(|c| c.user_id);
16313        this.user_store().read_with(cx, |user_store, cx| {
16314            user_store.participant_names(user_ids, cx)
16315        })
16316    }
16317}
16318
16319pub trait SemanticsProvider {
16320    fn hover(
16321        &self,
16322        buffer: &Entity<Buffer>,
16323        position: text::Anchor,
16324        cx: &mut App,
16325    ) -> Option<Task<Vec<project::Hover>>>;
16326
16327    fn inlay_hints(
16328        &self,
16329        buffer_handle: Entity<Buffer>,
16330        range: Range<text::Anchor>,
16331        cx: &mut App,
16332    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16333
16334    fn resolve_inlay_hint(
16335        &self,
16336        hint: InlayHint,
16337        buffer_handle: Entity<Buffer>,
16338        server_id: LanguageServerId,
16339        cx: &mut App,
16340    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16341
16342    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16343
16344    fn document_highlights(
16345        &self,
16346        buffer: &Entity<Buffer>,
16347        position: text::Anchor,
16348        cx: &mut App,
16349    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16350
16351    fn definitions(
16352        &self,
16353        buffer: &Entity<Buffer>,
16354        position: text::Anchor,
16355        kind: GotoDefinitionKind,
16356        cx: &mut App,
16357    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16358
16359    fn range_for_rename(
16360        &self,
16361        buffer: &Entity<Buffer>,
16362        position: text::Anchor,
16363        cx: &mut App,
16364    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16365
16366    fn perform_rename(
16367        &self,
16368        buffer: &Entity<Buffer>,
16369        position: text::Anchor,
16370        new_name: String,
16371        cx: &mut App,
16372    ) -> Option<Task<Result<ProjectTransaction>>>;
16373}
16374
16375pub trait CompletionProvider {
16376    fn completions(
16377        &self,
16378        buffer: &Entity<Buffer>,
16379        buffer_position: text::Anchor,
16380        trigger: CompletionContext,
16381        window: &mut Window,
16382        cx: &mut Context<Editor>,
16383    ) -> Task<Result<Vec<Completion>>>;
16384
16385    fn resolve_completions(
16386        &self,
16387        buffer: Entity<Buffer>,
16388        completion_indices: Vec<usize>,
16389        completions: Rc<RefCell<Box<[Completion]>>>,
16390        cx: &mut Context<Editor>,
16391    ) -> Task<Result<bool>>;
16392
16393    fn apply_additional_edits_for_completion(
16394        &self,
16395        _buffer: Entity<Buffer>,
16396        _completions: Rc<RefCell<Box<[Completion]>>>,
16397        _completion_index: usize,
16398        _push_to_history: bool,
16399        _cx: &mut Context<Editor>,
16400    ) -> Task<Result<Option<language::Transaction>>> {
16401        Task::ready(Ok(None))
16402    }
16403
16404    fn is_completion_trigger(
16405        &self,
16406        buffer: &Entity<Buffer>,
16407        position: language::Anchor,
16408        text: &str,
16409        trigger_in_words: bool,
16410        cx: &mut Context<Editor>,
16411    ) -> bool;
16412
16413    fn sort_completions(&self) -> bool {
16414        true
16415    }
16416}
16417
16418pub trait CodeActionProvider {
16419    fn id(&self) -> Arc<str>;
16420
16421    fn code_actions(
16422        &self,
16423        buffer: &Entity<Buffer>,
16424        range: Range<text::Anchor>,
16425        window: &mut Window,
16426        cx: &mut App,
16427    ) -> Task<Result<Vec<CodeAction>>>;
16428
16429    fn apply_code_action(
16430        &self,
16431        buffer_handle: Entity<Buffer>,
16432        action: CodeAction,
16433        excerpt_id: ExcerptId,
16434        push_to_history: bool,
16435        window: &mut Window,
16436        cx: &mut App,
16437    ) -> Task<Result<ProjectTransaction>>;
16438}
16439
16440impl CodeActionProvider for Entity<Project> {
16441    fn id(&self) -> Arc<str> {
16442        "project".into()
16443    }
16444
16445    fn code_actions(
16446        &self,
16447        buffer: &Entity<Buffer>,
16448        range: Range<text::Anchor>,
16449        _window: &mut Window,
16450        cx: &mut App,
16451    ) -> Task<Result<Vec<CodeAction>>> {
16452        self.update(cx, |project, cx| {
16453            project.code_actions(buffer, range, None, cx)
16454        })
16455    }
16456
16457    fn apply_code_action(
16458        &self,
16459        buffer_handle: Entity<Buffer>,
16460        action: CodeAction,
16461        _excerpt_id: ExcerptId,
16462        push_to_history: bool,
16463        _window: &mut Window,
16464        cx: &mut App,
16465    ) -> Task<Result<ProjectTransaction>> {
16466        self.update(cx, |project, cx| {
16467            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16468        })
16469    }
16470}
16471
16472fn snippet_completions(
16473    project: &Project,
16474    buffer: &Entity<Buffer>,
16475    buffer_position: text::Anchor,
16476    cx: &mut App,
16477) -> Task<Result<Vec<Completion>>> {
16478    let language = buffer.read(cx).language_at(buffer_position);
16479    let language_name = language.as_ref().map(|language| language.lsp_id());
16480    let snippet_store = project.snippets().read(cx);
16481    let snippets = snippet_store.snippets_for(language_name, cx);
16482
16483    if snippets.is_empty() {
16484        return Task::ready(Ok(vec![]));
16485    }
16486    let snapshot = buffer.read(cx).text_snapshot();
16487    let chars: String = snapshot
16488        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16489        .collect();
16490
16491    let scope = language.map(|language| language.default_scope());
16492    let executor = cx.background_executor().clone();
16493
16494    cx.background_spawn(async move {
16495        let classifier = CharClassifier::new(scope).for_completion(true);
16496        let mut last_word = chars
16497            .chars()
16498            .take_while(|c| classifier.is_word(*c))
16499            .collect::<String>();
16500        last_word = last_word.chars().rev().collect();
16501
16502        if last_word.is_empty() {
16503            return Ok(vec![]);
16504        }
16505
16506        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16507        let to_lsp = |point: &text::Anchor| {
16508            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16509            point_to_lsp(end)
16510        };
16511        let lsp_end = to_lsp(&buffer_position);
16512
16513        let candidates = snippets
16514            .iter()
16515            .enumerate()
16516            .flat_map(|(ix, snippet)| {
16517                snippet
16518                    .prefix
16519                    .iter()
16520                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16521            })
16522            .collect::<Vec<StringMatchCandidate>>();
16523
16524        let mut matches = fuzzy::match_strings(
16525            &candidates,
16526            &last_word,
16527            last_word.chars().any(|c| c.is_uppercase()),
16528            100,
16529            &Default::default(),
16530            executor,
16531        )
16532        .await;
16533
16534        // Remove all candidates where the query's start does not match the start of any word in the candidate
16535        if let Some(query_start) = last_word.chars().next() {
16536            matches.retain(|string_match| {
16537                split_words(&string_match.string).any(|word| {
16538                    // Check that the first codepoint of the word as lowercase matches the first
16539                    // codepoint of the query as lowercase
16540                    word.chars()
16541                        .flat_map(|codepoint| codepoint.to_lowercase())
16542                        .zip(query_start.to_lowercase())
16543                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16544                })
16545            });
16546        }
16547
16548        let matched_strings = matches
16549            .into_iter()
16550            .map(|m| m.string)
16551            .collect::<HashSet<_>>();
16552
16553        let result: Vec<Completion> = snippets
16554            .into_iter()
16555            .filter_map(|snippet| {
16556                let matching_prefix = snippet
16557                    .prefix
16558                    .iter()
16559                    .find(|prefix| matched_strings.contains(*prefix))?;
16560                let start = as_offset - last_word.len();
16561                let start = snapshot.anchor_before(start);
16562                let range = start..buffer_position;
16563                let lsp_start = to_lsp(&start);
16564                let lsp_range = lsp::Range {
16565                    start: lsp_start,
16566                    end: lsp_end,
16567                };
16568                Some(Completion {
16569                    old_range: range,
16570                    new_text: snippet.body.clone(),
16571                    resolved: false,
16572                    label: CodeLabel {
16573                        text: matching_prefix.clone(),
16574                        runs: vec![],
16575                        filter_range: 0..matching_prefix.len(),
16576                    },
16577                    server_id: LanguageServerId(usize::MAX),
16578                    documentation: snippet
16579                        .description
16580                        .clone()
16581                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16582                    lsp_completion: lsp::CompletionItem {
16583                        label: snippet.prefix.first().unwrap().clone(),
16584                        kind: Some(CompletionItemKind::SNIPPET),
16585                        label_details: snippet.description.as_ref().map(|description| {
16586                            lsp::CompletionItemLabelDetails {
16587                                detail: Some(description.clone()),
16588                                description: None,
16589                            }
16590                        }),
16591                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16592                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16593                            lsp::InsertReplaceEdit {
16594                                new_text: snippet.body.clone(),
16595                                insert: lsp_range,
16596                                replace: lsp_range,
16597                            },
16598                        )),
16599                        filter_text: Some(snippet.body.clone()),
16600                        sort_text: Some(char::MAX.to_string()),
16601                        ..Default::default()
16602                    },
16603                    confirm: None,
16604                })
16605            })
16606            .collect();
16607
16608        Ok(result)
16609    })
16610}
16611
16612impl CompletionProvider for Entity<Project> {
16613    fn completions(
16614        &self,
16615        buffer: &Entity<Buffer>,
16616        buffer_position: text::Anchor,
16617        options: CompletionContext,
16618        _window: &mut Window,
16619        cx: &mut Context<Editor>,
16620    ) -> Task<Result<Vec<Completion>>> {
16621        self.update(cx, |project, cx| {
16622            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16623            let project_completions = project.completions(buffer, buffer_position, options, cx);
16624            cx.background_spawn(async move {
16625                let mut completions = project_completions.await?;
16626                let snippets_completions = snippets.await?;
16627                completions.extend(snippets_completions);
16628                Ok(completions)
16629            })
16630        })
16631    }
16632
16633    fn resolve_completions(
16634        &self,
16635        buffer: Entity<Buffer>,
16636        completion_indices: Vec<usize>,
16637        completions: Rc<RefCell<Box<[Completion]>>>,
16638        cx: &mut Context<Editor>,
16639    ) -> Task<Result<bool>> {
16640        self.update(cx, |project, cx| {
16641            project.lsp_store().update(cx, |lsp_store, cx| {
16642                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16643            })
16644        })
16645    }
16646
16647    fn apply_additional_edits_for_completion(
16648        &self,
16649        buffer: Entity<Buffer>,
16650        completions: Rc<RefCell<Box<[Completion]>>>,
16651        completion_index: usize,
16652        push_to_history: bool,
16653        cx: &mut Context<Editor>,
16654    ) -> Task<Result<Option<language::Transaction>>> {
16655        self.update(cx, |project, cx| {
16656            project.lsp_store().update(cx, |lsp_store, cx| {
16657                lsp_store.apply_additional_edits_for_completion(
16658                    buffer,
16659                    completions,
16660                    completion_index,
16661                    push_to_history,
16662                    cx,
16663                )
16664            })
16665        })
16666    }
16667
16668    fn is_completion_trigger(
16669        &self,
16670        buffer: &Entity<Buffer>,
16671        position: language::Anchor,
16672        text: &str,
16673        trigger_in_words: bool,
16674        cx: &mut Context<Editor>,
16675    ) -> bool {
16676        let mut chars = text.chars();
16677        let char = if let Some(char) = chars.next() {
16678            char
16679        } else {
16680            return false;
16681        };
16682        if chars.next().is_some() {
16683            return false;
16684        }
16685
16686        let buffer = buffer.read(cx);
16687        let snapshot = buffer.snapshot();
16688        if !snapshot.settings_at(position, cx).show_completions_on_input {
16689            return false;
16690        }
16691        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16692        if trigger_in_words && classifier.is_word(char) {
16693            return true;
16694        }
16695
16696        buffer.completion_triggers().contains(text)
16697    }
16698}
16699
16700impl SemanticsProvider for Entity<Project> {
16701    fn hover(
16702        &self,
16703        buffer: &Entity<Buffer>,
16704        position: text::Anchor,
16705        cx: &mut App,
16706    ) -> Option<Task<Vec<project::Hover>>> {
16707        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16708    }
16709
16710    fn document_highlights(
16711        &self,
16712        buffer: &Entity<Buffer>,
16713        position: text::Anchor,
16714        cx: &mut App,
16715    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16716        Some(self.update(cx, |project, cx| {
16717            project.document_highlights(buffer, position, cx)
16718        }))
16719    }
16720
16721    fn definitions(
16722        &self,
16723        buffer: &Entity<Buffer>,
16724        position: text::Anchor,
16725        kind: GotoDefinitionKind,
16726        cx: &mut App,
16727    ) -> Option<Task<Result<Vec<LocationLink>>>> {
16728        Some(self.update(cx, |project, cx| match kind {
16729            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16730            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16731            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16732            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16733        }))
16734    }
16735
16736    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16737        // TODO: make this work for remote projects
16738        self.update(cx, |this, cx| {
16739            buffer.update(cx, |buffer, cx| {
16740                this.any_language_server_supports_inlay_hints(buffer, cx)
16741            })
16742        })
16743    }
16744
16745    fn inlay_hints(
16746        &self,
16747        buffer_handle: Entity<Buffer>,
16748        range: Range<text::Anchor>,
16749        cx: &mut App,
16750    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16751        Some(self.update(cx, |project, cx| {
16752            project.inlay_hints(buffer_handle, range, cx)
16753        }))
16754    }
16755
16756    fn resolve_inlay_hint(
16757        &self,
16758        hint: InlayHint,
16759        buffer_handle: Entity<Buffer>,
16760        server_id: LanguageServerId,
16761        cx: &mut App,
16762    ) -> Option<Task<anyhow::Result<InlayHint>>> {
16763        Some(self.update(cx, |project, cx| {
16764            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16765        }))
16766    }
16767
16768    fn range_for_rename(
16769        &self,
16770        buffer: &Entity<Buffer>,
16771        position: text::Anchor,
16772        cx: &mut App,
16773    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16774        Some(self.update(cx, |project, cx| {
16775            let buffer = buffer.clone();
16776            let task = project.prepare_rename(buffer.clone(), position, cx);
16777            cx.spawn(|_, mut cx| async move {
16778                Ok(match task.await? {
16779                    PrepareRenameResponse::Success(range) => Some(range),
16780                    PrepareRenameResponse::InvalidPosition => None,
16781                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16782                        // Fallback on using TreeSitter info to determine identifier range
16783                        buffer.update(&mut cx, |buffer, _| {
16784                            let snapshot = buffer.snapshot();
16785                            let (range, kind) = snapshot.surrounding_word(position);
16786                            if kind != Some(CharKind::Word) {
16787                                return None;
16788                            }
16789                            Some(
16790                                snapshot.anchor_before(range.start)
16791                                    ..snapshot.anchor_after(range.end),
16792                            )
16793                        })?
16794                    }
16795                })
16796            })
16797        }))
16798    }
16799
16800    fn perform_rename(
16801        &self,
16802        buffer: &Entity<Buffer>,
16803        position: text::Anchor,
16804        new_name: String,
16805        cx: &mut App,
16806    ) -> Option<Task<Result<ProjectTransaction>>> {
16807        Some(self.update(cx, |project, cx| {
16808            project.perform_rename(buffer.clone(), position, new_name, cx)
16809        }))
16810    }
16811}
16812
16813fn inlay_hint_settings(
16814    location: Anchor,
16815    snapshot: &MultiBufferSnapshot,
16816    cx: &mut Context<Editor>,
16817) -> InlayHintSettings {
16818    let file = snapshot.file_at(location);
16819    let language = snapshot.language_at(location).map(|l| l.name());
16820    language_settings(language, file, cx).inlay_hints
16821}
16822
16823fn consume_contiguous_rows(
16824    contiguous_row_selections: &mut Vec<Selection<Point>>,
16825    selection: &Selection<Point>,
16826    display_map: &DisplaySnapshot,
16827    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16828) -> (MultiBufferRow, MultiBufferRow) {
16829    contiguous_row_selections.push(selection.clone());
16830    let start_row = MultiBufferRow(selection.start.row);
16831    let mut end_row = ending_row(selection, display_map);
16832
16833    while let Some(next_selection) = selections.peek() {
16834        if next_selection.start.row <= end_row.0 {
16835            end_row = ending_row(next_selection, display_map);
16836            contiguous_row_selections.push(selections.next().unwrap().clone());
16837        } else {
16838            break;
16839        }
16840    }
16841    (start_row, end_row)
16842}
16843
16844fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16845    if next_selection.end.column > 0 || next_selection.is_empty() {
16846        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16847    } else {
16848        MultiBufferRow(next_selection.end.row)
16849    }
16850}
16851
16852impl EditorSnapshot {
16853    pub fn remote_selections_in_range<'a>(
16854        &'a self,
16855        range: &'a Range<Anchor>,
16856        collaboration_hub: &dyn CollaborationHub,
16857        cx: &'a App,
16858    ) -> impl 'a + Iterator<Item = RemoteSelection> {
16859        let participant_names = collaboration_hub.user_names(cx);
16860        let participant_indices = collaboration_hub.user_participant_indices(cx);
16861        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16862        let collaborators_by_replica_id = collaborators_by_peer_id
16863            .iter()
16864            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16865            .collect::<HashMap<_, _>>();
16866        self.buffer_snapshot
16867            .selections_in_range(range, false)
16868            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16869                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16870                let participant_index = participant_indices.get(&collaborator.user_id).copied();
16871                let user_name = participant_names.get(&collaborator.user_id).cloned();
16872                Some(RemoteSelection {
16873                    replica_id,
16874                    selection,
16875                    cursor_shape,
16876                    line_mode,
16877                    participant_index,
16878                    peer_id: collaborator.peer_id,
16879                    user_name,
16880                })
16881            })
16882    }
16883
16884    pub fn hunks_for_ranges(
16885        &self,
16886        ranges: impl Iterator<Item = Range<Point>>,
16887    ) -> Vec<MultiBufferDiffHunk> {
16888        let mut hunks = Vec::new();
16889        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16890            HashMap::default();
16891        for query_range in ranges {
16892            let query_rows =
16893                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16894            for hunk in self.buffer_snapshot.diff_hunks_in_range(
16895                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16896            ) {
16897                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16898                // when the caret is just above or just below the deleted hunk.
16899                let allow_adjacent = hunk.status().is_deleted();
16900                let related_to_selection = if allow_adjacent {
16901                    hunk.row_range.overlaps(&query_rows)
16902                        || hunk.row_range.start == query_rows.end
16903                        || hunk.row_range.end == query_rows.start
16904                } else {
16905                    hunk.row_range.overlaps(&query_rows)
16906                };
16907                if related_to_selection {
16908                    if !processed_buffer_rows
16909                        .entry(hunk.buffer_id)
16910                        .or_default()
16911                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16912                    {
16913                        continue;
16914                    }
16915                    hunks.push(hunk);
16916                }
16917            }
16918        }
16919
16920        hunks
16921    }
16922
16923    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16924        self.display_snapshot.buffer_snapshot.language_at(position)
16925    }
16926
16927    pub fn is_focused(&self) -> bool {
16928        self.is_focused
16929    }
16930
16931    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16932        self.placeholder_text.as_ref()
16933    }
16934
16935    pub fn scroll_position(&self) -> gpui::Point<f32> {
16936        self.scroll_anchor.scroll_position(&self.display_snapshot)
16937    }
16938
16939    fn gutter_dimensions(
16940        &self,
16941        font_id: FontId,
16942        font_size: Pixels,
16943        max_line_number_width: Pixels,
16944        cx: &App,
16945    ) -> Option<GutterDimensions> {
16946        if !self.show_gutter {
16947            return None;
16948        }
16949
16950        let descent = cx.text_system().descent(font_id, font_size);
16951        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16952        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16953
16954        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16955            matches!(
16956                ProjectSettings::get_global(cx).git.git_gutter,
16957                Some(GitGutterSetting::TrackedFiles)
16958            )
16959        });
16960        let gutter_settings = EditorSettings::get_global(cx).gutter;
16961        let show_line_numbers = self
16962            .show_line_numbers
16963            .unwrap_or(gutter_settings.line_numbers);
16964        let line_gutter_width = if show_line_numbers {
16965            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16966            let min_width_for_number_on_gutter = em_advance * 4.0;
16967            max_line_number_width.max(min_width_for_number_on_gutter)
16968        } else {
16969            0.0.into()
16970        };
16971
16972        let show_code_actions = self
16973            .show_code_actions
16974            .unwrap_or(gutter_settings.code_actions);
16975
16976        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16977
16978        let git_blame_entries_width =
16979            self.git_blame_gutter_max_author_length
16980                .map(|max_author_length| {
16981                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16982
16983                    /// The number of characters to dedicate to gaps and margins.
16984                    const SPACING_WIDTH: usize = 4;
16985
16986                    let max_char_count = max_author_length
16987                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16988                        + ::git::SHORT_SHA_LENGTH
16989                        + MAX_RELATIVE_TIMESTAMP.len()
16990                        + SPACING_WIDTH;
16991
16992                    em_advance * max_char_count
16993                });
16994
16995        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16996        left_padding += if show_code_actions || show_runnables {
16997            em_width * 3.0
16998        } else if show_git_gutter && show_line_numbers {
16999            em_width * 2.0
17000        } else if show_git_gutter || show_line_numbers {
17001            em_width
17002        } else {
17003            px(0.)
17004        };
17005
17006        let right_padding = if gutter_settings.folds && show_line_numbers {
17007            em_width * 4.0
17008        } else if gutter_settings.folds {
17009            em_width * 3.0
17010        } else if show_line_numbers {
17011            em_width
17012        } else {
17013            px(0.)
17014        };
17015
17016        Some(GutterDimensions {
17017            left_padding,
17018            right_padding,
17019            width: line_gutter_width + left_padding + right_padding,
17020            margin: -descent,
17021            git_blame_entries_width,
17022        })
17023    }
17024
17025    pub fn render_crease_toggle(
17026        &self,
17027        buffer_row: MultiBufferRow,
17028        row_contains_cursor: bool,
17029        editor: Entity<Editor>,
17030        window: &mut Window,
17031        cx: &mut App,
17032    ) -> Option<AnyElement> {
17033        let folded = self.is_line_folded(buffer_row);
17034        let mut is_foldable = false;
17035
17036        if let Some(crease) = self
17037            .crease_snapshot
17038            .query_row(buffer_row, &self.buffer_snapshot)
17039        {
17040            is_foldable = true;
17041            match crease {
17042                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17043                    if let Some(render_toggle) = render_toggle {
17044                        let toggle_callback =
17045                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17046                                if folded {
17047                                    editor.update(cx, |editor, cx| {
17048                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17049                                    });
17050                                } else {
17051                                    editor.update(cx, |editor, cx| {
17052                                        editor.unfold_at(
17053                                            &crate::UnfoldAt { buffer_row },
17054                                            window,
17055                                            cx,
17056                                        )
17057                                    });
17058                                }
17059                            });
17060                        return Some((render_toggle)(
17061                            buffer_row,
17062                            folded,
17063                            toggle_callback,
17064                            window,
17065                            cx,
17066                        ));
17067                    }
17068                }
17069            }
17070        }
17071
17072        is_foldable |= self.starts_indent(buffer_row);
17073
17074        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17075            Some(
17076                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17077                    .toggle_state(folded)
17078                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17079                        if folded {
17080                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17081                        } else {
17082                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17083                        }
17084                    }))
17085                    .into_any_element(),
17086            )
17087        } else {
17088            None
17089        }
17090    }
17091
17092    pub fn render_crease_trailer(
17093        &self,
17094        buffer_row: MultiBufferRow,
17095        window: &mut Window,
17096        cx: &mut App,
17097    ) -> Option<AnyElement> {
17098        let folded = self.is_line_folded(buffer_row);
17099        if let Crease::Inline { render_trailer, .. } = self
17100            .crease_snapshot
17101            .query_row(buffer_row, &self.buffer_snapshot)?
17102        {
17103            let render_trailer = render_trailer.as_ref()?;
17104            Some(render_trailer(buffer_row, folded, window, cx))
17105        } else {
17106            None
17107        }
17108    }
17109}
17110
17111impl Deref for EditorSnapshot {
17112    type Target = DisplaySnapshot;
17113
17114    fn deref(&self) -> &Self::Target {
17115        &self.display_snapshot
17116    }
17117}
17118
17119#[derive(Clone, Debug, PartialEq, Eq)]
17120pub enum EditorEvent {
17121    InputIgnored {
17122        text: Arc<str>,
17123    },
17124    InputHandled {
17125        utf16_range_to_replace: Option<Range<isize>>,
17126        text: Arc<str>,
17127    },
17128    ExcerptsAdded {
17129        buffer: Entity<Buffer>,
17130        predecessor: ExcerptId,
17131        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17132    },
17133    ExcerptsRemoved {
17134        ids: Vec<ExcerptId>,
17135    },
17136    BufferFoldToggled {
17137        ids: Vec<ExcerptId>,
17138        folded: bool,
17139    },
17140    ExcerptsEdited {
17141        ids: Vec<ExcerptId>,
17142    },
17143    ExcerptsExpanded {
17144        ids: Vec<ExcerptId>,
17145    },
17146    BufferEdited,
17147    Edited {
17148        transaction_id: clock::Lamport,
17149    },
17150    Reparsed(BufferId),
17151    Focused,
17152    FocusedIn,
17153    Blurred,
17154    DirtyChanged,
17155    Saved,
17156    TitleChanged,
17157    DiffBaseChanged,
17158    SelectionsChanged {
17159        local: bool,
17160    },
17161    ScrollPositionChanged {
17162        local: bool,
17163        autoscroll: bool,
17164    },
17165    Closed,
17166    TransactionUndone {
17167        transaction_id: clock::Lamport,
17168    },
17169    TransactionBegun {
17170        transaction_id: clock::Lamport,
17171    },
17172    Reloaded,
17173    CursorShapeChanged,
17174}
17175
17176impl EventEmitter<EditorEvent> for Editor {}
17177
17178impl Focusable for Editor {
17179    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17180        self.focus_handle.clone()
17181    }
17182}
17183
17184impl Render for Editor {
17185    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17186        let settings = ThemeSettings::get_global(cx);
17187
17188        let mut text_style = match self.mode {
17189            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17190                color: cx.theme().colors().editor_foreground,
17191                font_family: settings.ui_font.family.clone(),
17192                font_features: settings.ui_font.features.clone(),
17193                font_fallbacks: settings.ui_font.fallbacks.clone(),
17194                font_size: rems(0.875).into(),
17195                font_weight: settings.ui_font.weight,
17196                line_height: relative(settings.buffer_line_height.value()),
17197                ..Default::default()
17198            },
17199            EditorMode::Full => TextStyle {
17200                color: cx.theme().colors().editor_foreground,
17201                font_family: settings.buffer_font.family.clone(),
17202                font_features: settings.buffer_font.features.clone(),
17203                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17204                font_size: settings.buffer_font_size(cx).into(),
17205                font_weight: settings.buffer_font.weight,
17206                line_height: relative(settings.buffer_line_height.value()),
17207                ..Default::default()
17208            },
17209        };
17210        if let Some(text_style_refinement) = &self.text_style_refinement {
17211            text_style.refine(text_style_refinement)
17212        }
17213
17214        let background = match self.mode {
17215            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17216            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17217            EditorMode::Full => cx.theme().colors().editor_background,
17218        };
17219
17220        EditorElement::new(
17221            &cx.entity(),
17222            EditorStyle {
17223                background,
17224                local_player: cx.theme().players().local(),
17225                text: text_style,
17226                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17227                syntax: cx.theme().syntax().clone(),
17228                status: cx.theme().status().clone(),
17229                inlay_hints_style: make_inlay_hints_style(cx),
17230                inline_completion_styles: make_suggestion_styles(cx),
17231                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17232            },
17233        )
17234    }
17235}
17236
17237impl EntityInputHandler for Editor {
17238    fn text_for_range(
17239        &mut self,
17240        range_utf16: Range<usize>,
17241        adjusted_range: &mut Option<Range<usize>>,
17242        _: &mut Window,
17243        cx: &mut Context<Self>,
17244    ) -> Option<String> {
17245        let snapshot = self.buffer.read(cx).read(cx);
17246        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17247        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17248        if (start.0..end.0) != range_utf16 {
17249            adjusted_range.replace(start.0..end.0);
17250        }
17251        Some(snapshot.text_for_range(start..end).collect())
17252    }
17253
17254    fn selected_text_range(
17255        &mut self,
17256        ignore_disabled_input: bool,
17257        _: &mut Window,
17258        cx: &mut Context<Self>,
17259    ) -> Option<UTF16Selection> {
17260        // Prevent the IME menu from appearing when holding down an alphabetic key
17261        // while input is disabled.
17262        if !ignore_disabled_input && !self.input_enabled {
17263            return None;
17264        }
17265
17266        let selection = self.selections.newest::<OffsetUtf16>(cx);
17267        let range = selection.range();
17268
17269        Some(UTF16Selection {
17270            range: range.start.0..range.end.0,
17271            reversed: selection.reversed,
17272        })
17273    }
17274
17275    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17276        let snapshot = self.buffer.read(cx).read(cx);
17277        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17278        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17279    }
17280
17281    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17282        self.clear_highlights::<InputComposition>(cx);
17283        self.ime_transaction.take();
17284    }
17285
17286    fn replace_text_in_range(
17287        &mut self,
17288        range_utf16: Option<Range<usize>>,
17289        text: &str,
17290        window: &mut Window,
17291        cx: &mut Context<Self>,
17292    ) {
17293        if !self.input_enabled {
17294            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17295            return;
17296        }
17297
17298        self.transact(window, cx, |this, window, cx| {
17299            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17300                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17301                Some(this.selection_replacement_ranges(range_utf16, cx))
17302            } else {
17303                this.marked_text_ranges(cx)
17304            };
17305
17306            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17307                let newest_selection_id = this.selections.newest_anchor().id;
17308                this.selections
17309                    .all::<OffsetUtf16>(cx)
17310                    .iter()
17311                    .zip(ranges_to_replace.iter())
17312                    .find_map(|(selection, range)| {
17313                        if selection.id == newest_selection_id {
17314                            Some(
17315                                (range.start.0 as isize - selection.head().0 as isize)
17316                                    ..(range.end.0 as isize - selection.head().0 as isize),
17317                            )
17318                        } else {
17319                            None
17320                        }
17321                    })
17322            });
17323
17324            cx.emit(EditorEvent::InputHandled {
17325                utf16_range_to_replace: range_to_replace,
17326                text: text.into(),
17327            });
17328
17329            if let Some(new_selected_ranges) = new_selected_ranges {
17330                this.change_selections(None, window, cx, |selections| {
17331                    selections.select_ranges(new_selected_ranges)
17332                });
17333                this.backspace(&Default::default(), window, cx);
17334            }
17335
17336            this.handle_input(text, window, cx);
17337        });
17338
17339        if let Some(transaction) = self.ime_transaction {
17340            self.buffer.update(cx, |buffer, cx| {
17341                buffer.group_until_transaction(transaction, cx);
17342            });
17343        }
17344
17345        self.unmark_text(window, cx);
17346    }
17347
17348    fn replace_and_mark_text_in_range(
17349        &mut self,
17350        range_utf16: Option<Range<usize>>,
17351        text: &str,
17352        new_selected_range_utf16: Option<Range<usize>>,
17353        window: &mut Window,
17354        cx: &mut Context<Self>,
17355    ) {
17356        if !self.input_enabled {
17357            return;
17358        }
17359
17360        let transaction = self.transact(window, cx, |this, window, cx| {
17361            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17362                let snapshot = this.buffer.read(cx).read(cx);
17363                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17364                    for marked_range in &mut marked_ranges {
17365                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17366                        marked_range.start.0 += relative_range_utf16.start;
17367                        marked_range.start =
17368                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17369                        marked_range.end =
17370                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17371                    }
17372                }
17373                Some(marked_ranges)
17374            } else if let Some(range_utf16) = range_utf16 {
17375                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17376                Some(this.selection_replacement_ranges(range_utf16, cx))
17377            } else {
17378                None
17379            };
17380
17381            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17382                let newest_selection_id = this.selections.newest_anchor().id;
17383                this.selections
17384                    .all::<OffsetUtf16>(cx)
17385                    .iter()
17386                    .zip(ranges_to_replace.iter())
17387                    .find_map(|(selection, range)| {
17388                        if selection.id == newest_selection_id {
17389                            Some(
17390                                (range.start.0 as isize - selection.head().0 as isize)
17391                                    ..(range.end.0 as isize - selection.head().0 as isize),
17392                            )
17393                        } else {
17394                            None
17395                        }
17396                    })
17397            });
17398
17399            cx.emit(EditorEvent::InputHandled {
17400                utf16_range_to_replace: range_to_replace,
17401                text: text.into(),
17402            });
17403
17404            if let Some(ranges) = ranges_to_replace {
17405                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17406            }
17407
17408            let marked_ranges = {
17409                let snapshot = this.buffer.read(cx).read(cx);
17410                this.selections
17411                    .disjoint_anchors()
17412                    .iter()
17413                    .map(|selection| {
17414                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17415                    })
17416                    .collect::<Vec<_>>()
17417            };
17418
17419            if text.is_empty() {
17420                this.unmark_text(window, cx);
17421            } else {
17422                this.highlight_text::<InputComposition>(
17423                    marked_ranges.clone(),
17424                    HighlightStyle {
17425                        underline: Some(UnderlineStyle {
17426                            thickness: px(1.),
17427                            color: None,
17428                            wavy: false,
17429                        }),
17430                        ..Default::default()
17431                    },
17432                    cx,
17433                );
17434            }
17435
17436            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17437            let use_autoclose = this.use_autoclose;
17438            let use_auto_surround = this.use_auto_surround;
17439            this.set_use_autoclose(false);
17440            this.set_use_auto_surround(false);
17441            this.handle_input(text, window, cx);
17442            this.set_use_autoclose(use_autoclose);
17443            this.set_use_auto_surround(use_auto_surround);
17444
17445            if let Some(new_selected_range) = new_selected_range_utf16 {
17446                let snapshot = this.buffer.read(cx).read(cx);
17447                let new_selected_ranges = marked_ranges
17448                    .into_iter()
17449                    .map(|marked_range| {
17450                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17451                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17452                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17453                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17454                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17455                    })
17456                    .collect::<Vec<_>>();
17457
17458                drop(snapshot);
17459                this.change_selections(None, window, cx, |selections| {
17460                    selections.select_ranges(new_selected_ranges)
17461                });
17462            }
17463        });
17464
17465        self.ime_transaction = self.ime_transaction.or(transaction);
17466        if let Some(transaction) = self.ime_transaction {
17467            self.buffer.update(cx, |buffer, cx| {
17468                buffer.group_until_transaction(transaction, cx);
17469            });
17470        }
17471
17472        if self.text_highlights::<InputComposition>(cx).is_none() {
17473            self.ime_transaction.take();
17474        }
17475    }
17476
17477    fn bounds_for_range(
17478        &mut self,
17479        range_utf16: Range<usize>,
17480        element_bounds: gpui::Bounds<Pixels>,
17481        window: &mut Window,
17482        cx: &mut Context<Self>,
17483    ) -> Option<gpui::Bounds<Pixels>> {
17484        let text_layout_details = self.text_layout_details(window);
17485        let gpui::Size {
17486            width: em_width,
17487            height: line_height,
17488        } = self.character_size(window);
17489
17490        let snapshot = self.snapshot(window, cx);
17491        let scroll_position = snapshot.scroll_position();
17492        let scroll_left = scroll_position.x * em_width;
17493
17494        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17495        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17496            + self.gutter_dimensions.width
17497            + self.gutter_dimensions.margin;
17498        let y = line_height * (start.row().as_f32() - scroll_position.y);
17499
17500        Some(Bounds {
17501            origin: element_bounds.origin + point(x, y),
17502            size: size(em_width, line_height),
17503        })
17504    }
17505
17506    fn character_index_for_point(
17507        &mut self,
17508        point: gpui::Point<Pixels>,
17509        _window: &mut Window,
17510        _cx: &mut Context<Self>,
17511    ) -> Option<usize> {
17512        let position_map = self.last_position_map.as_ref()?;
17513        if !position_map.text_hitbox.contains(&point) {
17514            return None;
17515        }
17516        let display_point = position_map.point_for_position(point).previous_valid;
17517        let anchor = position_map
17518            .snapshot
17519            .display_point_to_anchor(display_point, Bias::Left);
17520        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17521        Some(utf16_offset.0)
17522    }
17523}
17524
17525trait SelectionExt {
17526    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17527    fn spanned_rows(
17528        &self,
17529        include_end_if_at_line_start: bool,
17530        map: &DisplaySnapshot,
17531    ) -> Range<MultiBufferRow>;
17532}
17533
17534impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17535    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17536        let start = self
17537            .start
17538            .to_point(&map.buffer_snapshot)
17539            .to_display_point(map);
17540        let end = self
17541            .end
17542            .to_point(&map.buffer_snapshot)
17543            .to_display_point(map);
17544        if self.reversed {
17545            end..start
17546        } else {
17547            start..end
17548        }
17549    }
17550
17551    fn spanned_rows(
17552        &self,
17553        include_end_if_at_line_start: bool,
17554        map: &DisplaySnapshot,
17555    ) -> Range<MultiBufferRow> {
17556        let start = self.start.to_point(&map.buffer_snapshot);
17557        let mut end = self.end.to_point(&map.buffer_snapshot);
17558        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17559            end.row -= 1;
17560        }
17561
17562        let buffer_start = map.prev_line_boundary(start).0;
17563        let buffer_end = map.next_line_boundary(end).0;
17564        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17565    }
17566}
17567
17568impl<T: InvalidationRegion> InvalidationStack<T> {
17569    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17570    where
17571        S: Clone + ToOffset,
17572    {
17573        while let Some(region) = self.last() {
17574            let all_selections_inside_invalidation_ranges =
17575                if selections.len() == region.ranges().len() {
17576                    selections
17577                        .iter()
17578                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17579                        .all(|(selection, invalidation_range)| {
17580                            let head = selection.head().to_offset(buffer);
17581                            invalidation_range.start <= head && invalidation_range.end >= head
17582                        })
17583                } else {
17584                    false
17585                };
17586
17587            if all_selections_inside_invalidation_ranges {
17588                break;
17589            } else {
17590                self.pop();
17591            }
17592        }
17593    }
17594}
17595
17596impl<T> Default for InvalidationStack<T> {
17597    fn default() -> Self {
17598        Self(Default::default())
17599    }
17600}
17601
17602impl<T> Deref for InvalidationStack<T> {
17603    type Target = Vec<T>;
17604
17605    fn deref(&self) -> &Self::Target {
17606        &self.0
17607    }
17608}
17609
17610impl<T> DerefMut for InvalidationStack<T> {
17611    fn deref_mut(&mut self) -> &mut Self::Target {
17612        &mut self.0
17613    }
17614}
17615
17616impl InvalidationRegion for SnippetState {
17617    fn ranges(&self) -> &[Range<Anchor>] {
17618        &self.ranges[self.active_index]
17619    }
17620}
17621
17622pub fn diagnostic_block_renderer(
17623    diagnostic: Diagnostic,
17624    max_message_rows: Option<u8>,
17625    allow_closing: bool,
17626    _is_valid: bool,
17627) -> RenderBlock {
17628    let (text_without_backticks, code_ranges) =
17629        highlight_diagnostic_message(&diagnostic, max_message_rows);
17630
17631    Arc::new(move |cx: &mut BlockContext| {
17632        let group_id: SharedString = cx.block_id.to_string().into();
17633
17634        let mut text_style = cx.window.text_style().clone();
17635        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17636        let theme_settings = ThemeSettings::get_global(cx);
17637        text_style.font_family = theme_settings.buffer_font.family.clone();
17638        text_style.font_style = theme_settings.buffer_font.style;
17639        text_style.font_features = theme_settings.buffer_font.features.clone();
17640        text_style.font_weight = theme_settings.buffer_font.weight;
17641
17642        let multi_line_diagnostic = diagnostic.message.contains('\n');
17643
17644        let buttons = |diagnostic: &Diagnostic| {
17645            if multi_line_diagnostic {
17646                v_flex()
17647            } else {
17648                h_flex()
17649            }
17650            .when(allow_closing, |div| {
17651                div.children(diagnostic.is_primary.then(|| {
17652                    IconButton::new("close-block", IconName::XCircle)
17653                        .icon_color(Color::Muted)
17654                        .size(ButtonSize::Compact)
17655                        .style(ButtonStyle::Transparent)
17656                        .visible_on_hover(group_id.clone())
17657                        .on_click(move |_click, window, cx| {
17658                            window.dispatch_action(Box::new(Cancel), cx)
17659                        })
17660                        .tooltip(|window, cx| {
17661                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17662                        })
17663                }))
17664            })
17665            .child(
17666                IconButton::new("copy-block", IconName::Copy)
17667                    .icon_color(Color::Muted)
17668                    .size(ButtonSize::Compact)
17669                    .style(ButtonStyle::Transparent)
17670                    .visible_on_hover(group_id.clone())
17671                    .on_click({
17672                        let message = diagnostic.message.clone();
17673                        move |_click, _, cx| {
17674                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17675                        }
17676                    })
17677                    .tooltip(Tooltip::text("Copy diagnostic message")),
17678            )
17679        };
17680
17681        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17682            AvailableSpace::min_size(),
17683            cx.window,
17684            cx.app,
17685        );
17686
17687        h_flex()
17688            .id(cx.block_id)
17689            .group(group_id.clone())
17690            .relative()
17691            .size_full()
17692            .block_mouse_down()
17693            .pl(cx.gutter_dimensions.width)
17694            .w(cx.max_width - cx.gutter_dimensions.full_width())
17695            .child(
17696                div()
17697                    .flex()
17698                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17699                    .flex_shrink(),
17700            )
17701            .child(buttons(&diagnostic))
17702            .child(div().flex().flex_shrink_0().child(
17703                StyledText::new(text_without_backticks.clone()).with_highlights(
17704                    &text_style,
17705                    code_ranges.iter().map(|range| {
17706                        (
17707                            range.clone(),
17708                            HighlightStyle {
17709                                font_weight: Some(FontWeight::BOLD),
17710                                ..Default::default()
17711                            },
17712                        )
17713                    }),
17714                ),
17715            ))
17716            .into_any_element()
17717    })
17718}
17719
17720fn inline_completion_edit_text(
17721    current_snapshot: &BufferSnapshot,
17722    edits: &[(Range<Anchor>, String)],
17723    edit_preview: &EditPreview,
17724    include_deletions: bool,
17725    cx: &App,
17726) -> HighlightedText {
17727    let edits = edits
17728        .iter()
17729        .map(|(anchor, text)| {
17730            (
17731                anchor.start.text_anchor..anchor.end.text_anchor,
17732                text.clone(),
17733            )
17734        })
17735        .collect::<Vec<_>>();
17736
17737    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17738}
17739
17740pub fn highlight_diagnostic_message(
17741    diagnostic: &Diagnostic,
17742    mut max_message_rows: Option<u8>,
17743) -> (SharedString, Vec<Range<usize>>) {
17744    let mut text_without_backticks = String::new();
17745    let mut code_ranges = Vec::new();
17746
17747    if let Some(source) = &diagnostic.source {
17748        text_without_backticks.push_str(source);
17749        code_ranges.push(0..source.len());
17750        text_without_backticks.push_str(": ");
17751    }
17752
17753    let mut prev_offset = 0;
17754    let mut in_code_block = false;
17755    let has_row_limit = max_message_rows.is_some();
17756    let mut newline_indices = diagnostic
17757        .message
17758        .match_indices('\n')
17759        .filter(|_| has_row_limit)
17760        .map(|(ix, _)| ix)
17761        .fuse()
17762        .peekable();
17763
17764    for (quote_ix, _) in diagnostic
17765        .message
17766        .match_indices('`')
17767        .chain([(diagnostic.message.len(), "")])
17768    {
17769        let mut first_newline_ix = None;
17770        let mut last_newline_ix = None;
17771        while let Some(newline_ix) = newline_indices.peek() {
17772            if *newline_ix < quote_ix {
17773                if first_newline_ix.is_none() {
17774                    first_newline_ix = Some(*newline_ix);
17775                }
17776                last_newline_ix = Some(*newline_ix);
17777
17778                if let Some(rows_left) = &mut max_message_rows {
17779                    if *rows_left == 0 {
17780                        break;
17781                    } else {
17782                        *rows_left -= 1;
17783                    }
17784                }
17785                let _ = newline_indices.next();
17786            } else {
17787                break;
17788            }
17789        }
17790        let prev_len = text_without_backticks.len();
17791        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17792        text_without_backticks.push_str(new_text);
17793        if in_code_block {
17794            code_ranges.push(prev_len..text_without_backticks.len());
17795        }
17796        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17797        in_code_block = !in_code_block;
17798        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17799            text_without_backticks.push_str("...");
17800            break;
17801        }
17802    }
17803
17804    (text_without_backticks.into(), code_ranges)
17805}
17806
17807fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17808    match severity {
17809        DiagnosticSeverity::ERROR => colors.error,
17810        DiagnosticSeverity::WARNING => colors.warning,
17811        DiagnosticSeverity::INFORMATION => colors.info,
17812        DiagnosticSeverity::HINT => colors.info,
17813        _ => colors.ignored,
17814    }
17815}
17816
17817pub fn styled_runs_for_code_label<'a>(
17818    label: &'a CodeLabel,
17819    syntax_theme: &'a theme::SyntaxTheme,
17820) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17821    let fade_out = HighlightStyle {
17822        fade_out: Some(0.35),
17823        ..Default::default()
17824    };
17825
17826    let mut prev_end = label.filter_range.end;
17827    label
17828        .runs
17829        .iter()
17830        .enumerate()
17831        .flat_map(move |(ix, (range, highlight_id))| {
17832            let style = if let Some(style) = highlight_id.style(syntax_theme) {
17833                style
17834            } else {
17835                return Default::default();
17836            };
17837            let mut muted_style = style;
17838            muted_style.highlight(fade_out);
17839
17840            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17841            if range.start >= label.filter_range.end {
17842                if range.start > prev_end {
17843                    runs.push((prev_end..range.start, fade_out));
17844                }
17845                runs.push((range.clone(), muted_style));
17846            } else if range.end <= label.filter_range.end {
17847                runs.push((range.clone(), style));
17848            } else {
17849                runs.push((range.start..label.filter_range.end, style));
17850                runs.push((label.filter_range.end..range.end, muted_style));
17851            }
17852            prev_end = cmp::max(prev_end, range.end);
17853
17854            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17855                runs.push((prev_end..label.text.len(), fade_out));
17856            }
17857
17858            runs
17859        })
17860}
17861
17862pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17863    let mut prev_index = 0;
17864    let mut prev_codepoint: Option<char> = None;
17865    text.char_indices()
17866        .chain([(text.len(), '\0')])
17867        .filter_map(move |(index, codepoint)| {
17868            let prev_codepoint = prev_codepoint.replace(codepoint)?;
17869            let is_boundary = index == text.len()
17870                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17871                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17872            if is_boundary {
17873                let chunk = &text[prev_index..index];
17874                prev_index = index;
17875                Some(chunk)
17876            } else {
17877                None
17878            }
17879        })
17880}
17881
17882pub trait RangeToAnchorExt: Sized {
17883    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17884
17885    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17886        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17887        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17888    }
17889}
17890
17891impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17892    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17893        let start_offset = self.start.to_offset(snapshot);
17894        let end_offset = self.end.to_offset(snapshot);
17895        if start_offset == end_offset {
17896            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17897        } else {
17898            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17899        }
17900    }
17901}
17902
17903pub trait RowExt {
17904    fn as_f32(&self) -> f32;
17905
17906    fn next_row(&self) -> Self;
17907
17908    fn previous_row(&self) -> Self;
17909
17910    fn minus(&self, other: Self) -> u32;
17911}
17912
17913impl RowExt for DisplayRow {
17914    fn as_f32(&self) -> f32 {
17915        self.0 as f32
17916    }
17917
17918    fn next_row(&self) -> Self {
17919        Self(self.0 + 1)
17920    }
17921
17922    fn previous_row(&self) -> Self {
17923        Self(self.0.saturating_sub(1))
17924    }
17925
17926    fn minus(&self, other: Self) -> u32 {
17927        self.0 - other.0
17928    }
17929}
17930
17931impl RowExt for MultiBufferRow {
17932    fn as_f32(&self) -> f32 {
17933        self.0 as f32
17934    }
17935
17936    fn next_row(&self) -> Self {
17937        Self(self.0 + 1)
17938    }
17939
17940    fn previous_row(&self) -> Self {
17941        Self(self.0.saturating_sub(1))
17942    }
17943
17944    fn minus(&self, other: Self) -> u32 {
17945        self.0 - other.0
17946    }
17947}
17948
17949trait RowRangeExt {
17950    type Row;
17951
17952    fn len(&self) -> usize;
17953
17954    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17955}
17956
17957impl RowRangeExt for Range<MultiBufferRow> {
17958    type Row = MultiBufferRow;
17959
17960    fn len(&self) -> usize {
17961        (self.end.0 - self.start.0) as usize
17962    }
17963
17964    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17965        (self.start.0..self.end.0).map(MultiBufferRow)
17966    }
17967}
17968
17969impl RowRangeExt for Range<DisplayRow> {
17970    type Row = DisplayRow;
17971
17972    fn len(&self) -> usize {
17973        (self.end.0 - self.start.0) as usize
17974    }
17975
17976    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17977        (self.start.0..self.end.0).map(DisplayRow)
17978    }
17979}
17980
17981/// If select range has more than one line, we
17982/// just point the cursor to range.start.
17983fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17984    if range.start.row == range.end.row {
17985        range
17986    } else {
17987        range.start..range.start
17988    }
17989}
17990pub struct KillRing(ClipboardItem);
17991impl Global for KillRing {}
17992
17993const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17994
17995fn all_edits_insertions_or_deletions(
17996    edits: &Vec<(Range<Anchor>, String)>,
17997    snapshot: &MultiBufferSnapshot,
17998) -> bool {
17999    let mut all_insertions = true;
18000    let mut all_deletions = true;
18001
18002    for (range, new_text) in edits.iter() {
18003        let range_is_empty = range.to_offset(&snapshot).is_empty();
18004        let text_is_empty = new_text.is_empty();
18005
18006        if range_is_empty != text_is_empty {
18007            if range_is_empty {
18008                all_deletions = false;
18009            } else {
18010                all_insertions = false;
18011            }
18012        } else {
18013            return false;
18014        }
18015
18016        if !all_insertions && !all_deletions {
18017            return false;
18018        }
18019    }
18020    all_insertions || all_deletions
18021}