editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkSecondaryStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use ::git::{status::FileStatus, Restore};
   77use code_context_menus::{
   78    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   79    CompletionsMenu, ContextMenuOrigin,
   80};
   81use git::blame::GitBlame;
   82use gpui::{
   83    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   84    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   85    ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
   86    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   87    HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   88    ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
   89    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   90    WeakEntity, WeakFocusHandle, Window,
   91};
   92use highlight_matching_bracket::refresh_matching_bracket_highlights;
   93use hover_popover::{hide_hover, HoverState};
   94use indent_guides::ActiveIndentGuidesState;
   95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   96pub use inline_completion::Direction;
   97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   98pub use items::MAX_TAB_TITLE_LEN;
   99use itertools::Itertools;
  100use language::{
  101    language_settings::{
  102        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  103    },
  104    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  105    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, DiskState,
  106    EditPredictionsMode, EditPreview, HighlightedText, IndentKind, IndentSize, Language,
  107    OffsetRangeExt, Point, Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  108};
  109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  110use linked_editing_ranges::refresh_linked_ranges;
  111use mouse_context_menu::MouseContextMenu;
  112use persistence::DB;
  113pub use proposed_changes_editor::{
  114    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  115};
  116use smallvec::smallvec;
  117use std::iter::Peekable;
  118use task::{ResolvedTask, TaskTemplate, TaskVariables};
  119
  120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  121pub use lsp::CompletionContext;
  122use lsp::{
  123    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  124    LanguageServerId, LanguageServerName,
  125};
  126
  127use language::BufferSnapshot;
  128use movement::TextLayoutDetails;
  129pub use multi_buffer::{
  130    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  131    ToOffset, ToPoint,
  132};
  133use multi_buffer::{
  134    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  135    ToOffsetUtf16,
  136};
  137use project::{
  138    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  139    project_settings::{GitGutterSetting, ProjectSettings},
  140    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  141    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  142};
  143use rand::prelude::*;
  144use rpc::{proto::*, ErrorExt};
  145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  146use selections_collection::{
  147    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  148};
  149use serde::{Deserialize, Serialize};
  150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  151use smallvec::SmallVec;
  152use snippet::Snippet;
  153use std::{
  154    any::TypeId,
  155    borrow::Cow,
  156    cell::RefCell,
  157    cmp::{self, Ordering, Reverse},
  158    mem,
  159    num::NonZeroU32,
  160    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  161    path::{Path, PathBuf},
  162    rc::Rc,
  163    sync::Arc,
  164    time::{Duration, Instant},
  165};
  166pub use sum_tree::Bias;
  167use sum_tree::TreeMap;
  168use text::{BufferId, OffsetUtf16, Rope};
  169use theme::{
  170    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  171    ThemeColors, ThemeSettings,
  172};
  173use ui::{
  174    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  175    Tooltip,
  176};
  177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  178use workspace::{
  179    item::{ItemHandle, PreviewTabsSettings},
  180    ItemId, RestoreOnStartupBehavior,
  181};
  182use workspace::{
  183    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  184    WorkspaceSettings,
  185};
  186use workspace::{
  187    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  188};
  189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  190
  191use crate::hover_links::{find_url, find_url_from_range};
  192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  193
  194pub const FILE_HEADER_HEIGHT: u32 = 2;
  195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  199const MAX_LINE_LEN: usize = 1024;
  200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  203#[doc(hidden)]
  204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  205
  206pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  207pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  208
  209pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  210pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  211
  212const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  213    alt: true,
  214    shift: true,
  215    control: false,
  216    platform: false,
  217    function: false,
  218};
  219
  220#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  221pub enum InlayId {
  222    InlineCompletion(usize),
  223    Hint(usize),
  224}
  225
  226impl InlayId {
  227    fn id(&self) -> usize {
  228        match self {
  229            Self::InlineCompletion(id) => *id,
  230            Self::Hint(id) => *id,
  231        }
  232    }
  233}
  234
  235enum DocumentHighlightRead {}
  236enum DocumentHighlightWrite {}
  237enum InputComposition {}
  238enum SelectedTextHighlight {}
  239
  240#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  241pub enum Navigated {
  242    Yes,
  243    No,
  244}
  245
  246impl Navigated {
  247    pub fn from_bool(yes: bool) -> Navigated {
  248        if yes {
  249            Navigated::Yes
  250        } else {
  251            Navigated::No
  252        }
  253    }
  254}
  255
  256pub fn init_settings(cx: &mut App) {
  257    EditorSettings::register(cx);
  258}
  259
  260pub fn init(cx: &mut App) {
  261    init_settings(cx);
  262
  263    workspace::register_project_item::<Editor>(cx);
  264    workspace::FollowableViewRegistry::register::<Editor>(cx);
  265    workspace::register_serializable_item::<Editor>(cx);
  266
  267    cx.observe_new(
  268        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  269            workspace.register_action(Editor::new_file);
  270            workspace.register_action(Editor::new_file_vertical);
  271            workspace.register_action(Editor::new_file_horizontal);
  272            workspace.register_action(Editor::cancel_language_server_work);
  273        },
  274    )
  275    .detach();
  276
  277    cx.on_action(move |_: &workspace::NewFile, cx| {
  278        let app_state = workspace::AppState::global(cx);
  279        if let Some(app_state) = app_state.upgrade() {
  280            workspace::open_new(
  281                Default::default(),
  282                app_state,
  283                cx,
  284                |workspace, window, cx| {
  285                    Editor::new_file(workspace, &Default::default(), window, cx)
  286                },
  287            )
  288            .detach();
  289        }
  290    });
  291    cx.on_action(move |_: &workspace::NewWindow, cx| {
  292        let app_state = workspace::AppState::global(cx);
  293        if let Some(app_state) = app_state.upgrade() {
  294            workspace::open_new(
  295                Default::default(),
  296                app_state,
  297                cx,
  298                |workspace, window, cx| {
  299                    cx.activate(true);
  300                    Editor::new_file(workspace, &Default::default(), window, cx)
  301                },
  302            )
  303            .detach();
  304        }
  305    });
  306}
  307
  308pub struct SearchWithinRange;
  309
  310trait InvalidationRegion {
  311    fn ranges(&self) -> &[Range<Anchor>];
  312}
  313
  314#[derive(Clone, Debug, PartialEq)]
  315pub enum SelectPhase {
  316    Begin {
  317        position: DisplayPoint,
  318        add: bool,
  319        click_count: usize,
  320    },
  321    BeginColumnar {
  322        position: DisplayPoint,
  323        reset: bool,
  324        goal_column: u32,
  325    },
  326    Extend {
  327        position: DisplayPoint,
  328        click_count: usize,
  329    },
  330    Update {
  331        position: DisplayPoint,
  332        goal_column: u32,
  333        scroll_delta: gpui::Point<f32>,
  334    },
  335    End,
  336}
  337
  338#[derive(Clone, Debug)]
  339pub enum SelectMode {
  340    Character,
  341    Word(Range<Anchor>),
  342    Line(Range<Anchor>),
  343    All,
  344}
  345
  346#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  347pub enum EditorMode {
  348    SingleLine { auto_width: bool },
  349    AutoHeight { max_lines: usize },
  350    Full,
  351}
  352
  353#[derive(Copy, Clone, Debug)]
  354pub enum SoftWrap {
  355    /// Prefer not to wrap at all.
  356    ///
  357    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  358    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  359    GitDiff,
  360    /// Prefer a single line generally, unless an overly long line is encountered.
  361    None,
  362    /// Soft wrap lines that exceed the editor width.
  363    EditorWidth,
  364    /// Soft wrap lines at the preferred line length.
  365    Column(u32),
  366    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  367    Bounded(u32),
  368}
  369
  370#[derive(Clone)]
  371pub struct EditorStyle {
  372    pub background: Hsla,
  373    pub local_player: PlayerColor,
  374    pub text: TextStyle,
  375    pub scrollbar_width: Pixels,
  376    pub syntax: Arc<SyntaxTheme>,
  377    pub status: StatusColors,
  378    pub inlay_hints_style: HighlightStyle,
  379    pub inline_completion_styles: InlineCompletionStyles,
  380    pub unnecessary_code_fade: f32,
  381}
  382
  383impl Default for EditorStyle {
  384    fn default() -> Self {
  385        Self {
  386            background: Hsla::default(),
  387            local_player: PlayerColor::default(),
  388            text: TextStyle::default(),
  389            scrollbar_width: Pixels::default(),
  390            syntax: Default::default(),
  391            // HACK: Status colors don't have a real default.
  392            // We should look into removing the status colors from the editor
  393            // style and retrieve them directly from the theme.
  394            status: StatusColors::dark(),
  395            inlay_hints_style: HighlightStyle::default(),
  396            inline_completion_styles: InlineCompletionStyles {
  397                insertion: HighlightStyle::default(),
  398                whitespace: HighlightStyle::default(),
  399            },
  400            unnecessary_code_fade: Default::default(),
  401        }
  402    }
  403}
  404
  405pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  406    let show_background = language_settings::language_settings(None, None, cx)
  407        .inlay_hints
  408        .show_background;
  409
  410    HighlightStyle {
  411        color: Some(cx.theme().status().hint),
  412        background_color: show_background.then(|| cx.theme().status().hint_background),
  413        ..HighlightStyle::default()
  414    }
  415}
  416
  417pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  418    InlineCompletionStyles {
  419        insertion: HighlightStyle {
  420            color: Some(cx.theme().status().predictive),
  421            ..HighlightStyle::default()
  422        },
  423        whitespace: HighlightStyle {
  424            background_color: Some(cx.theme().status().created_background),
  425            ..HighlightStyle::default()
  426        },
  427    }
  428}
  429
  430type CompletionId = usize;
  431
  432pub(crate) enum EditDisplayMode {
  433    TabAccept,
  434    DiffPopover,
  435    Inline,
  436}
  437
  438enum InlineCompletion {
  439    Edit {
  440        edits: Vec<(Range<Anchor>, String)>,
  441        edit_preview: Option<EditPreview>,
  442        display_mode: EditDisplayMode,
  443        snapshot: BufferSnapshot,
  444    },
  445    Move {
  446        target: Anchor,
  447        snapshot: BufferSnapshot,
  448    },
  449}
  450
  451struct InlineCompletionState {
  452    inlay_ids: Vec<InlayId>,
  453    completion: InlineCompletion,
  454    completion_id: Option<SharedString>,
  455    invalidation_range: Range<Anchor>,
  456}
  457
  458enum EditPredictionSettings {
  459    Disabled,
  460    Enabled {
  461        show_in_menu: bool,
  462        preview_requires_modifier: bool,
  463    },
  464}
  465
  466enum InlineCompletionHighlight {}
  467
  468#[derive(Debug, Clone)]
  469struct InlineDiagnostic {
  470    message: SharedString,
  471    group_id: usize,
  472    is_primary: bool,
  473    start: Point,
  474    severity: DiagnosticSeverity,
  475}
  476
  477pub enum MenuInlineCompletionsPolicy {
  478    Never,
  479    ByProvider,
  480}
  481
  482pub enum EditPredictionPreview {
  483    /// Modifier is not pressed
  484    Inactive,
  485    /// Modifier pressed
  486    Active {
  487        previous_scroll_position: Option<ScrollAnchor>,
  488    },
  489}
  490
  491#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  492struct EditorActionId(usize);
  493
  494impl EditorActionId {
  495    pub fn post_inc(&mut self) -> Self {
  496        let answer = self.0;
  497
  498        *self = Self(answer + 1);
  499
  500        Self(answer)
  501    }
  502}
  503
  504// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  505// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  506
  507type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  508type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  509
  510#[derive(Default)]
  511struct ScrollbarMarkerState {
  512    scrollbar_size: Size<Pixels>,
  513    dirty: bool,
  514    markers: Arc<[PaintQuad]>,
  515    pending_refresh: Option<Task<Result<()>>>,
  516}
  517
  518impl ScrollbarMarkerState {
  519    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  520        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  521    }
  522}
  523
  524#[derive(Clone, Debug)]
  525struct RunnableTasks {
  526    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  527    offset: MultiBufferOffset,
  528    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  529    column: u32,
  530    // Values of all named captures, including those starting with '_'
  531    extra_variables: HashMap<String, String>,
  532    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  533    context_range: Range<BufferOffset>,
  534}
  535
  536impl RunnableTasks {
  537    fn resolve<'a>(
  538        &'a self,
  539        cx: &'a task::TaskContext,
  540    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  541        self.templates.iter().filter_map(|(kind, template)| {
  542            template
  543                .resolve_task(&kind.to_id_base(), cx)
  544                .map(|task| (kind.clone(), task))
  545        })
  546    }
  547}
  548
  549#[derive(Clone)]
  550struct ResolvedTasks {
  551    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  552    position: Anchor,
  553}
  554#[derive(Copy, Clone, Debug)]
  555struct MultiBufferOffset(usize);
  556#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  557struct BufferOffset(usize);
  558
  559// Addons allow storing per-editor state in other crates (e.g. Vim)
  560pub trait Addon: 'static {
  561    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  562
  563    fn render_buffer_header_controls(
  564        &self,
  565        _: &ExcerptInfo,
  566        _: &Window,
  567        _: &App,
  568    ) -> Option<AnyElement> {
  569        None
  570    }
  571
  572    fn to_any(&self) -> &dyn std::any::Any;
  573}
  574
  575#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  576pub enum IsVimMode {
  577    Yes,
  578    No,
  579}
  580
  581/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  582///
  583/// See the [module level documentation](self) for more information.
  584pub struct Editor {
  585    focus_handle: FocusHandle,
  586    last_focused_descendant: Option<WeakFocusHandle>,
  587    /// The text buffer being edited
  588    buffer: Entity<MultiBuffer>,
  589    /// Map of how text in the buffer should be displayed.
  590    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  591    pub display_map: Entity<DisplayMap>,
  592    pub selections: SelectionsCollection,
  593    pub scroll_manager: ScrollManager,
  594    /// When inline assist editors are linked, they all render cursors because
  595    /// typing enters text into each of them, even the ones that aren't focused.
  596    pub(crate) show_cursor_when_unfocused: bool,
  597    columnar_selection_tail: Option<Anchor>,
  598    add_selections_state: Option<AddSelectionsState>,
  599    select_next_state: Option<SelectNextState>,
  600    select_prev_state: Option<SelectNextState>,
  601    selection_history: SelectionHistory,
  602    autoclose_regions: Vec<AutocloseRegion>,
  603    snippet_stack: InvalidationStack<SnippetState>,
  604    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  605    ime_transaction: Option<TransactionId>,
  606    active_diagnostics: Option<ActiveDiagnosticGroup>,
  607    show_inline_diagnostics: bool,
  608    inline_diagnostics_update: Task<()>,
  609    inline_diagnostics_enabled: bool,
  610    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  611    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  612
  613    // TODO: make this a access method
  614    pub project: Option<Entity<Project>>,
  615    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  616    completion_provider: Option<Box<dyn CompletionProvider>>,
  617    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  618    blink_manager: Entity<BlinkManager>,
  619    show_cursor_names: bool,
  620    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  621    pub show_local_selections: bool,
  622    mode: EditorMode,
  623    show_breadcrumbs: bool,
  624    show_gutter: bool,
  625    show_scrollbars: bool,
  626    show_line_numbers: Option<bool>,
  627    use_relative_line_numbers: Option<bool>,
  628    show_git_diff_gutter: Option<bool>,
  629    show_code_actions: Option<bool>,
  630    show_runnables: Option<bool>,
  631    show_wrap_guides: Option<bool>,
  632    show_indent_guides: Option<bool>,
  633    placeholder_text: Option<Arc<str>>,
  634    highlight_order: usize,
  635    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  636    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  637    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  638    scrollbar_marker_state: ScrollbarMarkerState,
  639    active_indent_guides_state: ActiveIndentGuidesState,
  640    nav_history: Option<ItemNavHistory>,
  641    context_menu: RefCell<Option<CodeContextMenu>>,
  642    mouse_context_menu: Option<MouseContextMenu>,
  643    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  644    signature_help_state: SignatureHelpState,
  645    auto_signature_help: Option<bool>,
  646    find_all_references_task_sources: Vec<Anchor>,
  647    next_completion_id: CompletionId,
  648    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  649    code_actions_task: Option<Task<Result<()>>>,
  650    selection_highlight_task: Option<Task<()>>,
  651    document_highlights_task: Option<Task<()>>,
  652    linked_editing_range_task: Option<Task<Option<()>>>,
  653    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  654    pending_rename: Option<RenameState>,
  655    searchable: bool,
  656    cursor_shape: CursorShape,
  657    current_line_highlight: Option<CurrentLineHighlight>,
  658    collapse_matches: bool,
  659    autoindent_mode: Option<AutoindentMode>,
  660    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  661    input_enabled: bool,
  662    use_modal_editing: bool,
  663    read_only: bool,
  664    leader_peer_id: Option<PeerId>,
  665    remote_id: Option<ViewId>,
  666    hover_state: HoverState,
  667    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  668    gutter_hovered: bool,
  669    hovered_link_state: Option<HoveredLinkState>,
  670    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  671    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  672    active_inline_completion: Option<InlineCompletionState>,
  673    /// Used to prevent flickering as the user types while the menu is open
  674    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  675    edit_prediction_settings: EditPredictionSettings,
  676    inline_completions_hidden_for_vim_mode: bool,
  677    show_inline_completions_override: Option<bool>,
  678    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  679    edit_prediction_preview: EditPredictionPreview,
  680    edit_prediction_indent_conflict: bool,
  681    edit_prediction_requires_modifier_in_indent_conflict: bool,
  682    inlay_hint_cache: InlayHintCache,
  683    next_inlay_id: usize,
  684    _subscriptions: Vec<Subscription>,
  685    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  686    gutter_dimensions: GutterDimensions,
  687    style: Option<EditorStyle>,
  688    text_style_refinement: Option<TextStyleRefinement>,
  689    next_editor_action_id: EditorActionId,
  690    editor_actions:
  691        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  692    use_autoclose: bool,
  693    use_auto_surround: bool,
  694    auto_replace_emoji_shortcode: bool,
  695    show_git_blame_gutter: bool,
  696    show_git_blame_inline: bool,
  697    show_git_blame_inline_delay_task: Option<Task<()>>,
  698    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  699    git_blame_inline_enabled: bool,
  700    serialize_dirty_buffers: bool,
  701    show_selection_menu: Option<bool>,
  702    blame: Option<Entity<GitBlame>>,
  703    blame_subscription: Option<Subscription>,
  704    custom_context_menu: Option<
  705        Box<
  706            dyn 'static
  707                + Fn(
  708                    &mut Self,
  709                    DisplayPoint,
  710                    &mut Window,
  711                    &mut Context<Self>,
  712                ) -> Option<Entity<ui::ContextMenu>>,
  713        >,
  714    >,
  715    last_bounds: Option<Bounds<Pixels>>,
  716    last_position_map: Option<Rc<PositionMap>>,
  717    expect_bounds_change: Option<Bounds<Pixels>>,
  718    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  719    tasks_update_task: Option<Task<()>>,
  720    in_project_search: bool,
  721    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  722    breadcrumb_header: Option<String>,
  723    focused_block: Option<FocusedBlock>,
  724    next_scroll_position: NextScrollCursorCenterTopBottom,
  725    addons: HashMap<TypeId, Box<dyn Addon>>,
  726    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  727    load_diff_task: Option<Shared<Task<()>>>,
  728    selection_mark_mode: bool,
  729    toggle_fold_multiple_buffers: Task<()>,
  730    _scroll_cursor_center_top_bottom_task: Task<()>,
  731    serialize_selections: Task<()>,
  732}
  733
  734#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  735enum NextScrollCursorCenterTopBottom {
  736    #[default]
  737    Center,
  738    Top,
  739    Bottom,
  740}
  741
  742impl NextScrollCursorCenterTopBottom {
  743    fn next(&self) -> Self {
  744        match self {
  745            Self::Center => Self::Top,
  746            Self::Top => Self::Bottom,
  747            Self::Bottom => Self::Center,
  748        }
  749    }
  750}
  751
  752#[derive(Clone)]
  753pub struct EditorSnapshot {
  754    pub mode: EditorMode,
  755    show_gutter: bool,
  756    show_line_numbers: Option<bool>,
  757    show_git_diff_gutter: Option<bool>,
  758    show_code_actions: Option<bool>,
  759    show_runnables: Option<bool>,
  760    git_blame_gutter_max_author_length: Option<usize>,
  761    pub display_snapshot: DisplaySnapshot,
  762    pub placeholder_text: Option<Arc<str>>,
  763    is_focused: bool,
  764    scroll_anchor: ScrollAnchor,
  765    ongoing_scroll: OngoingScroll,
  766    current_line_highlight: CurrentLineHighlight,
  767    gutter_hovered: bool,
  768}
  769
  770const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  771
  772#[derive(Default, Debug, Clone, Copy)]
  773pub struct GutterDimensions {
  774    pub left_padding: Pixels,
  775    pub right_padding: Pixels,
  776    pub width: Pixels,
  777    pub margin: Pixels,
  778    pub git_blame_entries_width: Option<Pixels>,
  779}
  780
  781impl GutterDimensions {
  782    /// The full width of the space taken up by the gutter.
  783    pub fn full_width(&self) -> Pixels {
  784        self.margin + self.width
  785    }
  786
  787    /// The width of the space reserved for the fold indicators,
  788    /// use alongside 'justify_end' and `gutter_width` to
  789    /// right align content with the line numbers
  790    pub fn fold_area_width(&self) -> Pixels {
  791        self.margin + self.right_padding
  792    }
  793}
  794
  795#[derive(Debug)]
  796pub struct RemoteSelection {
  797    pub replica_id: ReplicaId,
  798    pub selection: Selection<Anchor>,
  799    pub cursor_shape: CursorShape,
  800    pub peer_id: PeerId,
  801    pub line_mode: bool,
  802    pub participant_index: Option<ParticipantIndex>,
  803    pub user_name: Option<SharedString>,
  804}
  805
  806#[derive(Clone, Debug)]
  807struct SelectionHistoryEntry {
  808    selections: Arc<[Selection<Anchor>]>,
  809    select_next_state: Option<SelectNextState>,
  810    select_prev_state: Option<SelectNextState>,
  811    add_selections_state: Option<AddSelectionsState>,
  812}
  813
  814enum SelectionHistoryMode {
  815    Normal,
  816    Undoing,
  817    Redoing,
  818}
  819
  820#[derive(Clone, PartialEq, Eq, Hash)]
  821struct HoveredCursor {
  822    replica_id: u16,
  823    selection_id: usize,
  824}
  825
  826impl Default for SelectionHistoryMode {
  827    fn default() -> Self {
  828        Self::Normal
  829    }
  830}
  831
  832#[derive(Default)]
  833struct SelectionHistory {
  834    #[allow(clippy::type_complexity)]
  835    selections_by_transaction:
  836        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  837    mode: SelectionHistoryMode,
  838    undo_stack: VecDeque<SelectionHistoryEntry>,
  839    redo_stack: VecDeque<SelectionHistoryEntry>,
  840}
  841
  842impl SelectionHistory {
  843    fn insert_transaction(
  844        &mut self,
  845        transaction_id: TransactionId,
  846        selections: Arc<[Selection<Anchor>]>,
  847    ) {
  848        self.selections_by_transaction
  849            .insert(transaction_id, (selections, None));
  850    }
  851
  852    #[allow(clippy::type_complexity)]
  853    fn transaction(
  854        &self,
  855        transaction_id: TransactionId,
  856    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  857        self.selections_by_transaction.get(&transaction_id)
  858    }
  859
  860    #[allow(clippy::type_complexity)]
  861    fn transaction_mut(
  862        &mut self,
  863        transaction_id: TransactionId,
  864    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  865        self.selections_by_transaction.get_mut(&transaction_id)
  866    }
  867
  868    fn push(&mut self, entry: SelectionHistoryEntry) {
  869        if !entry.selections.is_empty() {
  870            match self.mode {
  871                SelectionHistoryMode::Normal => {
  872                    self.push_undo(entry);
  873                    self.redo_stack.clear();
  874                }
  875                SelectionHistoryMode::Undoing => self.push_redo(entry),
  876                SelectionHistoryMode::Redoing => self.push_undo(entry),
  877            }
  878        }
  879    }
  880
  881    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  882        if self
  883            .undo_stack
  884            .back()
  885            .map_or(true, |e| e.selections != entry.selections)
  886        {
  887            self.undo_stack.push_back(entry);
  888            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  889                self.undo_stack.pop_front();
  890            }
  891        }
  892    }
  893
  894    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  895        if self
  896            .redo_stack
  897            .back()
  898            .map_or(true, |e| e.selections != entry.selections)
  899        {
  900            self.redo_stack.push_back(entry);
  901            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  902                self.redo_stack.pop_front();
  903            }
  904        }
  905    }
  906}
  907
  908struct RowHighlight {
  909    index: usize,
  910    range: Range<Anchor>,
  911    color: Hsla,
  912    should_autoscroll: bool,
  913}
  914
  915#[derive(Clone, Debug)]
  916struct AddSelectionsState {
  917    above: bool,
  918    stack: Vec<usize>,
  919}
  920
  921#[derive(Clone)]
  922struct SelectNextState {
  923    query: AhoCorasick,
  924    wordwise: bool,
  925    done: bool,
  926}
  927
  928impl std::fmt::Debug for SelectNextState {
  929    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  930        f.debug_struct(std::any::type_name::<Self>())
  931            .field("wordwise", &self.wordwise)
  932            .field("done", &self.done)
  933            .finish()
  934    }
  935}
  936
  937#[derive(Debug)]
  938struct AutocloseRegion {
  939    selection_id: usize,
  940    range: Range<Anchor>,
  941    pair: BracketPair,
  942}
  943
  944#[derive(Debug)]
  945struct SnippetState {
  946    ranges: Vec<Vec<Range<Anchor>>>,
  947    active_index: usize,
  948    choices: Vec<Option<Vec<String>>>,
  949}
  950
  951#[doc(hidden)]
  952pub struct RenameState {
  953    pub range: Range<Anchor>,
  954    pub old_name: Arc<str>,
  955    pub editor: Entity<Editor>,
  956    block_id: CustomBlockId,
  957}
  958
  959struct InvalidationStack<T>(Vec<T>);
  960
  961struct RegisteredInlineCompletionProvider {
  962    provider: Arc<dyn InlineCompletionProviderHandle>,
  963    _subscription: Subscription,
  964}
  965
  966#[derive(Debug)]
  967struct ActiveDiagnosticGroup {
  968    primary_range: Range<Anchor>,
  969    primary_message: String,
  970    group_id: usize,
  971    blocks: HashMap<CustomBlockId, Diagnostic>,
  972    is_valid: bool,
  973}
  974
  975#[derive(Serialize, Deserialize, Clone, Debug)]
  976pub struct ClipboardSelection {
  977    /// The number of bytes in this selection.
  978    pub len: usize,
  979    /// Whether this was a full-line selection.
  980    pub is_entire_line: bool,
  981    /// The column where this selection originally started.
  982    pub start_column: u32,
  983}
  984
  985#[derive(Debug)]
  986pub(crate) struct NavigationData {
  987    cursor_anchor: Anchor,
  988    cursor_position: Point,
  989    scroll_anchor: ScrollAnchor,
  990    scroll_top_row: u32,
  991}
  992
  993#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  994pub enum GotoDefinitionKind {
  995    Symbol,
  996    Declaration,
  997    Type,
  998    Implementation,
  999}
 1000
 1001#[derive(Debug, Clone)]
 1002enum InlayHintRefreshReason {
 1003    Toggle(bool),
 1004    SettingsChange(InlayHintSettings),
 1005    NewLinesShown,
 1006    BufferEdited(HashSet<Arc<Language>>),
 1007    RefreshRequested,
 1008    ExcerptsRemoved(Vec<ExcerptId>),
 1009}
 1010
 1011impl InlayHintRefreshReason {
 1012    fn description(&self) -> &'static str {
 1013        match self {
 1014            Self::Toggle(_) => "toggle",
 1015            Self::SettingsChange(_) => "settings change",
 1016            Self::NewLinesShown => "new lines shown",
 1017            Self::BufferEdited(_) => "buffer edited",
 1018            Self::RefreshRequested => "refresh requested",
 1019            Self::ExcerptsRemoved(_) => "excerpts removed",
 1020        }
 1021    }
 1022}
 1023
 1024pub enum FormatTarget {
 1025    Buffers,
 1026    Ranges(Vec<Range<MultiBufferPoint>>),
 1027}
 1028
 1029pub(crate) struct FocusedBlock {
 1030    id: BlockId,
 1031    focus_handle: WeakFocusHandle,
 1032}
 1033
 1034#[derive(Clone)]
 1035enum JumpData {
 1036    MultiBufferRow {
 1037        row: MultiBufferRow,
 1038        line_offset_from_top: u32,
 1039    },
 1040    MultiBufferPoint {
 1041        excerpt_id: ExcerptId,
 1042        position: Point,
 1043        anchor: text::Anchor,
 1044        line_offset_from_top: u32,
 1045    },
 1046}
 1047
 1048pub enum MultibufferSelectionMode {
 1049    First,
 1050    All,
 1051}
 1052
 1053impl Editor {
 1054    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1055        let buffer = cx.new(|cx| Buffer::local("", cx));
 1056        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1057        Self::new(
 1058            EditorMode::SingleLine { auto_width: false },
 1059            buffer,
 1060            None,
 1061            false,
 1062            window,
 1063            cx,
 1064        )
 1065    }
 1066
 1067    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1068        let buffer = cx.new(|cx| Buffer::local("", cx));
 1069        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1070        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1071    }
 1072
 1073    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1074        let buffer = cx.new(|cx| Buffer::local("", cx));
 1075        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1076        Self::new(
 1077            EditorMode::SingleLine { auto_width: true },
 1078            buffer,
 1079            None,
 1080            false,
 1081            window,
 1082            cx,
 1083        )
 1084    }
 1085
 1086    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1087        let buffer = cx.new(|cx| Buffer::local("", cx));
 1088        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1089        Self::new(
 1090            EditorMode::AutoHeight { max_lines },
 1091            buffer,
 1092            None,
 1093            false,
 1094            window,
 1095            cx,
 1096        )
 1097    }
 1098
 1099    pub fn for_buffer(
 1100        buffer: Entity<Buffer>,
 1101        project: Option<Entity<Project>>,
 1102        window: &mut Window,
 1103        cx: &mut Context<Self>,
 1104    ) -> Self {
 1105        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1106        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1107    }
 1108
 1109    pub fn for_multibuffer(
 1110        buffer: Entity<MultiBuffer>,
 1111        project: Option<Entity<Project>>,
 1112        show_excerpt_controls: bool,
 1113        window: &mut Window,
 1114        cx: &mut Context<Self>,
 1115    ) -> Self {
 1116        Self::new(
 1117            EditorMode::Full,
 1118            buffer,
 1119            project,
 1120            show_excerpt_controls,
 1121            window,
 1122            cx,
 1123        )
 1124    }
 1125
 1126    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1127        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1128        let mut clone = Self::new(
 1129            self.mode,
 1130            self.buffer.clone(),
 1131            self.project.clone(),
 1132            show_excerpt_controls,
 1133            window,
 1134            cx,
 1135        );
 1136        self.display_map.update(cx, |display_map, cx| {
 1137            let snapshot = display_map.snapshot(cx);
 1138            clone.display_map.update(cx, |display_map, cx| {
 1139                display_map.set_state(&snapshot, cx);
 1140            });
 1141        });
 1142        clone.selections.clone_state(&self.selections);
 1143        clone.scroll_manager.clone_state(&self.scroll_manager);
 1144        clone.searchable = self.searchable;
 1145        clone
 1146    }
 1147
 1148    pub fn new(
 1149        mode: EditorMode,
 1150        buffer: Entity<MultiBuffer>,
 1151        project: Option<Entity<Project>>,
 1152        show_excerpt_controls: bool,
 1153        window: &mut Window,
 1154        cx: &mut Context<Self>,
 1155    ) -> Self {
 1156        let style = window.text_style();
 1157        let font_size = style.font_size.to_pixels(window.rem_size());
 1158        let editor = cx.entity().downgrade();
 1159        let fold_placeholder = FoldPlaceholder {
 1160            constrain_width: true,
 1161            render: Arc::new(move |fold_id, fold_range, cx| {
 1162                let editor = editor.clone();
 1163                div()
 1164                    .id(fold_id)
 1165                    .bg(cx.theme().colors().ghost_element_background)
 1166                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1167                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1168                    .rounded_sm()
 1169                    .size_full()
 1170                    .cursor_pointer()
 1171                    .child("")
 1172                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1173                    .on_click(move |_, _window, cx| {
 1174                        editor
 1175                            .update(cx, |editor, cx| {
 1176                                editor.unfold_ranges(
 1177                                    &[fold_range.start..fold_range.end],
 1178                                    true,
 1179                                    false,
 1180                                    cx,
 1181                                );
 1182                                cx.stop_propagation();
 1183                            })
 1184                            .ok();
 1185                    })
 1186                    .into_any()
 1187            }),
 1188            merge_adjacent: true,
 1189            ..Default::default()
 1190        };
 1191        let display_map = cx.new(|cx| {
 1192            DisplayMap::new(
 1193                buffer.clone(),
 1194                style.font(),
 1195                font_size,
 1196                None,
 1197                show_excerpt_controls,
 1198                FILE_HEADER_HEIGHT,
 1199                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1200                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1201                fold_placeholder,
 1202                cx,
 1203            )
 1204        });
 1205
 1206        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1207
 1208        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1209
 1210        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1211            .then(|| language_settings::SoftWrap::None);
 1212
 1213        let mut project_subscriptions = Vec::new();
 1214        if mode == EditorMode::Full {
 1215            if let Some(project) = project.as_ref() {
 1216                if buffer.read(cx).is_singleton() {
 1217                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1218                        cx.emit(EditorEvent::TitleChanged);
 1219                    }));
 1220                }
 1221                project_subscriptions.push(cx.subscribe_in(
 1222                    project,
 1223                    window,
 1224                    |editor, _, event, window, cx| {
 1225                        if let project::Event::RefreshInlayHints = event {
 1226                            editor
 1227                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1228                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1229                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1230                                let focus_handle = editor.focus_handle(cx);
 1231                                if focus_handle.is_focused(window) {
 1232                                    let snapshot = buffer.read(cx).snapshot();
 1233                                    for (range, snippet) in snippet_edits {
 1234                                        let editor_range =
 1235                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1236                                        editor
 1237                                            .insert_snippet(
 1238                                                &[editor_range],
 1239                                                snippet.clone(),
 1240                                                window,
 1241                                                cx,
 1242                                            )
 1243                                            .ok();
 1244                                    }
 1245                                }
 1246                            }
 1247                        }
 1248                    },
 1249                ));
 1250                if let Some(task_inventory) = project
 1251                    .read(cx)
 1252                    .task_store()
 1253                    .read(cx)
 1254                    .task_inventory()
 1255                    .cloned()
 1256                {
 1257                    project_subscriptions.push(cx.observe_in(
 1258                        &task_inventory,
 1259                        window,
 1260                        |editor, _, window, cx| {
 1261                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1262                        },
 1263                    ));
 1264                }
 1265            }
 1266        }
 1267
 1268        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1269
 1270        let inlay_hint_settings =
 1271            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1272        let focus_handle = cx.focus_handle();
 1273        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1274            .detach();
 1275        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1276            .detach();
 1277        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1278            .detach();
 1279        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1280            .detach();
 1281
 1282        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1283            Some(false)
 1284        } else {
 1285            None
 1286        };
 1287
 1288        let mut code_action_providers = Vec::new();
 1289        let mut load_uncommitted_diff = None;
 1290        if let Some(project) = project.clone() {
 1291            load_uncommitted_diff = Some(
 1292                get_uncommitted_diff_for_buffer(
 1293                    &project,
 1294                    buffer.read(cx).all_buffers(),
 1295                    buffer.clone(),
 1296                    cx,
 1297                )
 1298                .shared(),
 1299            );
 1300            code_action_providers.push(Rc::new(project) as Rc<_>);
 1301        }
 1302
 1303        let mut this = Self {
 1304            focus_handle,
 1305            show_cursor_when_unfocused: false,
 1306            last_focused_descendant: None,
 1307            buffer: buffer.clone(),
 1308            display_map: display_map.clone(),
 1309            selections,
 1310            scroll_manager: ScrollManager::new(cx),
 1311            columnar_selection_tail: None,
 1312            add_selections_state: None,
 1313            select_next_state: None,
 1314            select_prev_state: None,
 1315            selection_history: Default::default(),
 1316            autoclose_regions: Default::default(),
 1317            snippet_stack: Default::default(),
 1318            select_larger_syntax_node_stack: Vec::new(),
 1319            ime_transaction: Default::default(),
 1320            active_diagnostics: None,
 1321            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1322            inline_diagnostics_update: Task::ready(()),
 1323            inline_diagnostics: Vec::new(),
 1324            soft_wrap_mode_override,
 1325            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1326            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1327            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1328            project,
 1329            blink_manager: blink_manager.clone(),
 1330            show_local_selections: true,
 1331            show_scrollbars: true,
 1332            mode,
 1333            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1334            show_gutter: mode == EditorMode::Full,
 1335            show_line_numbers: None,
 1336            use_relative_line_numbers: None,
 1337            show_git_diff_gutter: None,
 1338            show_code_actions: None,
 1339            show_runnables: None,
 1340            show_wrap_guides: None,
 1341            show_indent_guides,
 1342            placeholder_text: None,
 1343            highlight_order: 0,
 1344            highlighted_rows: HashMap::default(),
 1345            background_highlights: Default::default(),
 1346            gutter_highlights: TreeMap::default(),
 1347            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1348            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1349            nav_history: None,
 1350            context_menu: RefCell::new(None),
 1351            mouse_context_menu: None,
 1352            completion_tasks: Default::default(),
 1353            signature_help_state: SignatureHelpState::default(),
 1354            auto_signature_help: None,
 1355            find_all_references_task_sources: Vec::new(),
 1356            next_completion_id: 0,
 1357            next_inlay_id: 0,
 1358            code_action_providers,
 1359            available_code_actions: Default::default(),
 1360            code_actions_task: Default::default(),
 1361            selection_highlight_task: Default::default(),
 1362            document_highlights_task: Default::default(),
 1363            linked_editing_range_task: Default::default(),
 1364            pending_rename: Default::default(),
 1365            searchable: true,
 1366            cursor_shape: EditorSettings::get_global(cx)
 1367                .cursor_shape
 1368                .unwrap_or_default(),
 1369            current_line_highlight: None,
 1370            autoindent_mode: Some(AutoindentMode::EachLine),
 1371            collapse_matches: false,
 1372            workspace: None,
 1373            input_enabled: true,
 1374            use_modal_editing: mode == EditorMode::Full,
 1375            read_only: false,
 1376            use_autoclose: true,
 1377            use_auto_surround: true,
 1378            auto_replace_emoji_shortcode: false,
 1379            leader_peer_id: None,
 1380            remote_id: None,
 1381            hover_state: Default::default(),
 1382            pending_mouse_down: None,
 1383            hovered_link_state: Default::default(),
 1384            edit_prediction_provider: None,
 1385            active_inline_completion: None,
 1386            stale_inline_completion_in_menu: None,
 1387            edit_prediction_preview: EditPredictionPreview::Inactive,
 1388            inline_diagnostics_enabled: mode == EditorMode::Full,
 1389            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1390
 1391            gutter_hovered: false,
 1392            pixel_position_of_newest_cursor: None,
 1393            last_bounds: None,
 1394            last_position_map: None,
 1395            expect_bounds_change: None,
 1396            gutter_dimensions: GutterDimensions::default(),
 1397            style: None,
 1398            show_cursor_names: false,
 1399            hovered_cursors: Default::default(),
 1400            next_editor_action_id: EditorActionId::default(),
 1401            editor_actions: Rc::default(),
 1402            inline_completions_hidden_for_vim_mode: false,
 1403            show_inline_completions_override: None,
 1404            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1405            edit_prediction_settings: EditPredictionSettings::Disabled,
 1406            edit_prediction_indent_conflict: false,
 1407            edit_prediction_requires_modifier_in_indent_conflict: true,
 1408            custom_context_menu: None,
 1409            show_git_blame_gutter: false,
 1410            show_git_blame_inline: false,
 1411            show_selection_menu: None,
 1412            show_git_blame_inline_delay_task: None,
 1413            git_blame_inline_tooltip: None,
 1414            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1415            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1416                .session
 1417                .restore_unsaved_buffers,
 1418            blame: None,
 1419            blame_subscription: None,
 1420            tasks: Default::default(),
 1421            _subscriptions: vec![
 1422                cx.observe(&buffer, Self::on_buffer_changed),
 1423                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1424                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1425                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1426                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1427                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1428                cx.observe_window_activation(window, |editor, window, cx| {
 1429                    let active = window.is_window_active();
 1430                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1431                        if active {
 1432                            blink_manager.enable(cx);
 1433                        } else {
 1434                            blink_manager.disable(cx);
 1435                        }
 1436                    });
 1437                }),
 1438            ],
 1439            tasks_update_task: None,
 1440            linked_edit_ranges: Default::default(),
 1441            in_project_search: false,
 1442            previous_search_ranges: None,
 1443            breadcrumb_header: None,
 1444            focused_block: None,
 1445            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1446            addons: HashMap::default(),
 1447            registered_buffers: HashMap::default(),
 1448            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1449            selection_mark_mode: false,
 1450            toggle_fold_multiple_buffers: Task::ready(()),
 1451            serialize_selections: Task::ready(()),
 1452            text_style_refinement: None,
 1453            load_diff_task: load_uncommitted_diff,
 1454        };
 1455        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1456        this._subscriptions.extend(project_subscriptions);
 1457
 1458        this.end_selection(window, cx);
 1459        this.scroll_manager.show_scrollbar(window, cx);
 1460
 1461        if mode == EditorMode::Full {
 1462            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1463            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1464
 1465            if this.git_blame_inline_enabled {
 1466                this.git_blame_inline_enabled = true;
 1467                this.start_git_blame_inline(false, window, cx);
 1468            }
 1469
 1470            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1471                if let Some(project) = this.project.as_ref() {
 1472                    let handle = project.update(cx, |project, cx| {
 1473                        project.register_buffer_with_language_servers(&buffer, cx)
 1474                    });
 1475                    this.registered_buffers
 1476                        .insert(buffer.read(cx).remote_id(), handle);
 1477                }
 1478            }
 1479        }
 1480
 1481        this.report_editor_event("Editor Opened", None, cx);
 1482        this
 1483    }
 1484
 1485    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1486        self.mouse_context_menu
 1487            .as_ref()
 1488            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1489    }
 1490
 1491    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1492        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1493    }
 1494
 1495    fn key_context_internal(
 1496        &self,
 1497        has_active_edit_prediction: bool,
 1498        window: &Window,
 1499        cx: &App,
 1500    ) -> KeyContext {
 1501        let mut key_context = KeyContext::new_with_defaults();
 1502        key_context.add("Editor");
 1503        let mode = match self.mode {
 1504            EditorMode::SingleLine { .. } => "single_line",
 1505            EditorMode::AutoHeight { .. } => "auto_height",
 1506            EditorMode::Full => "full",
 1507        };
 1508
 1509        if EditorSettings::jupyter_enabled(cx) {
 1510            key_context.add("jupyter");
 1511        }
 1512
 1513        key_context.set("mode", mode);
 1514        if self.pending_rename.is_some() {
 1515            key_context.add("renaming");
 1516        }
 1517
 1518        match self.context_menu.borrow().as_ref() {
 1519            Some(CodeContextMenu::Completions(_)) => {
 1520                key_context.add("menu");
 1521                key_context.add("showing_completions");
 1522            }
 1523            Some(CodeContextMenu::CodeActions(_)) => {
 1524                key_context.add("menu");
 1525                key_context.add("showing_code_actions")
 1526            }
 1527            None => {}
 1528        }
 1529
 1530        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1531        if !self.focus_handle(cx).contains_focused(window, cx)
 1532            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1533        {
 1534            for addon in self.addons.values() {
 1535                addon.extend_key_context(&mut key_context, cx)
 1536            }
 1537        }
 1538
 1539        if let Some(extension) = self
 1540            .buffer
 1541            .read(cx)
 1542            .as_singleton()
 1543            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1544        {
 1545            key_context.set("extension", extension.to_string());
 1546        }
 1547
 1548        if has_active_edit_prediction {
 1549            if self.edit_prediction_in_conflict() {
 1550                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1551            } else {
 1552                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1553                key_context.add("copilot_suggestion");
 1554            }
 1555        }
 1556
 1557        if self.selection_mark_mode {
 1558            key_context.add("selection_mode");
 1559        }
 1560
 1561        key_context
 1562    }
 1563
 1564    pub fn edit_prediction_in_conflict(&self) -> bool {
 1565        if !self.show_edit_predictions_in_menu() {
 1566            return false;
 1567        }
 1568
 1569        let showing_completions = self
 1570            .context_menu
 1571            .borrow()
 1572            .as_ref()
 1573            .map_or(false, |context| {
 1574                matches!(context, CodeContextMenu::Completions(_))
 1575            });
 1576
 1577        showing_completions
 1578            || self.edit_prediction_requires_modifier()
 1579            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1580            // bindings to insert tab characters.
 1581            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1582    }
 1583
 1584    pub fn accept_edit_prediction_keybind(
 1585        &self,
 1586        window: &Window,
 1587        cx: &App,
 1588    ) -> AcceptEditPredictionBinding {
 1589        let key_context = self.key_context_internal(true, window, cx);
 1590        let in_conflict = self.edit_prediction_in_conflict();
 1591
 1592        AcceptEditPredictionBinding(
 1593            window
 1594                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1595                .into_iter()
 1596                .filter(|binding| {
 1597                    !in_conflict
 1598                        || binding
 1599                            .keystrokes()
 1600                            .first()
 1601                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1602                })
 1603                .rev()
 1604                .min_by_key(|binding| {
 1605                    binding
 1606                        .keystrokes()
 1607                        .first()
 1608                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1609                }),
 1610        )
 1611    }
 1612
 1613    pub fn new_file(
 1614        workspace: &mut Workspace,
 1615        _: &workspace::NewFile,
 1616        window: &mut Window,
 1617        cx: &mut Context<Workspace>,
 1618    ) {
 1619        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1620            "Failed to create buffer",
 1621            window,
 1622            cx,
 1623            |e, _, _| match e.error_code() {
 1624                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1625                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1626                e.error_tag("required").unwrap_or("the latest version")
 1627            )),
 1628                _ => None,
 1629            },
 1630        );
 1631    }
 1632
 1633    pub fn new_in_workspace(
 1634        workspace: &mut Workspace,
 1635        window: &mut Window,
 1636        cx: &mut Context<Workspace>,
 1637    ) -> Task<Result<Entity<Editor>>> {
 1638        let project = workspace.project().clone();
 1639        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1640
 1641        cx.spawn_in(window, |workspace, mut cx| async move {
 1642            let buffer = create.await?;
 1643            workspace.update_in(&mut cx, |workspace, window, cx| {
 1644                let editor =
 1645                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1646                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1647                editor
 1648            })
 1649        })
 1650    }
 1651
 1652    fn new_file_vertical(
 1653        workspace: &mut Workspace,
 1654        _: &workspace::NewFileSplitVertical,
 1655        window: &mut Window,
 1656        cx: &mut Context<Workspace>,
 1657    ) {
 1658        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1659    }
 1660
 1661    fn new_file_horizontal(
 1662        workspace: &mut Workspace,
 1663        _: &workspace::NewFileSplitHorizontal,
 1664        window: &mut Window,
 1665        cx: &mut Context<Workspace>,
 1666    ) {
 1667        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1668    }
 1669
 1670    fn new_file_in_direction(
 1671        workspace: &mut Workspace,
 1672        direction: SplitDirection,
 1673        window: &mut Window,
 1674        cx: &mut Context<Workspace>,
 1675    ) {
 1676        let project = workspace.project().clone();
 1677        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1678
 1679        cx.spawn_in(window, |workspace, mut cx| async move {
 1680            let buffer = create.await?;
 1681            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1682                workspace.split_item(
 1683                    direction,
 1684                    Box::new(
 1685                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1686                    ),
 1687                    window,
 1688                    cx,
 1689                )
 1690            })?;
 1691            anyhow::Ok(())
 1692        })
 1693        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1694            match e.error_code() {
 1695                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1696                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1697                e.error_tag("required").unwrap_or("the latest version")
 1698            )),
 1699                _ => None,
 1700            }
 1701        });
 1702    }
 1703
 1704    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1705        self.leader_peer_id
 1706    }
 1707
 1708    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1709        &self.buffer
 1710    }
 1711
 1712    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1713        self.workspace.as_ref()?.0.upgrade()
 1714    }
 1715
 1716    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1717        self.buffer().read(cx).title(cx)
 1718    }
 1719
 1720    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1721        let git_blame_gutter_max_author_length = self
 1722            .render_git_blame_gutter(cx)
 1723            .then(|| {
 1724                if let Some(blame) = self.blame.as_ref() {
 1725                    let max_author_length =
 1726                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1727                    Some(max_author_length)
 1728                } else {
 1729                    None
 1730                }
 1731            })
 1732            .flatten();
 1733
 1734        EditorSnapshot {
 1735            mode: self.mode,
 1736            show_gutter: self.show_gutter,
 1737            show_line_numbers: self.show_line_numbers,
 1738            show_git_diff_gutter: self.show_git_diff_gutter,
 1739            show_code_actions: self.show_code_actions,
 1740            show_runnables: self.show_runnables,
 1741            git_blame_gutter_max_author_length,
 1742            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1743            scroll_anchor: self.scroll_manager.anchor(),
 1744            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1745            placeholder_text: self.placeholder_text.clone(),
 1746            is_focused: self.focus_handle.is_focused(window),
 1747            current_line_highlight: self
 1748                .current_line_highlight
 1749                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1750            gutter_hovered: self.gutter_hovered,
 1751        }
 1752    }
 1753
 1754    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1755        self.buffer.read(cx).language_at(point, cx)
 1756    }
 1757
 1758    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1759        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1760    }
 1761
 1762    pub fn active_excerpt(
 1763        &self,
 1764        cx: &App,
 1765    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1766        self.buffer
 1767            .read(cx)
 1768            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1769    }
 1770
 1771    pub fn mode(&self) -> EditorMode {
 1772        self.mode
 1773    }
 1774
 1775    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1776        self.collaboration_hub.as_deref()
 1777    }
 1778
 1779    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1780        self.collaboration_hub = Some(hub);
 1781    }
 1782
 1783    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1784        self.in_project_search = in_project_search;
 1785    }
 1786
 1787    pub fn set_custom_context_menu(
 1788        &mut self,
 1789        f: impl 'static
 1790            + Fn(
 1791                &mut Self,
 1792                DisplayPoint,
 1793                &mut Window,
 1794                &mut Context<Self>,
 1795            ) -> Option<Entity<ui::ContextMenu>>,
 1796    ) {
 1797        self.custom_context_menu = Some(Box::new(f))
 1798    }
 1799
 1800    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1801        self.completion_provider = provider;
 1802    }
 1803
 1804    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1805        self.semantics_provider.clone()
 1806    }
 1807
 1808    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1809        self.semantics_provider = provider;
 1810    }
 1811
 1812    pub fn set_edit_prediction_provider<T>(
 1813        &mut self,
 1814        provider: Option<Entity<T>>,
 1815        window: &mut Window,
 1816        cx: &mut Context<Self>,
 1817    ) where
 1818        T: EditPredictionProvider,
 1819    {
 1820        self.edit_prediction_provider =
 1821            provider.map(|provider| RegisteredInlineCompletionProvider {
 1822                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1823                    if this.focus_handle.is_focused(window) {
 1824                        this.update_visible_inline_completion(window, cx);
 1825                    }
 1826                }),
 1827                provider: Arc::new(provider),
 1828            });
 1829        self.refresh_inline_completion(false, false, window, cx);
 1830    }
 1831
 1832    pub fn placeholder_text(&self) -> Option<&str> {
 1833        self.placeholder_text.as_deref()
 1834    }
 1835
 1836    pub fn set_placeholder_text(
 1837        &mut self,
 1838        placeholder_text: impl Into<Arc<str>>,
 1839        cx: &mut Context<Self>,
 1840    ) {
 1841        let placeholder_text = Some(placeholder_text.into());
 1842        if self.placeholder_text != placeholder_text {
 1843            self.placeholder_text = placeholder_text;
 1844            cx.notify();
 1845        }
 1846    }
 1847
 1848    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1849        self.cursor_shape = cursor_shape;
 1850
 1851        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1852        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1853
 1854        cx.notify();
 1855    }
 1856
 1857    pub fn set_current_line_highlight(
 1858        &mut self,
 1859        current_line_highlight: Option<CurrentLineHighlight>,
 1860    ) {
 1861        self.current_line_highlight = current_line_highlight;
 1862    }
 1863
 1864    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1865        self.collapse_matches = collapse_matches;
 1866    }
 1867
 1868    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1869        let buffers = self.buffer.read(cx).all_buffers();
 1870        let Some(project) = self.project.as_ref() else {
 1871            return;
 1872        };
 1873        project.update(cx, |project, cx| {
 1874            for buffer in buffers {
 1875                self.registered_buffers
 1876                    .entry(buffer.read(cx).remote_id())
 1877                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1878            }
 1879        })
 1880    }
 1881
 1882    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1883        if self.collapse_matches {
 1884            return range.start..range.start;
 1885        }
 1886        range.clone()
 1887    }
 1888
 1889    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1890        if self.display_map.read(cx).clip_at_line_ends != clip {
 1891            self.display_map
 1892                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1893        }
 1894    }
 1895
 1896    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1897        self.input_enabled = input_enabled;
 1898    }
 1899
 1900    pub fn set_inline_completions_hidden_for_vim_mode(
 1901        &mut self,
 1902        hidden: bool,
 1903        window: &mut Window,
 1904        cx: &mut Context<Self>,
 1905    ) {
 1906        if hidden != self.inline_completions_hidden_for_vim_mode {
 1907            self.inline_completions_hidden_for_vim_mode = hidden;
 1908            if hidden {
 1909                self.update_visible_inline_completion(window, cx);
 1910            } else {
 1911                self.refresh_inline_completion(true, false, window, cx);
 1912            }
 1913        }
 1914    }
 1915
 1916    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1917        self.menu_inline_completions_policy = value;
 1918    }
 1919
 1920    pub fn set_autoindent(&mut self, autoindent: bool) {
 1921        if autoindent {
 1922            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1923        } else {
 1924            self.autoindent_mode = None;
 1925        }
 1926    }
 1927
 1928    pub fn read_only(&self, cx: &App) -> bool {
 1929        self.read_only || self.buffer.read(cx).read_only()
 1930    }
 1931
 1932    pub fn set_read_only(&mut self, read_only: bool) {
 1933        self.read_only = read_only;
 1934    }
 1935
 1936    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1937        self.use_autoclose = autoclose;
 1938    }
 1939
 1940    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1941        self.use_auto_surround = auto_surround;
 1942    }
 1943
 1944    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1945        self.auto_replace_emoji_shortcode = auto_replace;
 1946    }
 1947
 1948    pub fn toggle_inline_completions(
 1949        &mut self,
 1950        _: &ToggleEditPrediction,
 1951        window: &mut Window,
 1952        cx: &mut Context<Self>,
 1953    ) {
 1954        if self.show_inline_completions_override.is_some() {
 1955            self.set_show_edit_predictions(None, window, cx);
 1956        } else {
 1957            let show_edit_predictions = !self.edit_predictions_enabled();
 1958            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1959        }
 1960    }
 1961
 1962    pub fn set_show_edit_predictions(
 1963        &mut self,
 1964        show_edit_predictions: Option<bool>,
 1965        window: &mut Window,
 1966        cx: &mut Context<Self>,
 1967    ) {
 1968        self.show_inline_completions_override = show_edit_predictions;
 1969
 1970        if let Some(false) = show_edit_predictions {
 1971            self.discard_inline_completion(false, cx);
 1972        } else {
 1973            self.refresh_inline_completion(false, true, window, cx);
 1974        }
 1975    }
 1976
 1977    fn inline_completions_disabled_in_scope(
 1978        &self,
 1979        buffer: &Entity<Buffer>,
 1980        buffer_position: language::Anchor,
 1981        cx: &App,
 1982    ) -> bool {
 1983        let snapshot = buffer.read(cx).snapshot();
 1984        let settings = snapshot.settings_at(buffer_position, cx);
 1985
 1986        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1987            return false;
 1988        };
 1989
 1990        scope.override_name().map_or(false, |scope_name| {
 1991            settings
 1992                .edit_predictions_disabled_in
 1993                .iter()
 1994                .any(|s| s == scope_name)
 1995        })
 1996    }
 1997
 1998    pub fn set_use_modal_editing(&mut self, to: bool) {
 1999        self.use_modal_editing = to;
 2000    }
 2001
 2002    pub fn use_modal_editing(&self) -> bool {
 2003        self.use_modal_editing
 2004    }
 2005
 2006    fn selections_did_change(
 2007        &mut self,
 2008        local: bool,
 2009        old_cursor_position: &Anchor,
 2010        show_completions: bool,
 2011        window: &mut Window,
 2012        cx: &mut Context<Self>,
 2013    ) {
 2014        window.invalidate_character_coordinates();
 2015
 2016        // Copy selections to primary selection buffer
 2017        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2018        if local {
 2019            let selections = self.selections.all::<usize>(cx);
 2020            let buffer_handle = self.buffer.read(cx).read(cx);
 2021
 2022            let mut text = String::new();
 2023            for (index, selection) in selections.iter().enumerate() {
 2024                let text_for_selection = buffer_handle
 2025                    .text_for_range(selection.start..selection.end)
 2026                    .collect::<String>();
 2027
 2028                text.push_str(&text_for_selection);
 2029                if index != selections.len() - 1 {
 2030                    text.push('\n');
 2031                }
 2032            }
 2033
 2034            if !text.is_empty() {
 2035                cx.write_to_primary(ClipboardItem::new_string(text));
 2036            }
 2037        }
 2038
 2039        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2040            self.buffer.update(cx, |buffer, cx| {
 2041                buffer.set_active_selections(
 2042                    &self.selections.disjoint_anchors(),
 2043                    self.selections.line_mode,
 2044                    self.cursor_shape,
 2045                    cx,
 2046                )
 2047            });
 2048        }
 2049        let display_map = self
 2050            .display_map
 2051            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2052        let buffer = &display_map.buffer_snapshot;
 2053        self.add_selections_state = None;
 2054        self.select_next_state = None;
 2055        self.select_prev_state = None;
 2056        self.select_larger_syntax_node_stack.clear();
 2057        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2058        self.snippet_stack
 2059            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2060        self.take_rename(false, window, cx);
 2061
 2062        let new_cursor_position = self.selections.newest_anchor().head();
 2063
 2064        self.push_to_nav_history(
 2065            *old_cursor_position,
 2066            Some(new_cursor_position.to_point(buffer)),
 2067            cx,
 2068        );
 2069
 2070        if local {
 2071            let new_cursor_position = self.selections.newest_anchor().head();
 2072            let mut context_menu = self.context_menu.borrow_mut();
 2073            let completion_menu = match context_menu.as_ref() {
 2074                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2075                _ => {
 2076                    *context_menu = None;
 2077                    None
 2078                }
 2079            };
 2080            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2081                if !self.registered_buffers.contains_key(&buffer_id) {
 2082                    if let Some(project) = self.project.as_ref() {
 2083                        project.update(cx, |project, cx| {
 2084                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2085                                return;
 2086                            };
 2087                            self.registered_buffers.insert(
 2088                                buffer_id,
 2089                                project.register_buffer_with_language_servers(&buffer, cx),
 2090                            );
 2091                        })
 2092                    }
 2093                }
 2094            }
 2095
 2096            if let Some(completion_menu) = completion_menu {
 2097                let cursor_position = new_cursor_position.to_offset(buffer);
 2098                let (word_range, kind) =
 2099                    buffer.surrounding_word(completion_menu.initial_position, true);
 2100                if kind == Some(CharKind::Word)
 2101                    && word_range.to_inclusive().contains(&cursor_position)
 2102                {
 2103                    let mut completion_menu = completion_menu.clone();
 2104                    drop(context_menu);
 2105
 2106                    let query = Self::completion_query(buffer, cursor_position);
 2107                    cx.spawn(move |this, mut cx| async move {
 2108                        completion_menu
 2109                            .filter(query.as_deref(), cx.background_executor().clone())
 2110                            .await;
 2111
 2112                        this.update(&mut cx, |this, cx| {
 2113                            let mut context_menu = this.context_menu.borrow_mut();
 2114                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2115                            else {
 2116                                return;
 2117                            };
 2118
 2119                            if menu.id > completion_menu.id {
 2120                                return;
 2121                            }
 2122
 2123                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2124                            drop(context_menu);
 2125                            cx.notify();
 2126                        })
 2127                    })
 2128                    .detach();
 2129
 2130                    if show_completions {
 2131                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2132                    }
 2133                } else {
 2134                    drop(context_menu);
 2135                    self.hide_context_menu(window, cx);
 2136                }
 2137            } else {
 2138                drop(context_menu);
 2139            }
 2140
 2141            hide_hover(self, cx);
 2142
 2143            if old_cursor_position.to_display_point(&display_map).row()
 2144                != new_cursor_position.to_display_point(&display_map).row()
 2145            {
 2146                self.available_code_actions.take();
 2147            }
 2148            self.refresh_code_actions(window, cx);
 2149            self.refresh_document_highlights(cx);
 2150            self.refresh_selected_text_highlights(window, cx);
 2151            refresh_matching_bracket_highlights(self, window, cx);
 2152            self.update_visible_inline_completion(window, cx);
 2153            self.edit_prediction_requires_modifier_in_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.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4828            self.discard_inline_completion(false, cx);
 4829            return None;
 4830        }
 4831
 4832        if !user_requested
 4833            && (!self.should_show_edit_predictions()
 4834                || !self.is_focused(window)
 4835                || buffer.read(cx).is_empty())
 4836        {
 4837            self.discard_inline_completion(false, cx);
 4838            return None;
 4839        }
 4840
 4841        self.update_visible_inline_completion(window, cx);
 4842        provider.refresh(
 4843            self.project.clone(),
 4844            buffer,
 4845            cursor_buffer_position,
 4846            debounce,
 4847            cx,
 4848        );
 4849        Some(())
 4850    }
 4851
 4852    fn show_edit_predictions_in_menu(&self) -> bool {
 4853        match self.edit_prediction_settings {
 4854            EditPredictionSettings::Disabled => false,
 4855            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4856        }
 4857    }
 4858
 4859    pub fn edit_predictions_enabled(&self) -> bool {
 4860        match self.edit_prediction_settings {
 4861            EditPredictionSettings::Disabled => false,
 4862            EditPredictionSettings::Enabled { .. } => true,
 4863        }
 4864    }
 4865
 4866    fn edit_prediction_requires_modifier(&self) -> bool {
 4867        match self.edit_prediction_settings {
 4868            EditPredictionSettings::Disabled => false,
 4869            EditPredictionSettings::Enabled {
 4870                preview_requires_modifier,
 4871                ..
 4872            } => preview_requires_modifier,
 4873        }
 4874    }
 4875
 4876    fn edit_prediction_settings_at_position(
 4877        &self,
 4878        buffer: &Entity<Buffer>,
 4879        buffer_position: language::Anchor,
 4880        cx: &App,
 4881    ) -> EditPredictionSettings {
 4882        if self.mode != EditorMode::Full
 4883            || !self.show_inline_completions_override.unwrap_or(true)
 4884            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4885        {
 4886            return EditPredictionSettings::Disabled;
 4887        }
 4888
 4889        let buffer = buffer.read(cx);
 4890
 4891        let file = buffer.file();
 4892
 4893        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4894            return EditPredictionSettings::Disabled;
 4895        };
 4896
 4897        let by_provider = matches!(
 4898            self.menu_inline_completions_policy,
 4899            MenuInlineCompletionsPolicy::ByProvider
 4900        );
 4901
 4902        let show_in_menu = by_provider
 4903            && self
 4904                .edit_prediction_provider
 4905                .as_ref()
 4906                .map_or(false, |provider| {
 4907                    provider.provider.show_completions_in_menu()
 4908                });
 4909
 4910        let preview_requires_modifier =
 4911            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4912
 4913        EditPredictionSettings::Enabled {
 4914            show_in_menu,
 4915            preview_requires_modifier,
 4916        }
 4917    }
 4918
 4919    fn should_show_edit_predictions(&self) -> bool {
 4920        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4921    }
 4922
 4923    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4924        matches!(
 4925            self.edit_prediction_preview,
 4926            EditPredictionPreview::Active { .. }
 4927        )
 4928    }
 4929
 4930    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4931        let cursor = self.selections.newest_anchor().head();
 4932        if let Some((buffer, cursor_position)) =
 4933            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4934        {
 4935            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4936        } else {
 4937            false
 4938        }
 4939    }
 4940
 4941    fn inline_completions_enabled_in_buffer(
 4942        &self,
 4943        buffer: &Entity<Buffer>,
 4944        buffer_position: language::Anchor,
 4945        cx: &App,
 4946    ) -> bool {
 4947        maybe!({
 4948            let provider = self.edit_prediction_provider()?;
 4949            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4950                return Some(false);
 4951            }
 4952            let buffer = buffer.read(cx);
 4953            let Some(file) = buffer.file() else {
 4954                return Some(true);
 4955            };
 4956            let settings = all_language_settings(Some(file), cx);
 4957            Some(settings.inline_completions_enabled_for_path(file.path()))
 4958        })
 4959        .unwrap_or(false)
 4960    }
 4961
 4962    fn cycle_inline_completion(
 4963        &mut self,
 4964        direction: Direction,
 4965        window: &mut Window,
 4966        cx: &mut Context<Self>,
 4967    ) -> Option<()> {
 4968        let provider = self.edit_prediction_provider()?;
 4969        let cursor = self.selections.newest_anchor().head();
 4970        let (buffer, cursor_buffer_position) =
 4971            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4972        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4973            return None;
 4974        }
 4975
 4976        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4977        self.update_visible_inline_completion(window, cx);
 4978
 4979        Some(())
 4980    }
 4981
 4982    pub fn show_inline_completion(
 4983        &mut self,
 4984        _: &ShowEditPrediction,
 4985        window: &mut Window,
 4986        cx: &mut Context<Self>,
 4987    ) {
 4988        if !self.has_active_inline_completion() {
 4989            self.refresh_inline_completion(false, true, window, cx);
 4990            return;
 4991        }
 4992
 4993        self.update_visible_inline_completion(window, cx);
 4994    }
 4995
 4996    pub fn display_cursor_names(
 4997        &mut self,
 4998        _: &DisplayCursorNames,
 4999        window: &mut Window,
 5000        cx: &mut Context<Self>,
 5001    ) {
 5002        self.show_cursor_names(window, cx);
 5003    }
 5004
 5005    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5006        self.show_cursor_names = true;
 5007        cx.notify();
 5008        cx.spawn_in(window, |this, mut cx| async move {
 5009            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5010            this.update(&mut cx, |this, cx| {
 5011                this.show_cursor_names = false;
 5012                cx.notify()
 5013            })
 5014            .ok()
 5015        })
 5016        .detach();
 5017    }
 5018
 5019    pub fn next_edit_prediction(
 5020        &mut self,
 5021        _: &NextEditPrediction,
 5022        window: &mut Window,
 5023        cx: &mut Context<Self>,
 5024    ) {
 5025        if self.has_active_inline_completion() {
 5026            self.cycle_inline_completion(Direction::Next, window, cx);
 5027        } else {
 5028            let is_copilot_disabled = self
 5029                .refresh_inline_completion(false, true, window, cx)
 5030                .is_none();
 5031            if is_copilot_disabled {
 5032                cx.propagate();
 5033            }
 5034        }
 5035    }
 5036
 5037    pub fn previous_edit_prediction(
 5038        &mut self,
 5039        _: &PreviousEditPrediction,
 5040        window: &mut Window,
 5041        cx: &mut Context<Self>,
 5042    ) {
 5043        if self.has_active_inline_completion() {
 5044            self.cycle_inline_completion(Direction::Prev, window, cx);
 5045        } else {
 5046            let is_copilot_disabled = self
 5047                .refresh_inline_completion(false, true, window, cx)
 5048                .is_none();
 5049            if is_copilot_disabled {
 5050                cx.propagate();
 5051            }
 5052        }
 5053    }
 5054
 5055    pub fn accept_edit_prediction(
 5056        &mut self,
 5057        _: &AcceptEditPrediction,
 5058        window: &mut Window,
 5059        cx: &mut Context<Self>,
 5060    ) {
 5061        if self.show_edit_predictions_in_menu() {
 5062            self.hide_context_menu(window, cx);
 5063        }
 5064
 5065        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5066            return;
 5067        };
 5068
 5069        self.report_inline_completion_event(
 5070            active_inline_completion.completion_id.clone(),
 5071            true,
 5072            cx,
 5073        );
 5074
 5075        match &active_inline_completion.completion {
 5076            InlineCompletion::Move { target, .. } => {
 5077                let target = *target;
 5078
 5079                if let Some(position_map) = &self.last_position_map {
 5080                    if position_map
 5081                        .visible_row_range
 5082                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5083                        || !self.edit_prediction_requires_modifier()
 5084                    {
 5085                        self.unfold_ranges(&[target..target], true, false, cx);
 5086                        // Note that this is also done in vim's handler of the Tab action.
 5087                        self.change_selections(
 5088                            Some(Autoscroll::newest()),
 5089                            window,
 5090                            cx,
 5091                            |selections| {
 5092                                selections.select_anchor_ranges([target..target]);
 5093                            },
 5094                        );
 5095                        self.clear_row_highlights::<EditPredictionPreview>();
 5096
 5097                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5098                            previous_scroll_position: None,
 5099                        };
 5100                    } else {
 5101                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5102                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5103                        };
 5104                        self.highlight_rows::<EditPredictionPreview>(
 5105                            target..target,
 5106                            cx.theme().colors().editor_highlighted_line_background,
 5107                            true,
 5108                            cx,
 5109                        );
 5110                        self.request_autoscroll(Autoscroll::fit(), cx);
 5111                    }
 5112                }
 5113            }
 5114            InlineCompletion::Edit { edits, .. } => {
 5115                if let Some(provider) = self.edit_prediction_provider() {
 5116                    provider.accept(cx);
 5117                }
 5118
 5119                let snapshot = self.buffer.read(cx).snapshot(cx);
 5120                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5121
 5122                self.buffer.update(cx, |buffer, cx| {
 5123                    buffer.edit(edits.iter().cloned(), None, cx)
 5124                });
 5125
 5126                self.change_selections(None, window, cx, |s| {
 5127                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5128                });
 5129
 5130                self.update_visible_inline_completion(window, cx);
 5131                if self.active_inline_completion.is_none() {
 5132                    self.refresh_inline_completion(true, true, window, cx);
 5133                }
 5134
 5135                cx.notify();
 5136            }
 5137        }
 5138
 5139        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5140    }
 5141
 5142    pub fn accept_partial_inline_completion(
 5143        &mut self,
 5144        _: &AcceptPartialEditPrediction,
 5145        window: &mut Window,
 5146        cx: &mut Context<Self>,
 5147    ) {
 5148        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5149            return;
 5150        };
 5151        if self.selections.count() != 1 {
 5152            return;
 5153        }
 5154
 5155        self.report_inline_completion_event(
 5156            active_inline_completion.completion_id.clone(),
 5157            true,
 5158            cx,
 5159        );
 5160
 5161        match &active_inline_completion.completion {
 5162            InlineCompletion::Move { target, .. } => {
 5163                let target = *target;
 5164                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5165                    selections.select_anchor_ranges([target..target]);
 5166                });
 5167            }
 5168            InlineCompletion::Edit { edits, .. } => {
 5169                // Find an insertion that starts at the cursor position.
 5170                let snapshot = self.buffer.read(cx).snapshot(cx);
 5171                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5172                let insertion = edits.iter().find_map(|(range, text)| {
 5173                    let range = range.to_offset(&snapshot);
 5174                    if range.is_empty() && range.start == cursor_offset {
 5175                        Some(text)
 5176                    } else {
 5177                        None
 5178                    }
 5179                });
 5180
 5181                if let Some(text) = insertion {
 5182                    let mut partial_completion = text
 5183                        .chars()
 5184                        .by_ref()
 5185                        .take_while(|c| c.is_alphabetic())
 5186                        .collect::<String>();
 5187                    if partial_completion.is_empty() {
 5188                        partial_completion = text
 5189                            .chars()
 5190                            .by_ref()
 5191                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5192                            .collect::<String>();
 5193                    }
 5194
 5195                    cx.emit(EditorEvent::InputHandled {
 5196                        utf16_range_to_replace: None,
 5197                        text: partial_completion.clone().into(),
 5198                    });
 5199
 5200                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5201
 5202                    self.refresh_inline_completion(true, true, window, cx);
 5203                    cx.notify();
 5204                } else {
 5205                    self.accept_edit_prediction(&Default::default(), window, cx);
 5206                }
 5207            }
 5208        }
 5209    }
 5210
 5211    fn discard_inline_completion(
 5212        &mut self,
 5213        should_report_inline_completion_event: bool,
 5214        cx: &mut Context<Self>,
 5215    ) -> bool {
 5216        if should_report_inline_completion_event {
 5217            let completion_id = self
 5218                .active_inline_completion
 5219                .as_ref()
 5220                .and_then(|active_completion| active_completion.completion_id.clone());
 5221
 5222            self.report_inline_completion_event(completion_id, false, cx);
 5223        }
 5224
 5225        if let Some(provider) = self.edit_prediction_provider() {
 5226            provider.discard(cx);
 5227        }
 5228
 5229        self.take_active_inline_completion(cx)
 5230    }
 5231
 5232    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5233        let Some(provider) = self.edit_prediction_provider() else {
 5234            return;
 5235        };
 5236
 5237        let Some((_, buffer, _)) = self
 5238            .buffer
 5239            .read(cx)
 5240            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5241        else {
 5242            return;
 5243        };
 5244
 5245        let extension = buffer
 5246            .read(cx)
 5247            .file()
 5248            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5249
 5250        let event_type = match accepted {
 5251            true => "Edit Prediction Accepted",
 5252            false => "Edit Prediction Discarded",
 5253        };
 5254        telemetry::event!(
 5255            event_type,
 5256            provider = provider.name(),
 5257            prediction_id = id,
 5258            suggestion_accepted = accepted,
 5259            file_extension = extension,
 5260        );
 5261    }
 5262
 5263    pub fn has_active_inline_completion(&self) -> bool {
 5264        self.active_inline_completion.is_some()
 5265    }
 5266
 5267    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5268        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5269            return false;
 5270        };
 5271
 5272        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5273        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5274        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5275        true
 5276    }
 5277
 5278    /// Returns true when we're displaying the edit prediction popover below the cursor
 5279    /// like we are not previewing and the LSP autocomplete menu is visible
 5280    /// or we are in `when_holding_modifier` mode.
 5281    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5282        if self.edit_prediction_preview_is_active()
 5283            || !self.show_edit_predictions_in_menu()
 5284            || !self.edit_predictions_enabled()
 5285        {
 5286            return false;
 5287        }
 5288
 5289        if self.has_visible_completions_menu() {
 5290            return true;
 5291        }
 5292
 5293        has_completion && self.edit_prediction_requires_modifier()
 5294    }
 5295
 5296    fn handle_modifiers_changed(
 5297        &mut self,
 5298        modifiers: Modifiers,
 5299        position_map: &PositionMap,
 5300        window: &mut Window,
 5301        cx: &mut Context<Self>,
 5302    ) {
 5303        if self.show_edit_predictions_in_menu() {
 5304            self.update_edit_prediction_preview(&modifiers, window, cx);
 5305        }
 5306
 5307        self.update_selection_mode(&modifiers, position_map, window, cx);
 5308
 5309        let mouse_position = window.mouse_position();
 5310        if !position_map.text_hitbox.is_hovered(window) {
 5311            return;
 5312        }
 5313
 5314        self.update_hovered_link(
 5315            position_map.point_for_position(mouse_position),
 5316            &position_map.snapshot,
 5317            modifiers,
 5318            window,
 5319            cx,
 5320        )
 5321    }
 5322
 5323    fn update_selection_mode(
 5324        &mut self,
 5325        modifiers: &Modifiers,
 5326        position_map: &PositionMap,
 5327        window: &mut Window,
 5328        cx: &mut Context<Self>,
 5329    ) {
 5330        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5331            return;
 5332        }
 5333
 5334        let mouse_position = window.mouse_position();
 5335        let point_for_position = position_map.point_for_position(mouse_position);
 5336        let position = point_for_position.previous_valid;
 5337
 5338        self.select(
 5339            SelectPhase::BeginColumnar {
 5340                position,
 5341                reset: false,
 5342                goal_column: point_for_position.exact_unclipped.column(),
 5343            },
 5344            window,
 5345            cx,
 5346        );
 5347    }
 5348
 5349    fn update_edit_prediction_preview(
 5350        &mut self,
 5351        modifiers: &Modifiers,
 5352        window: &mut Window,
 5353        cx: &mut Context<Self>,
 5354    ) {
 5355        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5356        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5357            return;
 5358        };
 5359
 5360        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5361            if matches!(
 5362                self.edit_prediction_preview,
 5363                EditPredictionPreview::Inactive
 5364            ) {
 5365                self.edit_prediction_preview = EditPredictionPreview::Active {
 5366                    previous_scroll_position: None,
 5367                };
 5368
 5369                self.update_visible_inline_completion(window, cx);
 5370                cx.notify();
 5371            }
 5372        } else if let EditPredictionPreview::Active {
 5373            previous_scroll_position,
 5374        } = self.edit_prediction_preview
 5375        {
 5376            if let (Some(previous_scroll_position), Some(position_map)) =
 5377                (previous_scroll_position, self.last_position_map.as_ref())
 5378            {
 5379                self.set_scroll_position(
 5380                    previous_scroll_position
 5381                        .scroll_position(&position_map.snapshot.display_snapshot),
 5382                    window,
 5383                    cx,
 5384                );
 5385            }
 5386
 5387            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5388            self.clear_row_highlights::<EditPredictionPreview>();
 5389            self.update_visible_inline_completion(window, cx);
 5390            cx.notify();
 5391        }
 5392    }
 5393
 5394    fn update_visible_inline_completion(
 5395        &mut self,
 5396        _window: &mut Window,
 5397        cx: &mut Context<Self>,
 5398    ) -> Option<()> {
 5399        let selection = self.selections.newest_anchor();
 5400        let cursor = selection.head();
 5401        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5402        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5403        let excerpt_id = cursor.excerpt_id;
 5404
 5405        let show_in_menu = self.show_edit_predictions_in_menu();
 5406        let completions_menu_has_precedence = !show_in_menu
 5407            && (self.context_menu.borrow().is_some()
 5408                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5409
 5410        if completions_menu_has_precedence
 5411            || !offset_selection.is_empty()
 5412            || self
 5413                .active_inline_completion
 5414                .as_ref()
 5415                .map_or(false, |completion| {
 5416                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5417                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5418                    !invalidation_range.contains(&offset_selection.head())
 5419                })
 5420        {
 5421            self.discard_inline_completion(false, cx);
 5422            return None;
 5423        }
 5424
 5425        self.take_active_inline_completion(cx);
 5426        let Some(provider) = self.edit_prediction_provider() else {
 5427            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5428            return None;
 5429        };
 5430
 5431        let (buffer, cursor_buffer_position) =
 5432            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5433
 5434        self.edit_prediction_settings =
 5435            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5436
 5437        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5438
 5439        if self.edit_prediction_indent_conflict {
 5440            let cursor_point = cursor.to_point(&multibuffer);
 5441
 5442            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5443
 5444            if let Some((_, indent)) = indents.iter().next() {
 5445                if indent.len == cursor_point.column {
 5446                    self.edit_prediction_indent_conflict = false;
 5447                }
 5448            }
 5449        }
 5450
 5451        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5452        let edits = inline_completion
 5453            .edits
 5454            .into_iter()
 5455            .flat_map(|(range, new_text)| {
 5456                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5457                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5458                Some((start..end, new_text))
 5459            })
 5460            .collect::<Vec<_>>();
 5461        if edits.is_empty() {
 5462            return None;
 5463        }
 5464
 5465        let first_edit_start = edits.first().unwrap().0.start;
 5466        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5467        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5468
 5469        let last_edit_end = edits.last().unwrap().0.end;
 5470        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5471        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5472
 5473        let cursor_row = cursor.to_point(&multibuffer).row;
 5474
 5475        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5476
 5477        let mut inlay_ids = Vec::new();
 5478        let invalidation_row_range;
 5479        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5480            Some(cursor_row..edit_end_row)
 5481        } else if cursor_row > edit_end_row {
 5482            Some(edit_start_row..cursor_row)
 5483        } else {
 5484            None
 5485        };
 5486        let is_move =
 5487            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5488        let completion = if is_move {
 5489            invalidation_row_range =
 5490                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5491            let target = first_edit_start;
 5492            InlineCompletion::Move { target, snapshot }
 5493        } else {
 5494            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5495                && !self.inline_completions_hidden_for_vim_mode;
 5496
 5497            if show_completions_in_buffer {
 5498                if edits
 5499                    .iter()
 5500                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5501                {
 5502                    let mut inlays = Vec::new();
 5503                    for (range, new_text) in &edits {
 5504                        let inlay = Inlay::inline_completion(
 5505                            post_inc(&mut self.next_inlay_id),
 5506                            range.start,
 5507                            new_text.as_str(),
 5508                        );
 5509                        inlay_ids.push(inlay.id);
 5510                        inlays.push(inlay);
 5511                    }
 5512
 5513                    self.splice_inlays(&[], inlays, cx);
 5514                } else {
 5515                    let background_color = cx.theme().status().deleted_background;
 5516                    self.highlight_text::<InlineCompletionHighlight>(
 5517                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5518                        HighlightStyle {
 5519                            background_color: Some(background_color),
 5520                            ..Default::default()
 5521                        },
 5522                        cx,
 5523                    );
 5524                }
 5525            }
 5526
 5527            invalidation_row_range = edit_start_row..edit_end_row;
 5528
 5529            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5530                if provider.show_tab_accept_marker() {
 5531                    EditDisplayMode::TabAccept
 5532                } else {
 5533                    EditDisplayMode::Inline
 5534                }
 5535            } else {
 5536                EditDisplayMode::DiffPopover
 5537            };
 5538
 5539            InlineCompletion::Edit {
 5540                edits,
 5541                edit_preview: inline_completion.edit_preview,
 5542                display_mode,
 5543                snapshot,
 5544            }
 5545        };
 5546
 5547        let invalidation_range = multibuffer
 5548            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5549            ..multibuffer.anchor_after(Point::new(
 5550                invalidation_row_range.end,
 5551                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5552            ));
 5553
 5554        self.stale_inline_completion_in_menu = None;
 5555        self.active_inline_completion = Some(InlineCompletionState {
 5556            inlay_ids,
 5557            completion,
 5558            completion_id: inline_completion.id,
 5559            invalidation_range,
 5560        });
 5561
 5562        cx.notify();
 5563
 5564        Some(())
 5565    }
 5566
 5567    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5568        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5569    }
 5570
 5571    fn render_code_actions_indicator(
 5572        &self,
 5573        _style: &EditorStyle,
 5574        row: DisplayRow,
 5575        is_active: bool,
 5576        cx: &mut Context<Self>,
 5577    ) -> Option<IconButton> {
 5578        if self.available_code_actions.is_some() {
 5579            Some(
 5580                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5581                    .shape(ui::IconButtonShape::Square)
 5582                    .icon_size(IconSize::XSmall)
 5583                    .icon_color(Color::Muted)
 5584                    .toggle_state(is_active)
 5585                    .tooltip({
 5586                        let focus_handle = self.focus_handle.clone();
 5587                        move |window, cx| {
 5588                            Tooltip::for_action_in(
 5589                                "Toggle Code Actions",
 5590                                &ToggleCodeActions {
 5591                                    deployed_from_indicator: None,
 5592                                },
 5593                                &focus_handle,
 5594                                window,
 5595                                cx,
 5596                            )
 5597                        }
 5598                    })
 5599                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5600                        window.focus(&editor.focus_handle(cx));
 5601                        editor.toggle_code_actions(
 5602                            &ToggleCodeActions {
 5603                                deployed_from_indicator: Some(row),
 5604                            },
 5605                            window,
 5606                            cx,
 5607                        );
 5608                    })),
 5609            )
 5610        } else {
 5611            None
 5612        }
 5613    }
 5614
 5615    fn clear_tasks(&mut self) {
 5616        self.tasks.clear()
 5617    }
 5618
 5619    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5620        if self.tasks.insert(key, value).is_some() {
 5621            // This case should hopefully be rare, but just in case...
 5622            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5623        }
 5624    }
 5625
 5626    fn build_tasks_context(
 5627        project: &Entity<Project>,
 5628        buffer: &Entity<Buffer>,
 5629        buffer_row: u32,
 5630        tasks: &Arc<RunnableTasks>,
 5631        cx: &mut Context<Self>,
 5632    ) -> Task<Option<task::TaskContext>> {
 5633        let position = Point::new(buffer_row, tasks.column);
 5634        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5635        let location = Location {
 5636            buffer: buffer.clone(),
 5637            range: range_start..range_start,
 5638        };
 5639        // Fill in the environmental variables from the tree-sitter captures
 5640        let mut captured_task_variables = TaskVariables::default();
 5641        for (capture_name, value) in tasks.extra_variables.clone() {
 5642            captured_task_variables.insert(
 5643                task::VariableName::Custom(capture_name.into()),
 5644                value.clone(),
 5645            );
 5646        }
 5647        project.update(cx, |project, cx| {
 5648            project.task_store().update(cx, |task_store, cx| {
 5649                task_store.task_context_for_location(captured_task_variables, location, cx)
 5650            })
 5651        })
 5652    }
 5653
 5654    pub fn spawn_nearest_task(
 5655        &mut self,
 5656        action: &SpawnNearestTask,
 5657        window: &mut Window,
 5658        cx: &mut Context<Self>,
 5659    ) {
 5660        let Some((workspace, _)) = self.workspace.clone() else {
 5661            return;
 5662        };
 5663        let Some(project) = self.project.clone() else {
 5664            return;
 5665        };
 5666
 5667        // Try to find a closest, enclosing node using tree-sitter that has a
 5668        // task
 5669        let Some((buffer, buffer_row, tasks)) = self
 5670            .find_enclosing_node_task(cx)
 5671            // Or find the task that's closest in row-distance.
 5672            .or_else(|| self.find_closest_task(cx))
 5673        else {
 5674            return;
 5675        };
 5676
 5677        let reveal_strategy = action.reveal;
 5678        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5679        cx.spawn_in(window, |_, mut cx| async move {
 5680            let context = task_context.await?;
 5681            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5682
 5683            let resolved = resolved_task.resolved.as_mut()?;
 5684            resolved.reveal = reveal_strategy;
 5685
 5686            workspace
 5687                .update(&mut cx, |workspace, cx| {
 5688                    workspace::tasks::schedule_resolved_task(
 5689                        workspace,
 5690                        task_source_kind,
 5691                        resolved_task,
 5692                        false,
 5693                        cx,
 5694                    );
 5695                })
 5696                .ok()
 5697        })
 5698        .detach();
 5699    }
 5700
 5701    fn find_closest_task(
 5702        &mut self,
 5703        cx: &mut Context<Self>,
 5704    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5705        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5706
 5707        let ((buffer_id, row), tasks) = self
 5708            .tasks
 5709            .iter()
 5710            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5711
 5712        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5713        let tasks = Arc::new(tasks.to_owned());
 5714        Some((buffer, *row, tasks))
 5715    }
 5716
 5717    fn find_enclosing_node_task(
 5718        &mut self,
 5719        cx: &mut Context<Self>,
 5720    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5721        let snapshot = self.buffer.read(cx).snapshot(cx);
 5722        let offset = self.selections.newest::<usize>(cx).head();
 5723        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5724        let buffer_id = excerpt.buffer().remote_id();
 5725
 5726        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5727        let mut cursor = layer.node().walk();
 5728
 5729        while cursor.goto_first_child_for_byte(offset).is_some() {
 5730            if cursor.node().end_byte() == offset {
 5731                cursor.goto_next_sibling();
 5732            }
 5733        }
 5734
 5735        // Ascend to the smallest ancestor that contains the range and has a task.
 5736        loop {
 5737            let node = cursor.node();
 5738            let node_range = node.byte_range();
 5739            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5740
 5741            // Check if this node contains our offset
 5742            if node_range.start <= offset && node_range.end >= offset {
 5743                // If it contains offset, check for task
 5744                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5745                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5746                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5747                }
 5748            }
 5749
 5750            if !cursor.goto_parent() {
 5751                break;
 5752            }
 5753        }
 5754        None
 5755    }
 5756
 5757    fn render_run_indicator(
 5758        &self,
 5759        _style: &EditorStyle,
 5760        is_active: bool,
 5761        row: DisplayRow,
 5762        cx: &mut Context<Self>,
 5763    ) -> IconButton {
 5764        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5765            .shape(ui::IconButtonShape::Square)
 5766            .icon_size(IconSize::XSmall)
 5767            .icon_color(Color::Muted)
 5768            .toggle_state(is_active)
 5769            .on_click(cx.listener(move |editor, _e, window, cx| {
 5770                window.focus(&editor.focus_handle(cx));
 5771                editor.toggle_code_actions(
 5772                    &ToggleCodeActions {
 5773                        deployed_from_indicator: Some(row),
 5774                    },
 5775                    window,
 5776                    cx,
 5777                );
 5778            }))
 5779    }
 5780
 5781    pub fn context_menu_visible(&self) -> bool {
 5782        !self.edit_prediction_preview_is_active()
 5783            && self
 5784                .context_menu
 5785                .borrow()
 5786                .as_ref()
 5787                .map_or(false, |menu| menu.visible())
 5788    }
 5789
 5790    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5791        self.context_menu
 5792            .borrow()
 5793            .as_ref()
 5794            .map(|menu| menu.origin())
 5795    }
 5796
 5797    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5798    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5799
 5800    #[allow(clippy::too_many_arguments)]
 5801    fn render_edit_prediction_popover(
 5802        &mut self,
 5803        text_bounds: &Bounds<Pixels>,
 5804        content_origin: gpui::Point<Pixels>,
 5805        editor_snapshot: &EditorSnapshot,
 5806        visible_row_range: Range<DisplayRow>,
 5807        scroll_top: f32,
 5808        scroll_bottom: f32,
 5809        line_layouts: &[LineWithInvisibles],
 5810        line_height: Pixels,
 5811        scroll_pixel_position: gpui::Point<Pixels>,
 5812        newest_selection_head: Option<DisplayPoint>,
 5813        editor_width: Pixels,
 5814        style: &EditorStyle,
 5815        window: &mut Window,
 5816        cx: &mut App,
 5817    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5818        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5819
 5820        if self.edit_prediction_visible_in_cursor_popover(true) {
 5821            return None;
 5822        }
 5823
 5824        match &active_inline_completion.completion {
 5825            InlineCompletion::Move { target, .. } => {
 5826                let target_display_point = target.to_display_point(editor_snapshot);
 5827
 5828                if self.edit_prediction_requires_modifier() {
 5829                    if !self.edit_prediction_preview_is_active() {
 5830                        return None;
 5831                    }
 5832
 5833                    self.render_edit_prediction_modifier_jump_popover(
 5834                        text_bounds,
 5835                        content_origin,
 5836                        visible_row_range,
 5837                        line_layouts,
 5838                        line_height,
 5839                        scroll_pixel_position,
 5840                        newest_selection_head,
 5841                        target_display_point,
 5842                        window,
 5843                        cx,
 5844                    )
 5845                } else {
 5846                    self.render_edit_prediction_eager_jump_popover(
 5847                        text_bounds,
 5848                        content_origin,
 5849                        editor_snapshot,
 5850                        visible_row_range,
 5851                        scroll_top,
 5852                        scroll_bottom,
 5853                        line_height,
 5854                        scroll_pixel_position,
 5855                        target_display_point,
 5856                        editor_width,
 5857                        window,
 5858                        cx,
 5859                    )
 5860                }
 5861            }
 5862            InlineCompletion::Edit {
 5863                display_mode: EditDisplayMode::Inline,
 5864                ..
 5865            } => None,
 5866            InlineCompletion::Edit {
 5867                display_mode: EditDisplayMode::TabAccept,
 5868                edits,
 5869                ..
 5870            } => {
 5871                let range = &edits.first()?.0;
 5872                let target_display_point = range.end.to_display_point(editor_snapshot);
 5873
 5874                self.render_edit_prediction_end_of_line_popover(
 5875                    "Accept",
 5876                    editor_snapshot,
 5877                    visible_row_range,
 5878                    target_display_point,
 5879                    line_height,
 5880                    scroll_pixel_position,
 5881                    content_origin,
 5882                    editor_width,
 5883                    window,
 5884                    cx,
 5885                )
 5886            }
 5887            InlineCompletion::Edit {
 5888                edits,
 5889                edit_preview,
 5890                display_mode: EditDisplayMode::DiffPopover,
 5891                snapshot,
 5892            } => self.render_edit_prediction_diff_popover(
 5893                text_bounds,
 5894                content_origin,
 5895                editor_snapshot,
 5896                visible_row_range,
 5897                line_layouts,
 5898                line_height,
 5899                scroll_pixel_position,
 5900                newest_selection_head,
 5901                editor_width,
 5902                style,
 5903                edits,
 5904                edit_preview,
 5905                snapshot,
 5906                window,
 5907                cx,
 5908            ),
 5909        }
 5910    }
 5911
 5912    #[allow(clippy::too_many_arguments)]
 5913    fn render_edit_prediction_modifier_jump_popover(
 5914        &mut self,
 5915        text_bounds: &Bounds<Pixels>,
 5916        content_origin: gpui::Point<Pixels>,
 5917        visible_row_range: Range<DisplayRow>,
 5918        line_layouts: &[LineWithInvisibles],
 5919        line_height: Pixels,
 5920        scroll_pixel_position: gpui::Point<Pixels>,
 5921        newest_selection_head: Option<DisplayPoint>,
 5922        target_display_point: DisplayPoint,
 5923        window: &mut Window,
 5924        cx: &mut App,
 5925    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5926        let scrolled_content_origin =
 5927            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 5928
 5929        const SCROLL_PADDING_Y: Pixels = px(12.);
 5930
 5931        if target_display_point.row() < visible_row_range.start {
 5932            return self.render_edit_prediction_scroll_popover(
 5933                |_| SCROLL_PADDING_Y,
 5934                IconName::ArrowUp,
 5935                visible_row_range,
 5936                line_layouts,
 5937                newest_selection_head,
 5938                scrolled_content_origin,
 5939                window,
 5940                cx,
 5941            );
 5942        } else if target_display_point.row() >= visible_row_range.end {
 5943            return self.render_edit_prediction_scroll_popover(
 5944                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 5945                IconName::ArrowDown,
 5946                visible_row_range,
 5947                line_layouts,
 5948                newest_selection_head,
 5949                scrolled_content_origin,
 5950                window,
 5951                cx,
 5952            );
 5953        }
 5954
 5955        const POLE_WIDTH: Pixels = px(2.);
 5956
 5957        let mut element = v_flex()
 5958            .items_end()
 5959            .child(
 5960                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 5961                    .rounded_br(px(0.))
 5962                    .rounded_tr(px(0.))
 5963                    .border_r_2(),
 5964            )
 5965            .child(
 5966                div()
 5967                    .w(POLE_WIDTH)
 5968                    .bg(Editor::edit_prediction_callout_popover_border_color(cx))
 5969                    .h(line_height),
 5970            )
 5971            .into_any();
 5972
 5973        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 5974
 5975        let line_layout =
 5976            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 5977        let target_column = target_display_point.column() as usize;
 5978
 5979        let target_x = line_layout.x_for_index(target_column);
 5980        let target_y =
 5981            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 5982
 5983        let mut origin = scrolled_content_origin + point(target_x, target_y)
 5984            - point(size.width - POLE_WIDTH, size.height - line_height);
 5985
 5986        origin.x = origin.x.max(content_origin.x);
 5987
 5988        element.prepaint_at(origin, window, cx);
 5989
 5990        Some((element, origin))
 5991    }
 5992
 5993    #[allow(clippy::too_many_arguments)]
 5994    fn render_edit_prediction_scroll_popover(
 5995        &mut self,
 5996        to_y: impl Fn(Size<Pixels>) -> Pixels,
 5997        scroll_icon: IconName,
 5998        visible_row_range: Range<DisplayRow>,
 5999        line_layouts: &[LineWithInvisibles],
 6000        newest_selection_head: Option<DisplayPoint>,
 6001        scrolled_content_origin: gpui::Point<Pixels>,
 6002        window: &mut Window,
 6003        cx: &mut App,
 6004    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6005        let mut element = self
 6006            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6007            .into_any();
 6008
 6009        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6010
 6011        let cursor = newest_selection_head?;
 6012        let cursor_row_layout =
 6013            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6014        let cursor_column = cursor.column() as usize;
 6015
 6016        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6017
 6018        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6019
 6020        element.prepaint_at(origin, window, cx);
 6021        Some((element, origin))
 6022    }
 6023
 6024    #[allow(clippy::too_many_arguments)]
 6025    fn render_edit_prediction_eager_jump_popover(
 6026        &mut self,
 6027        text_bounds: &Bounds<Pixels>,
 6028        content_origin: gpui::Point<Pixels>,
 6029        editor_snapshot: &EditorSnapshot,
 6030        visible_row_range: Range<DisplayRow>,
 6031        scroll_top: f32,
 6032        scroll_bottom: f32,
 6033        line_height: Pixels,
 6034        scroll_pixel_position: gpui::Point<Pixels>,
 6035        target_display_point: DisplayPoint,
 6036        editor_width: Pixels,
 6037        window: &mut Window,
 6038        cx: &mut App,
 6039    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6040        if target_display_point.row().as_f32() < scroll_top {
 6041            let mut element = self
 6042                .render_edit_prediction_line_popover(
 6043                    "Jump to Edit",
 6044                    Some(IconName::ArrowUp),
 6045                    window,
 6046                    cx,
 6047                )?
 6048                .into_any();
 6049
 6050            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6051            let offset = point(
 6052                (text_bounds.size.width - size.width) / 2.,
 6053                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6054            );
 6055
 6056            let origin = text_bounds.origin + offset;
 6057            element.prepaint_at(origin, window, cx);
 6058            Some((element, origin))
 6059        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6060            let mut element = self
 6061                .render_edit_prediction_line_popover(
 6062                    "Jump to Edit",
 6063                    Some(IconName::ArrowDown),
 6064                    window,
 6065                    cx,
 6066                )?
 6067                .into_any();
 6068
 6069            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6070            let offset = point(
 6071                (text_bounds.size.width - size.width) / 2.,
 6072                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6073            );
 6074
 6075            let origin = text_bounds.origin + offset;
 6076            element.prepaint_at(origin, window, cx);
 6077            Some((element, origin))
 6078        } else {
 6079            self.render_edit_prediction_end_of_line_popover(
 6080                "Jump to Edit",
 6081                editor_snapshot,
 6082                visible_row_range,
 6083                target_display_point,
 6084                line_height,
 6085                scroll_pixel_position,
 6086                content_origin,
 6087                editor_width,
 6088                window,
 6089                cx,
 6090            )
 6091        }
 6092    }
 6093
 6094    #[allow(clippy::too_many_arguments)]
 6095    fn render_edit_prediction_end_of_line_popover(
 6096        self: &mut Editor,
 6097        label: &'static str,
 6098        editor_snapshot: &EditorSnapshot,
 6099        visible_row_range: Range<DisplayRow>,
 6100        target_display_point: DisplayPoint,
 6101        line_height: Pixels,
 6102        scroll_pixel_position: gpui::Point<Pixels>,
 6103        content_origin: gpui::Point<Pixels>,
 6104        editor_width: Pixels,
 6105        window: &mut Window,
 6106        cx: &mut App,
 6107    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6108        let target_line_end = DisplayPoint::new(
 6109            target_display_point.row(),
 6110            editor_snapshot.line_len(target_display_point.row()),
 6111        );
 6112
 6113        let mut element = self
 6114            .render_edit_prediction_line_popover(label, None, window, cx)?
 6115            .into_any();
 6116
 6117        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6118
 6119        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6120
 6121        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6122        let mut origin = start_point
 6123            + line_origin
 6124            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6125        origin.x = origin.x.max(content_origin.x);
 6126
 6127        let max_x = content_origin.x + editor_width - size.width;
 6128
 6129        if origin.x > max_x {
 6130            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6131
 6132            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6133                origin.y += offset;
 6134                IconName::ArrowUp
 6135            } else {
 6136                origin.y -= offset;
 6137                IconName::ArrowDown
 6138            };
 6139
 6140            element = self
 6141                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6142                .into_any();
 6143
 6144            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6145
 6146            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6147        }
 6148
 6149        element.prepaint_at(origin, window, cx);
 6150        Some((element, origin))
 6151    }
 6152
 6153    #[allow(clippy::too_many_arguments)]
 6154    fn render_edit_prediction_diff_popover(
 6155        self: &Editor,
 6156        text_bounds: &Bounds<Pixels>,
 6157        content_origin: gpui::Point<Pixels>,
 6158        editor_snapshot: &EditorSnapshot,
 6159        visible_row_range: Range<DisplayRow>,
 6160        line_layouts: &[LineWithInvisibles],
 6161        line_height: Pixels,
 6162        scroll_pixel_position: gpui::Point<Pixels>,
 6163        newest_selection_head: Option<DisplayPoint>,
 6164        editor_width: Pixels,
 6165        style: &EditorStyle,
 6166        edits: &Vec<(Range<Anchor>, String)>,
 6167        edit_preview: &Option<language::EditPreview>,
 6168        snapshot: &language::BufferSnapshot,
 6169        window: &mut Window,
 6170        cx: &mut App,
 6171    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6172        let edit_start = edits
 6173            .first()
 6174            .unwrap()
 6175            .0
 6176            .start
 6177            .to_display_point(editor_snapshot);
 6178        let edit_end = edits
 6179            .last()
 6180            .unwrap()
 6181            .0
 6182            .end
 6183            .to_display_point(editor_snapshot);
 6184
 6185        let is_visible = visible_row_range.contains(&edit_start.row())
 6186            || visible_row_range.contains(&edit_end.row());
 6187        if !is_visible {
 6188            return None;
 6189        }
 6190
 6191        let highlighted_edits =
 6192            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6193
 6194        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6195        let line_count = highlighted_edits.text.lines().count();
 6196
 6197        const BORDER_WIDTH: Pixels = px(1.);
 6198
 6199        let mut element = h_flex()
 6200            .items_start()
 6201            .child(
 6202                h_flex()
 6203                    .bg(cx.theme().colors().editor_background)
 6204                    .border(BORDER_WIDTH)
 6205                    .shadow_sm()
 6206                    .border_color(cx.theme().colors().border)
 6207                    .rounded_l_lg()
 6208                    .when(line_count > 1, |el| el.rounded_br_lg())
 6209                    .pr_1()
 6210                    .child(styled_text),
 6211            )
 6212            .child(
 6213                h_flex()
 6214                    .h(line_height + BORDER_WIDTH * px(2.))
 6215                    .px_1p5()
 6216                    .gap_1()
 6217                    // Workaround: For some reason, there's a gap if we don't do this
 6218                    .ml(-BORDER_WIDTH)
 6219                    .shadow(smallvec![gpui::BoxShadow {
 6220                        color: gpui::black().opacity(0.05),
 6221                        offset: point(px(1.), px(1.)),
 6222                        blur_radius: px(2.),
 6223                        spread_radius: px(0.),
 6224                    }])
 6225                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6226                    .border(BORDER_WIDTH)
 6227                    .border_color(cx.theme().colors().border)
 6228                    .rounded_r_lg()
 6229                    .children(self.render_edit_prediction_accept_keybind(window, cx)),
 6230            )
 6231            .into_any();
 6232
 6233        let longest_row =
 6234            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6235        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6236            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6237        } else {
 6238            layout_line(
 6239                longest_row,
 6240                editor_snapshot,
 6241                style,
 6242                editor_width,
 6243                |_| false,
 6244                window,
 6245                cx,
 6246            )
 6247            .width
 6248        };
 6249
 6250        let viewport_bounds =
 6251            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6252                right: -EditorElement::SCROLLBAR_WIDTH,
 6253                ..Default::default()
 6254            });
 6255
 6256        let x_after_longest =
 6257            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6258                - scroll_pixel_position.x;
 6259
 6260        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6261
 6262        // Fully visible if it can be displayed within the window (allow overlapping other
 6263        // panes). However, this is only allowed if the popover starts within text_bounds.
 6264        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6265            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6266
 6267        let mut origin = if can_position_to_the_right {
 6268            point(
 6269                x_after_longest,
 6270                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6271                    - scroll_pixel_position.y,
 6272            )
 6273        } else {
 6274            let cursor_row = newest_selection_head.map(|head| head.row());
 6275            let above_edit = edit_start
 6276                .row()
 6277                .0
 6278                .checked_sub(line_count as u32)
 6279                .map(DisplayRow);
 6280            let below_edit = Some(edit_end.row() + 1);
 6281            let above_cursor =
 6282                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6283            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6284
 6285            // Place the edit popover adjacent to the edit if there is a location
 6286            // available that is onscreen and does not obscure the cursor. Otherwise,
 6287            // place it adjacent to the cursor.
 6288            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6289                .into_iter()
 6290                .flatten()
 6291                .find(|&start_row| {
 6292                    let end_row = start_row + line_count as u32;
 6293                    visible_row_range.contains(&start_row)
 6294                        && visible_row_range.contains(&end_row)
 6295                        && cursor_row.map_or(true, |cursor_row| {
 6296                            !((start_row..end_row).contains(&cursor_row))
 6297                        })
 6298                })?;
 6299
 6300            content_origin
 6301                + point(
 6302                    -scroll_pixel_position.x,
 6303                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6304                )
 6305        };
 6306
 6307        origin.x -= BORDER_WIDTH;
 6308
 6309        window.defer_draw(element, origin, 1);
 6310
 6311        // Do not return an element, since it will already be drawn due to defer_draw.
 6312        None
 6313    }
 6314
 6315    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6316        px(30.)
 6317    }
 6318
 6319    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6320        if self.read_only(cx) {
 6321            cx.theme().players().read_only()
 6322        } else {
 6323            self.style.as_ref().unwrap().local_player
 6324        }
 6325    }
 6326
 6327    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 6328        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6329        let accept_keystroke = accept_binding.keystroke()?;
 6330
 6331        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6332
 6333        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6334            Color::Accent
 6335        } else {
 6336            Color::Muted
 6337        };
 6338
 6339        h_flex()
 6340            .px_0p5()
 6341            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6342            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6343            .text_size(TextSize::XSmall.rems(cx))
 6344            .child(h_flex().children(ui::render_modifiers(
 6345                &accept_keystroke.modifiers,
 6346                PlatformStyle::platform(),
 6347                Some(modifiers_color),
 6348                Some(IconSize::XSmall.rems().into()),
 6349                true,
 6350            )))
 6351            .when(is_platform_style_mac, |parent| {
 6352                parent.child(accept_keystroke.key.clone())
 6353            })
 6354            .when(!is_platform_style_mac, |parent| {
 6355                parent.child(
 6356                    Key::new(
 6357                        util::capitalize(&accept_keystroke.key),
 6358                        Some(Color::Default),
 6359                    )
 6360                    .size(Some(IconSize::XSmall.rems().into())),
 6361                )
 6362            })
 6363            .into()
 6364    }
 6365
 6366    fn render_edit_prediction_line_popover(
 6367        &self,
 6368        label: impl Into<SharedString>,
 6369        icon: Option<IconName>,
 6370        window: &mut Window,
 6371        cx: &App,
 6372    ) -> Option<Div> {
 6373        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6374
 6375        let result = h_flex()
 6376            .py_0p5()
 6377            .pl_1()
 6378            .pr(padding_right)
 6379            .gap_1()
 6380            .rounded(px(6.))
 6381            .border_1()
 6382            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6383            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6384            .shadow_sm()
 6385            .children(self.render_edit_prediction_accept_keybind(window, cx))
 6386            .child(Label::new(label).size(LabelSize::Small))
 6387            .when_some(icon, |element, icon| {
 6388                element.child(
 6389                    div()
 6390                        .mt(px(1.5))
 6391                        .child(Icon::new(icon).size(IconSize::Small)),
 6392                )
 6393            });
 6394
 6395        Some(result)
 6396    }
 6397
 6398    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6399        let accent_color = cx.theme().colors().text_accent;
 6400        let editor_bg_color = cx.theme().colors().editor_background;
 6401        editor_bg_color.blend(accent_color.opacity(0.1))
 6402    }
 6403
 6404    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6405        let accent_color = cx.theme().colors().text_accent;
 6406        let editor_bg_color = cx.theme().colors().editor_background;
 6407        editor_bg_color.blend(accent_color.opacity(0.6))
 6408    }
 6409
 6410    #[allow(clippy::too_many_arguments)]
 6411    fn render_edit_prediction_cursor_popover(
 6412        &self,
 6413        min_width: Pixels,
 6414        max_width: Pixels,
 6415        cursor_point: Point,
 6416        style: &EditorStyle,
 6417        accept_keystroke: Option<&gpui::Keystroke>,
 6418        _window: &Window,
 6419        cx: &mut Context<Editor>,
 6420    ) -> Option<AnyElement> {
 6421        let provider = self.edit_prediction_provider.as_ref()?;
 6422
 6423        if provider.provider.needs_terms_acceptance(cx) {
 6424            return Some(
 6425                h_flex()
 6426                    .min_w(min_width)
 6427                    .flex_1()
 6428                    .px_2()
 6429                    .py_1()
 6430                    .gap_3()
 6431                    .elevation_2(cx)
 6432                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6433                    .id("accept-terms")
 6434                    .cursor_pointer()
 6435                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6436                    .on_click(cx.listener(|this, _event, window, cx| {
 6437                        cx.stop_propagation();
 6438                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6439                        window.dispatch_action(
 6440                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6441                            cx,
 6442                        );
 6443                    }))
 6444                    .child(
 6445                        h_flex()
 6446                            .flex_1()
 6447                            .gap_2()
 6448                            .child(Icon::new(IconName::ZedPredict))
 6449                            .child(Label::new("Accept Terms of Service"))
 6450                            .child(div().w_full())
 6451                            .child(
 6452                                Icon::new(IconName::ArrowUpRight)
 6453                                    .color(Color::Muted)
 6454                                    .size(IconSize::Small),
 6455                            )
 6456                            .into_any_element(),
 6457                    )
 6458                    .into_any(),
 6459            );
 6460        }
 6461
 6462        let is_refreshing = provider.provider.is_refreshing(cx);
 6463
 6464        fn pending_completion_container() -> Div {
 6465            h_flex()
 6466                .h_full()
 6467                .flex_1()
 6468                .gap_2()
 6469                .child(Icon::new(IconName::ZedPredict))
 6470        }
 6471
 6472        let completion = match &self.active_inline_completion {
 6473            Some(completion) => match &completion.completion {
 6474                InlineCompletion::Move {
 6475                    target, snapshot, ..
 6476                } if !self.has_visible_completions_menu() => {
 6477                    use text::ToPoint as _;
 6478
 6479                    return Some(
 6480                        h_flex()
 6481                            .px_2()
 6482                            .py_1()
 6483                            .gap_2()
 6484                            .elevation_2(cx)
 6485                            .border_color(cx.theme().colors().border)
 6486                            .rounded(px(6.))
 6487                            .rounded_tl(px(0.))
 6488                            .child(
 6489                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6490                                    Icon::new(IconName::ZedPredictDown)
 6491                                } else {
 6492                                    Icon::new(IconName::ZedPredictUp)
 6493                                },
 6494                            )
 6495                            .child(Label::new("Hold").size(LabelSize::Small))
 6496                            .child(h_flex().children(ui::render_modifiers(
 6497                                &accept_keystroke?.modifiers,
 6498                                PlatformStyle::platform(),
 6499                                Some(Color::Default),
 6500                                Some(IconSize::Small.rems().into()),
 6501                                false,
 6502                            )))
 6503                            .into_any(),
 6504                    );
 6505                }
 6506                _ => self.render_edit_prediction_cursor_popover_preview(
 6507                    completion,
 6508                    cursor_point,
 6509                    style,
 6510                    cx,
 6511                )?,
 6512            },
 6513
 6514            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6515                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6516                    stale_completion,
 6517                    cursor_point,
 6518                    style,
 6519                    cx,
 6520                )?,
 6521
 6522                None => {
 6523                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6524                }
 6525            },
 6526
 6527            None => pending_completion_container().child(Label::new("No Prediction")),
 6528        };
 6529
 6530        let completion = if is_refreshing {
 6531            completion
 6532                .with_animation(
 6533                    "loading-completion",
 6534                    Animation::new(Duration::from_secs(2))
 6535                        .repeat()
 6536                        .with_easing(pulsating_between(0.4, 0.8)),
 6537                    |label, delta| label.opacity(delta),
 6538                )
 6539                .into_any_element()
 6540        } else {
 6541            completion.into_any_element()
 6542        };
 6543
 6544        let has_completion = self.active_inline_completion.is_some();
 6545
 6546        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6547        Some(
 6548            h_flex()
 6549                .min_w(min_width)
 6550                .max_w(max_width)
 6551                .flex_1()
 6552                .elevation_2(cx)
 6553                .border_color(cx.theme().colors().border)
 6554                .child(
 6555                    div()
 6556                        .flex_1()
 6557                        .py_1()
 6558                        .px_2()
 6559                        .overflow_hidden()
 6560                        .child(completion),
 6561                )
 6562                .when_some(accept_keystroke, |el, accept_keystroke| {
 6563                    if !accept_keystroke.modifiers.modified() {
 6564                        return el;
 6565                    }
 6566
 6567                    el.child(
 6568                        h_flex()
 6569                            .h_full()
 6570                            .border_l_1()
 6571                            .rounded_r_lg()
 6572                            .border_color(cx.theme().colors().border)
 6573                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6574                            .gap_1()
 6575                            .py_1()
 6576                            .px_2()
 6577                            .child(
 6578                                h_flex()
 6579                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6580                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6581                                    .child(h_flex().children(ui::render_modifiers(
 6582                                        &accept_keystroke.modifiers,
 6583                                        PlatformStyle::platform(),
 6584                                        Some(if !has_completion {
 6585                                            Color::Muted
 6586                                        } else {
 6587                                            Color::Default
 6588                                        }),
 6589                                        None,
 6590                                        false,
 6591                                    ))),
 6592                            )
 6593                            .child(Label::new("Preview").into_any_element())
 6594                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6595                    )
 6596                })
 6597                .into_any(),
 6598        )
 6599    }
 6600
 6601    fn render_edit_prediction_cursor_popover_preview(
 6602        &self,
 6603        completion: &InlineCompletionState,
 6604        cursor_point: Point,
 6605        style: &EditorStyle,
 6606        cx: &mut Context<Editor>,
 6607    ) -> Option<Div> {
 6608        use text::ToPoint as _;
 6609
 6610        fn render_relative_row_jump(
 6611            prefix: impl Into<String>,
 6612            current_row: u32,
 6613            target_row: u32,
 6614        ) -> Div {
 6615            let (row_diff, arrow) = if target_row < current_row {
 6616                (current_row - target_row, IconName::ArrowUp)
 6617            } else {
 6618                (target_row - current_row, IconName::ArrowDown)
 6619            };
 6620
 6621            h_flex()
 6622                .child(
 6623                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6624                        .color(Color::Muted)
 6625                        .size(LabelSize::Small),
 6626                )
 6627                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6628        }
 6629
 6630        match &completion.completion {
 6631            InlineCompletion::Move {
 6632                target, snapshot, ..
 6633            } => Some(
 6634                h_flex()
 6635                    .px_2()
 6636                    .gap_2()
 6637                    .flex_1()
 6638                    .child(
 6639                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6640                            Icon::new(IconName::ZedPredictDown)
 6641                        } else {
 6642                            Icon::new(IconName::ZedPredictUp)
 6643                        },
 6644                    )
 6645                    .child(Label::new("Jump to Edit")),
 6646            ),
 6647
 6648            InlineCompletion::Edit {
 6649                edits,
 6650                edit_preview,
 6651                snapshot,
 6652                display_mode: _,
 6653            } => {
 6654                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6655
 6656                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6657                    &snapshot,
 6658                    &edits,
 6659                    edit_preview.as_ref()?,
 6660                    true,
 6661                    cx,
 6662                )
 6663                .first_line_preview();
 6664
 6665                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6666                    .with_highlights(&style.text, highlighted_edits.highlights);
 6667
 6668                let preview = h_flex()
 6669                    .gap_1()
 6670                    .min_w_16()
 6671                    .child(styled_text)
 6672                    .when(has_more_lines, |parent| parent.child(""));
 6673
 6674                let left = if first_edit_row != cursor_point.row {
 6675                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6676                        .into_any_element()
 6677                } else {
 6678                    Icon::new(IconName::ZedPredict).into_any_element()
 6679                };
 6680
 6681                Some(
 6682                    h_flex()
 6683                        .h_full()
 6684                        .flex_1()
 6685                        .gap_2()
 6686                        .pr_1()
 6687                        .overflow_x_hidden()
 6688                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6689                        .child(left)
 6690                        .child(preview),
 6691                )
 6692            }
 6693        }
 6694    }
 6695
 6696    fn render_context_menu(
 6697        &self,
 6698        style: &EditorStyle,
 6699        max_height_in_lines: u32,
 6700        y_flipped: bool,
 6701        window: &mut Window,
 6702        cx: &mut Context<Editor>,
 6703    ) -> Option<AnyElement> {
 6704        let menu = self.context_menu.borrow();
 6705        let menu = menu.as_ref()?;
 6706        if !menu.visible() {
 6707            return None;
 6708        };
 6709        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6710    }
 6711
 6712    fn render_context_menu_aside(
 6713        &mut self,
 6714        max_size: Size<Pixels>,
 6715        window: &mut Window,
 6716        cx: &mut Context<Editor>,
 6717    ) -> Option<AnyElement> {
 6718        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6719            if menu.visible() {
 6720                menu.render_aside(self, max_size, window, cx)
 6721            } else {
 6722                None
 6723            }
 6724        })
 6725    }
 6726
 6727    fn hide_context_menu(
 6728        &mut self,
 6729        window: &mut Window,
 6730        cx: &mut Context<Self>,
 6731    ) -> Option<CodeContextMenu> {
 6732        cx.notify();
 6733        self.completion_tasks.clear();
 6734        let context_menu = self.context_menu.borrow_mut().take();
 6735        self.stale_inline_completion_in_menu.take();
 6736        self.update_visible_inline_completion(window, cx);
 6737        context_menu
 6738    }
 6739
 6740    fn show_snippet_choices(
 6741        &mut self,
 6742        choices: &Vec<String>,
 6743        selection: Range<Anchor>,
 6744        cx: &mut Context<Self>,
 6745    ) {
 6746        if selection.start.buffer_id.is_none() {
 6747            return;
 6748        }
 6749        let buffer_id = selection.start.buffer_id.unwrap();
 6750        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6751        let id = post_inc(&mut self.next_completion_id);
 6752
 6753        if let Some(buffer) = buffer {
 6754            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6755                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6756            ));
 6757        }
 6758    }
 6759
 6760    pub fn insert_snippet(
 6761        &mut self,
 6762        insertion_ranges: &[Range<usize>],
 6763        snippet: Snippet,
 6764        window: &mut Window,
 6765        cx: &mut Context<Self>,
 6766    ) -> Result<()> {
 6767        struct Tabstop<T> {
 6768            is_end_tabstop: bool,
 6769            ranges: Vec<Range<T>>,
 6770            choices: Option<Vec<String>>,
 6771        }
 6772
 6773        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6774            let snippet_text: Arc<str> = snippet.text.clone().into();
 6775            buffer.edit(
 6776                insertion_ranges
 6777                    .iter()
 6778                    .cloned()
 6779                    .map(|range| (range, snippet_text.clone())),
 6780                Some(AutoindentMode::EachLine),
 6781                cx,
 6782            );
 6783
 6784            let snapshot = &*buffer.read(cx);
 6785            let snippet = &snippet;
 6786            snippet
 6787                .tabstops
 6788                .iter()
 6789                .map(|tabstop| {
 6790                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6791                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6792                    });
 6793                    let mut tabstop_ranges = tabstop
 6794                        .ranges
 6795                        .iter()
 6796                        .flat_map(|tabstop_range| {
 6797                            let mut delta = 0_isize;
 6798                            insertion_ranges.iter().map(move |insertion_range| {
 6799                                let insertion_start = insertion_range.start as isize + delta;
 6800                                delta +=
 6801                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6802
 6803                                let start = ((insertion_start + tabstop_range.start) as usize)
 6804                                    .min(snapshot.len());
 6805                                let end = ((insertion_start + tabstop_range.end) as usize)
 6806                                    .min(snapshot.len());
 6807                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6808                            })
 6809                        })
 6810                        .collect::<Vec<_>>();
 6811                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6812
 6813                    Tabstop {
 6814                        is_end_tabstop,
 6815                        ranges: tabstop_ranges,
 6816                        choices: tabstop.choices.clone(),
 6817                    }
 6818                })
 6819                .collect::<Vec<_>>()
 6820        });
 6821        if let Some(tabstop) = tabstops.first() {
 6822            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6823                s.select_ranges(tabstop.ranges.iter().cloned());
 6824            });
 6825
 6826            if let Some(choices) = &tabstop.choices {
 6827                if let Some(selection) = tabstop.ranges.first() {
 6828                    self.show_snippet_choices(choices, selection.clone(), cx)
 6829                }
 6830            }
 6831
 6832            // If we're already at the last tabstop and it's at the end of the snippet,
 6833            // we're done, we don't need to keep the state around.
 6834            if !tabstop.is_end_tabstop {
 6835                let choices = tabstops
 6836                    .iter()
 6837                    .map(|tabstop| tabstop.choices.clone())
 6838                    .collect();
 6839
 6840                let ranges = tabstops
 6841                    .into_iter()
 6842                    .map(|tabstop| tabstop.ranges)
 6843                    .collect::<Vec<_>>();
 6844
 6845                self.snippet_stack.push(SnippetState {
 6846                    active_index: 0,
 6847                    ranges,
 6848                    choices,
 6849                });
 6850            }
 6851
 6852            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6853            if self.autoclose_regions.is_empty() {
 6854                let snapshot = self.buffer.read(cx).snapshot(cx);
 6855                for selection in &mut self.selections.all::<Point>(cx) {
 6856                    let selection_head = selection.head();
 6857                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6858                        continue;
 6859                    };
 6860
 6861                    let mut bracket_pair = None;
 6862                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6863                    let prev_chars = snapshot
 6864                        .reversed_chars_at(selection_head)
 6865                        .collect::<String>();
 6866                    for (pair, enabled) in scope.brackets() {
 6867                        if enabled
 6868                            && pair.close
 6869                            && prev_chars.starts_with(pair.start.as_str())
 6870                            && next_chars.starts_with(pair.end.as_str())
 6871                        {
 6872                            bracket_pair = Some(pair.clone());
 6873                            break;
 6874                        }
 6875                    }
 6876                    if let Some(pair) = bracket_pair {
 6877                        let start = snapshot.anchor_after(selection_head);
 6878                        let end = snapshot.anchor_after(selection_head);
 6879                        self.autoclose_regions.push(AutocloseRegion {
 6880                            selection_id: selection.id,
 6881                            range: start..end,
 6882                            pair,
 6883                        });
 6884                    }
 6885                }
 6886            }
 6887        }
 6888        Ok(())
 6889    }
 6890
 6891    pub fn move_to_next_snippet_tabstop(
 6892        &mut self,
 6893        window: &mut Window,
 6894        cx: &mut Context<Self>,
 6895    ) -> bool {
 6896        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6897    }
 6898
 6899    pub fn move_to_prev_snippet_tabstop(
 6900        &mut self,
 6901        window: &mut Window,
 6902        cx: &mut Context<Self>,
 6903    ) -> bool {
 6904        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6905    }
 6906
 6907    pub fn move_to_snippet_tabstop(
 6908        &mut self,
 6909        bias: Bias,
 6910        window: &mut Window,
 6911        cx: &mut Context<Self>,
 6912    ) -> bool {
 6913        if let Some(mut snippet) = self.snippet_stack.pop() {
 6914            match bias {
 6915                Bias::Left => {
 6916                    if snippet.active_index > 0 {
 6917                        snippet.active_index -= 1;
 6918                    } else {
 6919                        self.snippet_stack.push(snippet);
 6920                        return false;
 6921                    }
 6922                }
 6923                Bias::Right => {
 6924                    if snippet.active_index + 1 < snippet.ranges.len() {
 6925                        snippet.active_index += 1;
 6926                    } else {
 6927                        self.snippet_stack.push(snippet);
 6928                        return false;
 6929                    }
 6930                }
 6931            }
 6932            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6933                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6934                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6935                });
 6936
 6937                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6938                    if let Some(selection) = current_ranges.first() {
 6939                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6940                    }
 6941                }
 6942
 6943                // If snippet state is not at the last tabstop, push it back on the stack
 6944                if snippet.active_index + 1 < snippet.ranges.len() {
 6945                    self.snippet_stack.push(snippet);
 6946                }
 6947                return true;
 6948            }
 6949        }
 6950
 6951        false
 6952    }
 6953
 6954    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6955        self.transact(window, cx, |this, window, cx| {
 6956            this.select_all(&SelectAll, window, cx);
 6957            this.insert("", window, cx);
 6958        });
 6959    }
 6960
 6961    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6962        self.transact(window, cx, |this, window, cx| {
 6963            this.select_autoclose_pair(window, cx);
 6964            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6965            if !this.linked_edit_ranges.is_empty() {
 6966                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6967                let snapshot = this.buffer.read(cx).snapshot(cx);
 6968
 6969                for selection in selections.iter() {
 6970                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6971                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6972                    if selection_start.buffer_id != selection_end.buffer_id {
 6973                        continue;
 6974                    }
 6975                    if let Some(ranges) =
 6976                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6977                    {
 6978                        for (buffer, entries) in ranges {
 6979                            linked_ranges.entry(buffer).or_default().extend(entries);
 6980                        }
 6981                    }
 6982                }
 6983            }
 6984
 6985            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6986            if !this.selections.line_mode {
 6987                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6988                for selection in &mut selections {
 6989                    if selection.is_empty() {
 6990                        let old_head = selection.head();
 6991                        let mut new_head =
 6992                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6993                                .to_point(&display_map);
 6994                        if let Some((buffer, line_buffer_range)) = display_map
 6995                            .buffer_snapshot
 6996                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6997                        {
 6998                            let indent_size =
 6999                                buffer.indent_size_for_line(line_buffer_range.start.row);
 7000                            let indent_len = match indent_size.kind {
 7001                                IndentKind::Space => {
 7002                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7003                                }
 7004                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7005                            };
 7006                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7007                                let indent_len = indent_len.get();
 7008                                new_head = cmp::min(
 7009                                    new_head,
 7010                                    MultiBufferPoint::new(
 7011                                        old_head.row,
 7012                                        ((old_head.column - 1) / indent_len) * indent_len,
 7013                                    ),
 7014                                );
 7015                            }
 7016                        }
 7017
 7018                        selection.set_head(new_head, SelectionGoal::None);
 7019                    }
 7020                }
 7021            }
 7022
 7023            this.signature_help_state.set_backspace_pressed(true);
 7024            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7025                s.select(selections)
 7026            });
 7027            this.insert("", window, cx);
 7028            let empty_str: Arc<str> = Arc::from("");
 7029            for (buffer, edits) in linked_ranges {
 7030                let snapshot = buffer.read(cx).snapshot();
 7031                use text::ToPoint as TP;
 7032
 7033                let edits = edits
 7034                    .into_iter()
 7035                    .map(|range| {
 7036                        let end_point = TP::to_point(&range.end, &snapshot);
 7037                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7038
 7039                        if end_point == start_point {
 7040                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7041                                .saturating_sub(1);
 7042                            start_point =
 7043                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7044                        };
 7045
 7046                        (start_point..end_point, empty_str.clone())
 7047                    })
 7048                    .sorted_by_key(|(range, _)| range.start)
 7049                    .collect::<Vec<_>>();
 7050                buffer.update(cx, |this, cx| {
 7051                    this.edit(edits, None, cx);
 7052                })
 7053            }
 7054            this.refresh_inline_completion(true, false, window, cx);
 7055            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7056        });
 7057    }
 7058
 7059    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7060        self.transact(window, cx, |this, window, cx| {
 7061            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7062                let line_mode = s.line_mode;
 7063                s.move_with(|map, selection| {
 7064                    if selection.is_empty() && !line_mode {
 7065                        let cursor = movement::right(map, selection.head());
 7066                        selection.end = cursor;
 7067                        selection.reversed = true;
 7068                        selection.goal = SelectionGoal::None;
 7069                    }
 7070                })
 7071            });
 7072            this.insert("", window, cx);
 7073            this.refresh_inline_completion(true, false, window, cx);
 7074        });
 7075    }
 7076
 7077    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 7078        if self.move_to_prev_snippet_tabstop(window, cx) {
 7079            return;
 7080        }
 7081
 7082        self.outdent(&Outdent, window, cx);
 7083    }
 7084
 7085    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7086        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7087            return;
 7088        }
 7089
 7090        let mut selections = self.selections.all_adjusted(cx);
 7091        let buffer = self.buffer.read(cx);
 7092        let snapshot = buffer.snapshot(cx);
 7093        let rows_iter = selections.iter().map(|s| s.head().row);
 7094        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7095
 7096        let mut edits = Vec::new();
 7097        let mut prev_edited_row = 0;
 7098        let mut row_delta = 0;
 7099        for selection in &mut selections {
 7100            if selection.start.row != prev_edited_row {
 7101                row_delta = 0;
 7102            }
 7103            prev_edited_row = selection.end.row;
 7104
 7105            // If the selection is non-empty, then increase the indentation of the selected lines.
 7106            if !selection.is_empty() {
 7107                row_delta =
 7108                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7109                continue;
 7110            }
 7111
 7112            // If the selection is empty and the cursor is in the leading whitespace before the
 7113            // suggested indentation, then auto-indent the line.
 7114            let cursor = selection.head();
 7115            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7116            if let Some(suggested_indent) =
 7117                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7118            {
 7119                if cursor.column < suggested_indent.len
 7120                    && cursor.column <= current_indent.len
 7121                    && current_indent.len <= suggested_indent.len
 7122                {
 7123                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7124                    selection.end = selection.start;
 7125                    if row_delta == 0 {
 7126                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7127                            cursor.row,
 7128                            current_indent,
 7129                            suggested_indent,
 7130                        ));
 7131                        row_delta = suggested_indent.len - current_indent.len;
 7132                    }
 7133                    continue;
 7134                }
 7135            }
 7136
 7137            // Otherwise, insert a hard or soft tab.
 7138            let settings = buffer.settings_at(cursor, cx);
 7139            let tab_size = if settings.hard_tabs {
 7140                IndentSize::tab()
 7141            } else {
 7142                let tab_size = settings.tab_size.get();
 7143                let char_column = snapshot
 7144                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7145                    .flat_map(str::chars)
 7146                    .count()
 7147                    + row_delta as usize;
 7148                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7149                IndentSize::spaces(chars_to_next_tab_stop)
 7150            };
 7151            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7152            selection.end = selection.start;
 7153            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7154            row_delta += tab_size.len;
 7155        }
 7156
 7157        self.transact(window, cx, |this, window, cx| {
 7158            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7159            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7160                s.select(selections)
 7161            });
 7162            this.refresh_inline_completion(true, false, window, cx);
 7163        });
 7164    }
 7165
 7166    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7167        if self.read_only(cx) {
 7168            return;
 7169        }
 7170        let mut selections = self.selections.all::<Point>(cx);
 7171        let mut prev_edited_row = 0;
 7172        let mut row_delta = 0;
 7173        let mut edits = Vec::new();
 7174        let buffer = self.buffer.read(cx);
 7175        let snapshot = buffer.snapshot(cx);
 7176        for selection in &mut selections {
 7177            if selection.start.row != prev_edited_row {
 7178                row_delta = 0;
 7179            }
 7180            prev_edited_row = selection.end.row;
 7181
 7182            row_delta =
 7183                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7184        }
 7185
 7186        self.transact(window, cx, |this, window, cx| {
 7187            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7188            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7189                s.select(selections)
 7190            });
 7191        });
 7192    }
 7193
 7194    fn indent_selection(
 7195        buffer: &MultiBuffer,
 7196        snapshot: &MultiBufferSnapshot,
 7197        selection: &mut Selection<Point>,
 7198        edits: &mut Vec<(Range<Point>, String)>,
 7199        delta_for_start_row: u32,
 7200        cx: &App,
 7201    ) -> u32 {
 7202        let settings = buffer.settings_at(selection.start, cx);
 7203        let tab_size = settings.tab_size.get();
 7204        let indent_kind = if settings.hard_tabs {
 7205            IndentKind::Tab
 7206        } else {
 7207            IndentKind::Space
 7208        };
 7209        let mut start_row = selection.start.row;
 7210        let mut end_row = selection.end.row + 1;
 7211
 7212        // If a selection ends at the beginning of a line, don't indent
 7213        // that last line.
 7214        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7215            end_row -= 1;
 7216        }
 7217
 7218        // Avoid re-indenting a row that has already been indented by a
 7219        // previous selection, but still update this selection's column
 7220        // to reflect that indentation.
 7221        if delta_for_start_row > 0 {
 7222            start_row += 1;
 7223            selection.start.column += delta_for_start_row;
 7224            if selection.end.row == selection.start.row {
 7225                selection.end.column += delta_for_start_row;
 7226            }
 7227        }
 7228
 7229        let mut delta_for_end_row = 0;
 7230        let has_multiple_rows = start_row + 1 != end_row;
 7231        for row in start_row..end_row {
 7232            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7233            let indent_delta = match (current_indent.kind, indent_kind) {
 7234                (IndentKind::Space, IndentKind::Space) => {
 7235                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7236                    IndentSize::spaces(columns_to_next_tab_stop)
 7237                }
 7238                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7239                (_, IndentKind::Tab) => IndentSize::tab(),
 7240            };
 7241
 7242            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7243                0
 7244            } else {
 7245                selection.start.column
 7246            };
 7247            let row_start = Point::new(row, start);
 7248            edits.push((
 7249                row_start..row_start,
 7250                indent_delta.chars().collect::<String>(),
 7251            ));
 7252
 7253            // Update this selection's endpoints to reflect the indentation.
 7254            if row == selection.start.row {
 7255                selection.start.column += indent_delta.len;
 7256            }
 7257            if row == selection.end.row {
 7258                selection.end.column += indent_delta.len;
 7259                delta_for_end_row = indent_delta.len;
 7260            }
 7261        }
 7262
 7263        if selection.start.row == selection.end.row {
 7264            delta_for_start_row + delta_for_end_row
 7265        } else {
 7266            delta_for_end_row
 7267        }
 7268    }
 7269
 7270    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7271        if self.read_only(cx) {
 7272            return;
 7273        }
 7274        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7275        let selections = self.selections.all::<Point>(cx);
 7276        let mut deletion_ranges = Vec::new();
 7277        let mut last_outdent = None;
 7278        {
 7279            let buffer = self.buffer.read(cx);
 7280            let snapshot = buffer.snapshot(cx);
 7281            for selection in &selections {
 7282                let settings = buffer.settings_at(selection.start, cx);
 7283                let tab_size = settings.tab_size.get();
 7284                let mut rows = selection.spanned_rows(false, &display_map);
 7285
 7286                // Avoid re-outdenting a row that has already been outdented by a
 7287                // previous selection.
 7288                if let Some(last_row) = last_outdent {
 7289                    if last_row == rows.start {
 7290                        rows.start = rows.start.next_row();
 7291                    }
 7292                }
 7293                let has_multiple_rows = rows.len() > 1;
 7294                for row in rows.iter_rows() {
 7295                    let indent_size = snapshot.indent_size_for_line(row);
 7296                    if indent_size.len > 0 {
 7297                        let deletion_len = match indent_size.kind {
 7298                            IndentKind::Space => {
 7299                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7300                                if columns_to_prev_tab_stop == 0 {
 7301                                    tab_size
 7302                                } else {
 7303                                    columns_to_prev_tab_stop
 7304                                }
 7305                            }
 7306                            IndentKind::Tab => 1,
 7307                        };
 7308                        let start = if has_multiple_rows
 7309                            || deletion_len > selection.start.column
 7310                            || indent_size.len < selection.start.column
 7311                        {
 7312                            0
 7313                        } else {
 7314                            selection.start.column - deletion_len
 7315                        };
 7316                        deletion_ranges.push(
 7317                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7318                        );
 7319                        last_outdent = Some(row);
 7320                    }
 7321                }
 7322            }
 7323        }
 7324
 7325        self.transact(window, cx, |this, window, cx| {
 7326            this.buffer.update(cx, |buffer, cx| {
 7327                let empty_str: Arc<str> = Arc::default();
 7328                buffer.edit(
 7329                    deletion_ranges
 7330                        .into_iter()
 7331                        .map(|range| (range, empty_str.clone())),
 7332                    None,
 7333                    cx,
 7334                );
 7335            });
 7336            let selections = this.selections.all::<usize>(cx);
 7337            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7338                s.select(selections)
 7339            });
 7340        });
 7341    }
 7342
 7343    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7344        if self.read_only(cx) {
 7345            return;
 7346        }
 7347        let selections = self
 7348            .selections
 7349            .all::<usize>(cx)
 7350            .into_iter()
 7351            .map(|s| s.range());
 7352
 7353        self.transact(window, cx, |this, window, cx| {
 7354            this.buffer.update(cx, |buffer, cx| {
 7355                buffer.autoindent_ranges(selections, cx);
 7356            });
 7357            let selections = this.selections.all::<usize>(cx);
 7358            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7359                s.select(selections)
 7360            });
 7361        });
 7362    }
 7363
 7364    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7365        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7366        let selections = self.selections.all::<Point>(cx);
 7367
 7368        let mut new_cursors = Vec::new();
 7369        let mut edit_ranges = Vec::new();
 7370        let mut selections = selections.iter().peekable();
 7371        while let Some(selection) = selections.next() {
 7372            let mut rows = selection.spanned_rows(false, &display_map);
 7373            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7374
 7375            // Accumulate contiguous regions of rows that we want to delete.
 7376            while let Some(next_selection) = selections.peek() {
 7377                let next_rows = next_selection.spanned_rows(false, &display_map);
 7378                if next_rows.start <= rows.end {
 7379                    rows.end = next_rows.end;
 7380                    selections.next().unwrap();
 7381                } else {
 7382                    break;
 7383                }
 7384            }
 7385
 7386            let buffer = &display_map.buffer_snapshot;
 7387            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7388            let edit_end;
 7389            let cursor_buffer_row;
 7390            if buffer.max_point().row >= rows.end.0 {
 7391                // If there's a line after the range, delete the \n from the end of the row range
 7392                // and position the cursor on the next line.
 7393                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7394                cursor_buffer_row = rows.end;
 7395            } else {
 7396                // If there isn't a line after the range, delete the \n from the line before the
 7397                // start of the row range and position the cursor there.
 7398                edit_start = edit_start.saturating_sub(1);
 7399                edit_end = buffer.len();
 7400                cursor_buffer_row = rows.start.previous_row();
 7401            }
 7402
 7403            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7404            *cursor.column_mut() =
 7405                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7406
 7407            new_cursors.push((
 7408                selection.id,
 7409                buffer.anchor_after(cursor.to_point(&display_map)),
 7410            ));
 7411            edit_ranges.push(edit_start..edit_end);
 7412        }
 7413
 7414        self.transact(window, cx, |this, window, cx| {
 7415            let buffer = this.buffer.update(cx, |buffer, cx| {
 7416                let empty_str: Arc<str> = Arc::default();
 7417                buffer.edit(
 7418                    edit_ranges
 7419                        .into_iter()
 7420                        .map(|range| (range, empty_str.clone())),
 7421                    None,
 7422                    cx,
 7423                );
 7424                buffer.snapshot(cx)
 7425            });
 7426            let new_selections = new_cursors
 7427                .into_iter()
 7428                .map(|(id, cursor)| {
 7429                    let cursor = cursor.to_point(&buffer);
 7430                    Selection {
 7431                        id,
 7432                        start: cursor,
 7433                        end: cursor,
 7434                        reversed: false,
 7435                        goal: SelectionGoal::None,
 7436                    }
 7437                })
 7438                .collect();
 7439
 7440            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7441                s.select(new_selections);
 7442            });
 7443        });
 7444    }
 7445
 7446    pub fn join_lines_impl(
 7447        &mut self,
 7448        insert_whitespace: bool,
 7449        window: &mut Window,
 7450        cx: &mut Context<Self>,
 7451    ) {
 7452        if self.read_only(cx) {
 7453            return;
 7454        }
 7455        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7456        for selection in self.selections.all::<Point>(cx) {
 7457            let start = MultiBufferRow(selection.start.row);
 7458            // Treat single line selections as if they include the next line. Otherwise this action
 7459            // would do nothing for single line selections individual cursors.
 7460            let end = if selection.start.row == selection.end.row {
 7461                MultiBufferRow(selection.start.row + 1)
 7462            } else {
 7463                MultiBufferRow(selection.end.row)
 7464            };
 7465
 7466            if let Some(last_row_range) = row_ranges.last_mut() {
 7467                if start <= last_row_range.end {
 7468                    last_row_range.end = end;
 7469                    continue;
 7470                }
 7471            }
 7472            row_ranges.push(start..end);
 7473        }
 7474
 7475        let snapshot = self.buffer.read(cx).snapshot(cx);
 7476        let mut cursor_positions = Vec::new();
 7477        for row_range in &row_ranges {
 7478            let anchor = snapshot.anchor_before(Point::new(
 7479                row_range.end.previous_row().0,
 7480                snapshot.line_len(row_range.end.previous_row()),
 7481            ));
 7482            cursor_positions.push(anchor..anchor);
 7483        }
 7484
 7485        self.transact(window, cx, |this, window, cx| {
 7486            for row_range in row_ranges.into_iter().rev() {
 7487                for row in row_range.iter_rows().rev() {
 7488                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7489                    let next_line_row = row.next_row();
 7490                    let indent = snapshot.indent_size_for_line(next_line_row);
 7491                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7492
 7493                    let replace =
 7494                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7495                            " "
 7496                        } else {
 7497                            ""
 7498                        };
 7499
 7500                    this.buffer.update(cx, |buffer, cx| {
 7501                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7502                    });
 7503                }
 7504            }
 7505
 7506            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7507                s.select_anchor_ranges(cursor_positions)
 7508            });
 7509        });
 7510    }
 7511
 7512    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7513        self.join_lines_impl(true, window, cx);
 7514    }
 7515
 7516    pub fn sort_lines_case_sensitive(
 7517        &mut self,
 7518        _: &SortLinesCaseSensitive,
 7519        window: &mut Window,
 7520        cx: &mut Context<Self>,
 7521    ) {
 7522        self.manipulate_lines(window, cx, |lines| lines.sort())
 7523    }
 7524
 7525    pub fn sort_lines_case_insensitive(
 7526        &mut self,
 7527        _: &SortLinesCaseInsensitive,
 7528        window: &mut Window,
 7529        cx: &mut Context<Self>,
 7530    ) {
 7531        self.manipulate_lines(window, cx, |lines| {
 7532            lines.sort_by_key(|line| line.to_lowercase())
 7533        })
 7534    }
 7535
 7536    pub fn unique_lines_case_insensitive(
 7537        &mut self,
 7538        _: &UniqueLinesCaseInsensitive,
 7539        window: &mut Window,
 7540        cx: &mut Context<Self>,
 7541    ) {
 7542        self.manipulate_lines(window, cx, |lines| {
 7543            let mut seen = HashSet::default();
 7544            lines.retain(|line| seen.insert(line.to_lowercase()));
 7545        })
 7546    }
 7547
 7548    pub fn unique_lines_case_sensitive(
 7549        &mut self,
 7550        _: &UniqueLinesCaseSensitive,
 7551        window: &mut Window,
 7552        cx: &mut Context<Self>,
 7553    ) {
 7554        self.manipulate_lines(window, cx, |lines| {
 7555            let mut seen = HashSet::default();
 7556            lines.retain(|line| seen.insert(*line));
 7557        })
 7558    }
 7559
 7560    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7561        let Some(project) = self.project.clone() else {
 7562            return;
 7563        };
 7564        self.reload(project, window, cx)
 7565            .detach_and_notify_err(window, cx);
 7566    }
 7567
 7568    pub fn restore_file(
 7569        &mut self,
 7570        _: &::git::RestoreFile,
 7571        window: &mut Window,
 7572        cx: &mut Context<Self>,
 7573    ) {
 7574        let mut buffer_ids = HashSet::default();
 7575        let snapshot = self.buffer().read(cx).snapshot(cx);
 7576        for selection in self.selections.all::<usize>(cx) {
 7577            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7578        }
 7579
 7580        let buffer = self.buffer().read(cx);
 7581        let ranges = buffer_ids
 7582            .into_iter()
 7583            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7584            .collect::<Vec<_>>();
 7585
 7586        self.restore_hunks_in_ranges(ranges, window, cx);
 7587    }
 7588
 7589    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7590        let selections = self
 7591            .selections
 7592            .all(cx)
 7593            .into_iter()
 7594            .map(|s| s.range())
 7595            .collect();
 7596        self.restore_hunks_in_ranges(selections, window, cx);
 7597    }
 7598
 7599    fn restore_hunks_in_ranges(
 7600        &mut self,
 7601        ranges: Vec<Range<Point>>,
 7602        window: &mut Window,
 7603        cx: &mut Context<Editor>,
 7604    ) {
 7605        let mut revert_changes = HashMap::default();
 7606        let snapshot = self.buffer.read(cx).snapshot(cx);
 7607        let Some(project) = &self.project else {
 7608            return;
 7609        };
 7610
 7611        let chunk_by = self
 7612            .snapshot(window, cx)
 7613            .hunks_for_ranges(ranges.into_iter())
 7614            .into_iter()
 7615            .chunk_by(|hunk| hunk.buffer_id);
 7616        for (buffer_id, hunks) in &chunk_by {
 7617            let hunks = hunks.collect::<Vec<_>>();
 7618            for hunk in &hunks {
 7619                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7620            }
 7621            Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
 7622        }
 7623        drop(chunk_by);
 7624        if !revert_changes.is_empty() {
 7625            self.transact(window, cx, |editor, window, cx| {
 7626                editor.revert(revert_changes, window, cx);
 7627            });
 7628        }
 7629    }
 7630
 7631    pub fn open_active_item_in_terminal(
 7632        &mut self,
 7633        _: &OpenInTerminal,
 7634        window: &mut Window,
 7635        cx: &mut Context<Self>,
 7636    ) {
 7637        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7638            let project_path = buffer.read(cx).project_path(cx)?;
 7639            let project = self.project.as_ref()?.read(cx);
 7640            let entry = project.entry_for_path(&project_path, cx)?;
 7641            let parent = match &entry.canonical_path {
 7642                Some(canonical_path) => canonical_path.to_path_buf(),
 7643                None => project.absolute_path(&project_path, cx)?,
 7644            }
 7645            .parent()?
 7646            .to_path_buf();
 7647            Some(parent)
 7648        }) {
 7649            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7650        }
 7651    }
 7652
 7653    pub fn prepare_restore_change(
 7654        &self,
 7655        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7656        hunk: &MultiBufferDiffHunk,
 7657        cx: &mut App,
 7658    ) -> Option<()> {
 7659        let buffer = self.buffer.read(cx);
 7660        let diff = buffer.diff_for(hunk.buffer_id)?;
 7661        let buffer = buffer.buffer(hunk.buffer_id)?;
 7662        let buffer = buffer.read(cx);
 7663        let original_text = diff
 7664            .read(cx)
 7665            .base_text()
 7666            .as_ref()?
 7667            .as_rope()
 7668            .slice(hunk.diff_base_byte_range.clone());
 7669        let buffer_snapshot = buffer.snapshot();
 7670        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7671        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7672            probe
 7673                .0
 7674                .start
 7675                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7676                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7677        }) {
 7678            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7679            Some(())
 7680        } else {
 7681            None
 7682        }
 7683    }
 7684
 7685    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7686        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7687    }
 7688
 7689    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7690        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7691    }
 7692
 7693    fn manipulate_lines<Fn>(
 7694        &mut self,
 7695        window: &mut Window,
 7696        cx: &mut Context<Self>,
 7697        mut callback: Fn,
 7698    ) where
 7699        Fn: FnMut(&mut Vec<&str>),
 7700    {
 7701        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7702        let buffer = self.buffer.read(cx).snapshot(cx);
 7703
 7704        let mut edits = Vec::new();
 7705
 7706        let selections = self.selections.all::<Point>(cx);
 7707        let mut selections = selections.iter().peekable();
 7708        let mut contiguous_row_selections = Vec::new();
 7709        let mut new_selections = Vec::new();
 7710        let mut added_lines = 0;
 7711        let mut removed_lines = 0;
 7712
 7713        while let Some(selection) = selections.next() {
 7714            let (start_row, end_row) = consume_contiguous_rows(
 7715                &mut contiguous_row_selections,
 7716                selection,
 7717                &display_map,
 7718                &mut selections,
 7719            );
 7720
 7721            let start_point = Point::new(start_row.0, 0);
 7722            let end_point = Point::new(
 7723                end_row.previous_row().0,
 7724                buffer.line_len(end_row.previous_row()),
 7725            );
 7726            let text = buffer
 7727                .text_for_range(start_point..end_point)
 7728                .collect::<String>();
 7729
 7730            let mut lines = text.split('\n').collect_vec();
 7731
 7732            let lines_before = lines.len();
 7733            callback(&mut lines);
 7734            let lines_after = lines.len();
 7735
 7736            edits.push((start_point..end_point, lines.join("\n")));
 7737
 7738            // Selections must change based on added and removed line count
 7739            let start_row =
 7740                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7741            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7742            new_selections.push(Selection {
 7743                id: selection.id,
 7744                start: start_row,
 7745                end: end_row,
 7746                goal: SelectionGoal::None,
 7747                reversed: selection.reversed,
 7748            });
 7749
 7750            if lines_after > lines_before {
 7751                added_lines += lines_after - lines_before;
 7752            } else if lines_before > lines_after {
 7753                removed_lines += lines_before - lines_after;
 7754            }
 7755        }
 7756
 7757        self.transact(window, cx, |this, window, cx| {
 7758            let buffer = this.buffer.update(cx, |buffer, cx| {
 7759                buffer.edit(edits, None, cx);
 7760                buffer.snapshot(cx)
 7761            });
 7762
 7763            // Recalculate offsets on newly edited buffer
 7764            let new_selections = new_selections
 7765                .iter()
 7766                .map(|s| {
 7767                    let start_point = Point::new(s.start.0, 0);
 7768                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7769                    Selection {
 7770                        id: s.id,
 7771                        start: buffer.point_to_offset(start_point),
 7772                        end: buffer.point_to_offset(end_point),
 7773                        goal: s.goal,
 7774                        reversed: s.reversed,
 7775                    }
 7776                })
 7777                .collect();
 7778
 7779            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7780                s.select(new_selections);
 7781            });
 7782
 7783            this.request_autoscroll(Autoscroll::fit(), cx);
 7784        });
 7785    }
 7786
 7787    pub fn convert_to_upper_case(
 7788        &mut self,
 7789        _: &ConvertToUpperCase,
 7790        window: &mut Window,
 7791        cx: &mut Context<Self>,
 7792    ) {
 7793        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7794    }
 7795
 7796    pub fn convert_to_lower_case(
 7797        &mut self,
 7798        _: &ConvertToLowerCase,
 7799        window: &mut Window,
 7800        cx: &mut Context<Self>,
 7801    ) {
 7802        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7803    }
 7804
 7805    pub fn convert_to_title_case(
 7806        &mut self,
 7807        _: &ConvertToTitleCase,
 7808        window: &mut Window,
 7809        cx: &mut Context<Self>,
 7810    ) {
 7811        self.manipulate_text(window, cx, |text| {
 7812            text.split('\n')
 7813                .map(|line| line.to_case(Case::Title))
 7814                .join("\n")
 7815        })
 7816    }
 7817
 7818    pub fn convert_to_snake_case(
 7819        &mut self,
 7820        _: &ConvertToSnakeCase,
 7821        window: &mut Window,
 7822        cx: &mut Context<Self>,
 7823    ) {
 7824        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7825    }
 7826
 7827    pub fn convert_to_kebab_case(
 7828        &mut self,
 7829        _: &ConvertToKebabCase,
 7830        window: &mut Window,
 7831        cx: &mut Context<Self>,
 7832    ) {
 7833        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7834    }
 7835
 7836    pub fn convert_to_upper_camel_case(
 7837        &mut self,
 7838        _: &ConvertToUpperCamelCase,
 7839        window: &mut Window,
 7840        cx: &mut Context<Self>,
 7841    ) {
 7842        self.manipulate_text(window, cx, |text| {
 7843            text.split('\n')
 7844                .map(|line| line.to_case(Case::UpperCamel))
 7845                .join("\n")
 7846        })
 7847    }
 7848
 7849    pub fn convert_to_lower_camel_case(
 7850        &mut self,
 7851        _: &ConvertToLowerCamelCase,
 7852        window: &mut Window,
 7853        cx: &mut Context<Self>,
 7854    ) {
 7855        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7856    }
 7857
 7858    pub fn convert_to_opposite_case(
 7859        &mut self,
 7860        _: &ConvertToOppositeCase,
 7861        window: &mut Window,
 7862        cx: &mut Context<Self>,
 7863    ) {
 7864        self.manipulate_text(window, cx, |text| {
 7865            text.chars()
 7866                .fold(String::with_capacity(text.len()), |mut t, c| {
 7867                    if c.is_uppercase() {
 7868                        t.extend(c.to_lowercase());
 7869                    } else {
 7870                        t.extend(c.to_uppercase());
 7871                    }
 7872                    t
 7873                })
 7874        })
 7875    }
 7876
 7877    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7878    where
 7879        Fn: FnMut(&str) -> String,
 7880    {
 7881        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7882        let buffer = self.buffer.read(cx).snapshot(cx);
 7883
 7884        let mut new_selections = Vec::new();
 7885        let mut edits = Vec::new();
 7886        let mut selection_adjustment = 0i32;
 7887
 7888        for selection in self.selections.all::<usize>(cx) {
 7889            let selection_is_empty = selection.is_empty();
 7890
 7891            let (start, end) = if selection_is_empty {
 7892                let word_range = movement::surrounding_word(
 7893                    &display_map,
 7894                    selection.start.to_display_point(&display_map),
 7895                );
 7896                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7897                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7898                (start, end)
 7899            } else {
 7900                (selection.start, selection.end)
 7901            };
 7902
 7903            let text = buffer.text_for_range(start..end).collect::<String>();
 7904            let old_length = text.len() as i32;
 7905            let text = callback(&text);
 7906
 7907            new_selections.push(Selection {
 7908                start: (start as i32 - selection_adjustment) as usize,
 7909                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7910                goal: SelectionGoal::None,
 7911                ..selection
 7912            });
 7913
 7914            selection_adjustment += old_length - text.len() as i32;
 7915
 7916            edits.push((start..end, text));
 7917        }
 7918
 7919        self.transact(window, cx, |this, window, cx| {
 7920            this.buffer.update(cx, |buffer, cx| {
 7921                buffer.edit(edits, None, cx);
 7922            });
 7923
 7924            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7925                s.select(new_selections);
 7926            });
 7927
 7928            this.request_autoscroll(Autoscroll::fit(), cx);
 7929        });
 7930    }
 7931
 7932    pub fn duplicate(
 7933        &mut self,
 7934        upwards: bool,
 7935        whole_lines: bool,
 7936        window: &mut Window,
 7937        cx: &mut Context<Self>,
 7938    ) {
 7939        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7940        let buffer = &display_map.buffer_snapshot;
 7941        let selections = self.selections.all::<Point>(cx);
 7942
 7943        let mut edits = Vec::new();
 7944        let mut selections_iter = selections.iter().peekable();
 7945        while let Some(selection) = selections_iter.next() {
 7946            let mut rows = selection.spanned_rows(false, &display_map);
 7947            // duplicate line-wise
 7948            if whole_lines || selection.start == selection.end {
 7949                // Avoid duplicating the same lines twice.
 7950                while let Some(next_selection) = selections_iter.peek() {
 7951                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7952                    if next_rows.start < rows.end {
 7953                        rows.end = next_rows.end;
 7954                        selections_iter.next().unwrap();
 7955                    } else {
 7956                        break;
 7957                    }
 7958                }
 7959
 7960                // Copy the text from the selected row region and splice it either at the start
 7961                // or end of the region.
 7962                let start = Point::new(rows.start.0, 0);
 7963                let end = Point::new(
 7964                    rows.end.previous_row().0,
 7965                    buffer.line_len(rows.end.previous_row()),
 7966                );
 7967                let text = buffer
 7968                    .text_for_range(start..end)
 7969                    .chain(Some("\n"))
 7970                    .collect::<String>();
 7971                let insert_location = if upwards {
 7972                    Point::new(rows.end.0, 0)
 7973                } else {
 7974                    start
 7975                };
 7976                edits.push((insert_location..insert_location, text));
 7977            } else {
 7978                // duplicate character-wise
 7979                let start = selection.start;
 7980                let end = selection.end;
 7981                let text = buffer.text_for_range(start..end).collect::<String>();
 7982                edits.push((selection.end..selection.end, text));
 7983            }
 7984        }
 7985
 7986        self.transact(window, cx, |this, _, cx| {
 7987            this.buffer.update(cx, |buffer, cx| {
 7988                buffer.edit(edits, None, cx);
 7989            });
 7990
 7991            this.request_autoscroll(Autoscroll::fit(), cx);
 7992        });
 7993    }
 7994
 7995    pub fn duplicate_line_up(
 7996        &mut self,
 7997        _: &DuplicateLineUp,
 7998        window: &mut Window,
 7999        cx: &mut Context<Self>,
 8000    ) {
 8001        self.duplicate(true, true, window, cx);
 8002    }
 8003
 8004    pub fn duplicate_line_down(
 8005        &mut self,
 8006        _: &DuplicateLineDown,
 8007        window: &mut Window,
 8008        cx: &mut Context<Self>,
 8009    ) {
 8010        self.duplicate(false, true, window, cx);
 8011    }
 8012
 8013    pub fn duplicate_selection(
 8014        &mut self,
 8015        _: &DuplicateSelection,
 8016        window: &mut Window,
 8017        cx: &mut Context<Self>,
 8018    ) {
 8019        self.duplicate(false, false, window, cx);
 8020    }
 8021
 8022    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8023        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8024        let buffer = self.buffer.read(cx).snapshot(cx);
 8025
 8026        let mut edits = Vec::new();
 8027        let mut unfold_ranges = Vec::new();
 8028        let mut refold_creases = Vec::new();
 8029
 8030        let selections = self.selections.all::<Point>(cx);
 8031        let mut selections = selections.iter().peekable();
 8032        let mut contiguous_row_selections = Vec::new();
 8033        let mut new_selections = Vec::new();
 8034
 8035        while let Some(selection) = selections.next() {
 8036            // Find all the selections that span a contiguous row range
 8037            let (start_row, end_row) = consume_contiguous_rows(
 8038                &mut contiguous_row_selections,
 8039                selection,
 8040                &display_map,
 8041                &mut selections,
 8042            );
 8043
 8044            // Move the text spanned by the row range to be before the line preceding the row range
 8045            if start_row.0 > 0 {
 8046                let range_to_move = Point::new(
 8047                    start_row.previous_row().0,
 8048                    buffer.line_len(start_row.previous_row()),
 8049                )
 8050                    ..Point::new(
 8051                        end_row.previous_row().0,
 8052                        buffer.line_len(end_row.previous_row()),
 8053                    );
 8054                let insertion_point = display_map
 8055                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8056                    .0;
 8057
 8058                // Don't move lines across excerpts
 8059                if buffer
 8060                    .excerpt_containing(insertion_point..range_to_move.end)
 8061                    .is_some()
 8062                {
 8063                    let text = buffer
 8064                        .text_for_range(range_to_move.clone())
 8065                        .flat_map(|s| s.chars())
 8066                        .skip(1)
 8067                        .chain(['\n'])
 8068                        .collect::<String>();
 8069
 8070                    edits.push((
 8071                        buffer.anchor_after(range_to_move.start)
 8072                            ..buffer.anchor_before(range_to_move.end),
 8073                        String::new(),
 8074                    ));
 8075                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8076                    edits.push((insertion_anchor..insertion_anchor, text));
 8077
 8078                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8079
 8080                    // Move selections up
 8081                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8082                        |mut selection| {
 8083                            selection.start.row -= row_delta;
 8084                            selection.end.row -= row_delta;
 8085                            selection
 8086                        },
 8087                    ));
 8088
 8089                    // Move folds up
 8090                    unfold_ranges.push(range_to_move.clone());
 8091                    for fold in display_map.folds_in_range(
 8092                        buffer.anchor_before(range_to_move.start)
 8093                            ..buffer.anchor_after(range_to_move.end),
 8094                    ) {
 8095                        let mut start = fold.range.start.to_point(&buffer);
 8096                        let mut end = fold.range.end.to_point(&buffer);
 8097                        start.row -= row_delta;
 8098                        end.row -= row_delta;
 8099                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8100                    }
 8101                }
 8102            }
 8103
 8104            // If we didn't move line(s), preserve the existing selections
 8105            new_selections.append(&mut contiguous_row_selections);
 8106        }
 8107
 8108        self.transact(window, cx, |this, window, cx| {
 8109            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8110            this.buffer.update(cx, |buffer, cx| {
 8111                for (range, text) in edits {
 8112                    buffer.edit([(range, text)], None, cx);
 8113                }
 8114            });
 8115            this.fold_creases(refold_creases, true, window, cx);
 8116            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8117                s.select(new_selections);
 8118            })
 8119        });
 8120    }
 8121
 8122    pub fn move_line_down(
 8123        &mut self,
 8124        _: &MoveLineDown,
 8125        window: &mut Window,
 8126        cx: &mut Context<Self>,
 8127    ) {
 8128        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8129        let buffer = self.buffer.read(cx).snapshot(cx);
 8130
 8131        let mut edits = Vec::new();
 8132        let mut unfold_ranges = Vec::new();
 8133        let mut refold_creases = Vec::new();
 8134
 8135        let selections = self.selections.all::<Point>(cx);
 8136        let mut selections = selections.iter().peekable();
 8137        let mut contiguous_row_selections = Vec::new();
 8138        let mut new_selections = Vec::new();
 8139
 8140        while let Some(selection) = selections.next() {
 8141            // Find all the selections that span a contiguous row range
 8142            let (start_row, end_row) = consume_contiguous_rows(
 8143                &mut contiguous_row_selections,
 8144                selection,
 8145                &display_map,
 8146                &mut selections,
 8147            );
 8148
 8149            // Move the text spanned by the row range to be after the last line of the row range
 8150            if end_row.0 <= buffer.max_point().row {
 8151                let range_to_move =
 8152                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8153                let insertion_point = display_map
 8154                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8155                    .0;
 8156
 8157                // Don't move lines across excerpt boundaries
 8158                if buffer
 8159                    .excerpt_containing(range_to_move.start..insertion_point)
 8160                    .is_some()
 8161                {
 8162                    let mut text = String::from("\n");
 8163                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8164                    text.pop(); // Drop trailing newline
 8165                    edits.push((
 8166                        buffer.anchor_after(range_to_move.start)
 8167                            ..buffer.anchor_before(range_to_move.end),
 8168                        String::new(),
 8169                    ));
 8170                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8171                    edits.push((insertion_anchor..insertion_anchor, text));
 8172
 8173                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8174
 8175                    // Move selections down
 8176                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8177                        |mut selection| {
 8178                            selection.start.row += row_delta;
 8179                            selection.end.row += row_delta;
 8180                            selection
 8181                        },
 8182                    ));
 8183
 8184                    // Move folds down
 8185                    unfold_ranges.push(range_to_move.clone());
 8186                    for fold in display_map.folds_in_range(
 8187                        buffer.anchor_before(range_to_move.start)
 8188                            ..buffer.anchor_after(range_to_move.end),
 8189                    ) {
 8190                        let mut start = fold.range.start.to_point(&buffer);
 8191                        let mut end = fold.range.end.to_point(&buffer);
 8192                        start.row += row_delta;
 8193                        end.row += row_delta;
 8194                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8195                    }
 8196                }
 8197            }
 8198
 8199            // If we didn't move line(s), preserve the existing selections
 8200            new_selections.append(&mut contiguous_row_selections);
 8201        }
 8202
 8203        self.transact(window, cx, |this, window, cx| {
 8204            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8205            this.buffer.update(cx, |buffer, cx| {
 8206                for (range, text) in edits {
 8207                    buffer.edit([(range, text)], None, cx);
 8208                }
 8209            });
 8210            this.fold_creases(refold_creases, true, window, cx);
 8211            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8212                s.select(new_selections)
 8213            });
 8214        });
 8215    }
 8216
 8217    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8218        let text_layout_details = &self.text_layout_details(window);
 8219        self.transact(window, cx, |this, window, cx| {
 8220            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8221                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8222                let line_mode = s.line_mode;
 8223                s.move_with(|display_map, selection| {
 8224                    if !selection.is_empty() || line_mode {
 8225                        return;
 8226                    }
 8227
 8228                    let mut head = selection.head();
 8229                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8230                    if head.column() == display_map.line_len(head.row()) {
 8231                        transpose_offset = display_map
 8232                            .buffer_snapshot
 8233                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8234                    }
 8235
 8236                    if transpose_offset == 0 {
 8237                        return;
 8238                    }
 8239
 8240                    *head.column_mut() += 1;
 8241                    head = display_map.clip_point(head, Bias::Right);
 8242                    let goal = SelectionGoal::HorizontalPosition(
 8243                        display_map
 8244                            .x_for_display_point(head, text_layout_details)
 8245                            .into(),
 8246                    );
 8247                    selection.collapse_to(head, goal);
 8248
 8249                    let transpose_start = display_map
 8250                        .buffer_snapshot
 8251                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8252                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8253                        let transpose_end = display_map
 8254                            .buffer_snapshot
 8255                            .clip_offset(transpose_offset + 1, Bias::Right);
 8256                        if let Some(ch) =
 8257                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8258                        {
 8259                            edits.push((transpose_start..transpose_offset, String::new()));
 8260                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8261                        }
 8262                    }
 8263                });
 8264                edits
 8265            });
 8266            this.buffer
 8267                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8268            let selections = this.selections.all::<usize>(cx);
 8269            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8270                s.select(selections);
 8271            });
 8272        });
 8273    }
 8274
 8275    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8276        self.rewrap_impl(IsVimMode::No, cx)
 8277    }
 8278
 8279    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8280        let buffer = self.buffer.read(cx).snapshot(cx);
 8281        let selections = self.selections.all::<Point>(cx);
 8282        let mut selections = selections.iter().peekable();
 8283
 8284        let mut edits = Vec::new();
 8285        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8286
 8287        while let Some(selection) = selections.next() {
 8288            let mut start_row = selection.start.row;
 8289            let mut end_row = selection.end.row;
 8290
 8291            // Skip selections that overlap with a range that has already been rewrapped.
 8292            let selection_range = start_row..end_row;
 8293            if rewrapped_row_ranges
 8294                .iter()
 8295                .any(|range| range.overlaps(&selection_range))
 8296            {
 8297                continue;
 8298            }
 8299
 8300            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 8301
 8302            // Since not all lines in the selection may be at the same indent
 8303            // level, choose the indent size that is the most common between all
 8304            // of the lines.
 8305            //
 8306            // If there is a tie, we use the deepest indent.
 8307            let (indent_size, indent_end) = {
 8308                let mut indent_size_occurrences = HashMap::default();
 8309                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8310
 8311                for row in start_row..=end_row {
 8312                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8313                    rows_by_indent_size.entry(indent).or_default().push(row);
 8314                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8315                }
 8316
 8317                let indent_size = indent_size_occurrences
 8318                    .into_iter()
 8319                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8320                    .map(|(indent, _)| indent)
 8321                    .unwrap_or_default();
 8322                let row = rows_by_indent_size[&indent_size][0];
 8323                let indent_end = Point::new(row, indent_size.len);
 8324
 8325                (indent_size, indent_end)
 8326            };
 8327
 8328            let mut line_prefix = indent_size.chars().collect::<String>();
 8329
 8330            let mut inside_comment = false;
 8331            if let Some(comment_prefix) =
 8332                buffer
 8333                    .language_scope_at(selection.head())
 8334                    .and_then(|language| {
 8335                        language
 8336                            .line_comment_prefixes()
 8337                            .iter()
 8338                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8339                            .cloned()
 8340                    })
 8341            {
 8342                line_prefix.push_str(&comment_prefix);
 8343                inside_comment = true;
 8344            }
 8345
 8346            let language_settings = buffer.settings_at(selection.head(), cx);
 8347            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8348                RewrapBehavior::InComments => inside_comment,
 8349                RewrapBehavior::InSelections => !selection.is_empty(),
 8350                RewrapBehavior::Anywhere => true,
 8351            };
 8352
 8353            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8354            if !should_rewrap {
 8355                continue;
 8356            }
 8357
 8358            if selection.is_empty() {
 8359                'expand_upwards: while start_row > 0 {
 8360                    let prev_row = start_row - 1;
 8361                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8362                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8363                    {
 8364                        start_row = prev_row;
 8365                    } else {
 8366                        break 'expand_upwards;
 8367                    }
 8368                }
 8369
 8370                'expand_downwards: while end_row < buffer.max_point().row {
 8371                    let next_row = end_row + 1;
 8372                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8373                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8374                    {
 8375                        end_row = next_row;
 8376                    } else {
 8377                        break 'expand_downwards;
 8378                    }
 8379                }
 8380            }
 8381
 8382            let start = Point::new(start_row, 0);
 8383            let start_offset = start.to_offset(&buffer);
 8384            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8385            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8386            let Some(lines_without_prefixes) = selection_text
 8387                .lines()
 8388                .map(|line| {
 8389                    line.strip_prefix(&line_prefix)
 8390                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8391                        .ok_or_else(|| {
 8392                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8393                        })
 8394                })
 8395                .collect::<Result<Vec<_>, _>>()
 8396                .log_err()
 8397            else {
 8398                continue;
 8399            };
 8400
 8401            let wrap_column = buffer
 8402                .settings_at(Point::new(start_row, 0), cx)
 8403                .preferred_line_length as usize;
 8404            let wrapped_text = wrap_with_prefix(
 8405                line_prefix,
 8406                lines_without_prefixes.join(" "),
 8407                wrap_column,
 8408                tab_size,
 8409            );
 8410
 8411            // TODO: should always use char-based diff while still supporting cursor behavior that
 8412            // matches vim.
 8413            let mut diff_options = DiffOptions::default();
 8414            if is_vim_mode == IsVimMode::Yes {
 8415                diff_options.max_word_diff_len = 0;
 8416                diff_options.max_word_diff_line_count = 0;
 8417            } else {
 8418                diff_options.max_word_diff_len = usize::MAX;
 8419                diff_options.max_word_diff_line_count = usize::MAX;
 8420            }
 8421
 8422            for (old_range, new_text) in
 8423                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8424            {
 8425                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8426                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8427                edits.push((edit_start..edit_end, new_text));
 8428            }
 8429
 8430            rewrapped_row_ranges.push(start_row..=end_row);
 8431        }
 8432
 8433        self.buffer
 8434            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8435    }
 8436
 8437    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8438        let mut text = String::new();
 8439        let buffer = self.buffer.read(cx).snapshot(cx);
 8440        let mut selections = self.selections.all::<Point>(cx);
 8441        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8442        {
 8443            let max_point = buffer.max_point();
 8444            let mut is_first = true;
 8445            for selection in &mut selections {
 8446                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8447                if is_entire_line {
 8448                    selection.start = Point::new(selection.start.row, 0);
 8449                    if !selection.is_empty() && selection.end.column == 0 {
 8450                        selection.end = cmp::min(max_point, selection.end);
 8451                    } else {
 8452                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8453                    }
 8454                    selection.goal = SelectionGoal::None;
 8455                }
 8456                if is_first {
 8457                    is_first = false;
 8458                } else {
 8459                    text += "\n";
 8460                }
 8461                let mut len = 0;
 8462                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8463                    text.push_str(chunk);
 8464                    len += chunk.len();
 8465                }
 8466                clipboard_selections.push(ClipboardSelection {
 8467                    len,
 8468                    is_entire_line,
 8469                    start_column: selection.start.column,
 8470                });
 8471            }
 8472        }
 8473
 8474        self.transact(window, cx, |this, window, cx| {
 8475            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8476                s.select(selections);
 8477            });
 8478            this.insert("", window, cx);
 8479        });
 8480        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8481    }
 8482
 8483    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8484        let item = self.cut_common(window, cx);
 8485        cx.write_to_clipboard(item);
 8486    }
 8487
 8488    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8489        self.change_selections(None, window, cx, |s| {
 8490            s.move_with(|snapshot, sel| {
 8491                if sel.is_empty() {
 8492                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8493                }
 8494            });
 8495        });
 8496        let item = self.cut_common(window, cx);
 8497        cx.set_global(KillRing(item))
 8498    }
 8499
 8500    pub fn kill_ring_yank(
 8501        &mut self,
 8502        _: &KillRingYank,
 8503        window: &mut Window,
 8504        cx: &mut Context<Self>,
 8505    ) {
 8506        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8507            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8508                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8509            } else {
 8510                return;
 8511            }
 8512        } else {
 8513            return;
 8514        };
 8515        self.do_paste(&text, metadata, false, window, cx);
 8516    }
 8517
 8518    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8519        let selections = self.selections.all::<Point>(cx);
 8520        let buffer = self.buffer.read(cx).read(cx);
 8521        let mut text = String::new();
 8522
 8523        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8524        {
 8525            let max_point = buffer.max_point();
 8526            let mut is_first = true;
 8527            for selection in selections.iter() {
 8528                let mut start = selection.start;
 8529                let mut end = selection.end;
 8530                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8531                if is_entire_line {
 8532                    start = Point::new(start.row, 0);
 8533                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8534                }
 8535                if is_first {
 8536                    is_first = false;
 8537                } else {
 8538                    text += "\n";
 8539                }
 8540                let mut len = 0;
 8541                for chunk in buffer.text_for_range(start..end) {
 8542                    text.push_str(chunk);
 8543                    len += chunk.len();
 8544                }
 8545                clipboard_selections.push(ClipboardSelection {
 8546                    len,
 8547                    is_entire_line,
 8548                    start_column: start.column,
 8549                });
 8550            }
 8551        }
 8552
 8553        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8554            text,
 8555            clipboard_selections,
 8556        ));
 8557    }
 8558
 8559    pub fn do_paste(
 8560        &mut self,
 8561        text: &String,
 8562        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8563        handle_entire_lines: bool,
 8564        window: &mut Window,
 8565        cx: &mut Context<Self>,
 8566    ) {
 8567        if self.read_only(cx) {
 8568            return;
 8569        }
 8570
 8571        let clipboard_text = Cow::Borrowed(text);
 8572
 8573        self.transact(window, cx, |this, window, cx| {
 8574            if let Some(mut clipboard_selections) = clipboard_selections {
 8575                let old_selections = this.selections.all::<usize>(cx);
 8576                let all_selections_were_entire_line =
 8577                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8578                let first_selection_start_column =
 8579                    clipboard_selections.first().map(|s| s.start_column);
 8580                if clipboard_selections.len() != old_selections.len() {
 8581                    clipboard_selections.drain(..);
 8582                }
 8583                let cursor_offset = this.selections.last::<usize>(cx).head();
 8584                let mut auto_indent_on_paste = true;
 8585
 8586                this.buffer.update(cx, |buffer, cx| {
 8587                    let snapshot = buffer.read(cx);
 8588                    auto_indent_on_paste =
 8589                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8590
 8591                    let mut start_offset = 0;
 8592                    let mut edits = Vec::new();
 8593                    let mut original_start_columns = Vec::new();
 8594                    for (ix, selection) in old_selections.iter().enumerate() {
 8595                        let to_insert;
 8596                        let entire_line;
 8597                        let original_start_column;
 8598                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8599                            let end_offset = start_offset + clipboard_selection.len;
 8600                            to_insert = &clipboard_text[start_offset..end_offset];
 8601                            entire_line = clipboard_selection.is_entire_line;
 8602                            start_offset = end_offset + 1;
 8603                            original_start_column = Some(clipboard_selection.start_column);
 8604                        } else {
 8605                            to_insert = clipboard_text.as_str();
 8606                            entire_line = all_selections_were_entire_line;
 8607                            original_start_column = first_selection_start_column
 8608                        }
 8609
 8610                        // If the corresponding selection was empty when this slice of the
 8611                        // clipboard text was written, then the entire line containing the
 8612                        // selection was copied. If this selection is also currently empty,
 8613                        // then paste the line before the current line of the buffer.
 8614                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8615                            let column = selection.start.to_point(&snapshot).column as usize;
 8616                            let line_start = selection.start - column;
 8617                            line_start..line_start
 8618                        } else {
 8619                            selection.range()
 8620                        };
 8621
 8622                        edits.push((range, to_insert));
 8623                        original_start_columns.extend(original_start_column);
 8624                    }
 8625                    drop(snapshot);
 8626
 8627                    buffer.edit(
 8628                        edits,
 8629                        if auto_indent_on_paste {
 8630                            Some(AutoindentMode::Block {
 8631                                original_start_columns,
 8632                            })
 8633                        } else {
 8634                            None
 8635                        },
 8636                        cx,
 8637                    );
 8638                });
 8639
 8640                let selections = this.selections.all::<usize>(cx);
 8641                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8642                    s.select(selections)
 8643                });
 8644            } else {
 8645                this.insert(&clipboard_text, window, cx);
 8646            }
 8647        });
 8648    }
 8649
 8650    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8651        if let Some(item) = cx.read_from_clipboard() {
 8652            let entries = item.entries();
 8653
 8654            match entries.first() {
 8655                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8656                // of all the pasted entries.
 8657                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8658                    .do_paste(
 8659                        clipboard_string.text(),
 8660                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8661                        true,
 8662                        window,
 8663                        cx,
 8664                    ),
 8665                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8666            }
 8667        }
 8668    }
 8669
 8670    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8671        if self.read_only(cx) {
 8672            return;
 8673        }
 8674
 8675        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8676            if let Some((selections, _)) =
 8677                self.selection_history.transaction(transaction_id).cloned()
 8678            {
 8679                self.change_selections(None, window, cx, |s| {
 8680                    s.select_anchors(selections.to_vec());
 8681                });
 8682            }
 8683            self.request_autoscroll(Autoscroll::fit(), cx);
 8684            self.unmark_text(window, cx);
 8685            self.refresh_inline_completion(true, false, window, cx);
 8686            cx.emit(EditorEvent::Edited { transaction_id });
 8687            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8688        }
 8689    }
 8690
 8691    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8692        if self.read_only(cx) {
 8693            return;
 8694        }
 8695
 8696        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8697            if let Some((_, Some(selections))) =
 8698                self.selection_history.transaction(transaction_id).cloned()
 8699            {
 8700                self.change_selections(None, window, cx, |s| {
 8701                    s.select_anchors(selections.to_vec());
 8702                });
 8703            }
 8704            self.request_autoscroll(Autoscroll::fit(), cx);
 8705            self.unmark_text(window, cx);
 8706            self.refresh_inline_completion(true, false, window, cx);
 8707            cx.emit(EditorEvent::Edited { transaction_id });
 8708        }
 8709    }
 8710
 8711    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8712        self.buffer
 8713            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8714    }
 8715
 8716    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8717        self.buffer
 8718            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8719    }
 8720
 8721    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8722        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8723            let line_mode = s.line_mode;
 8724            s.move_with(|map, selection| {
 8725                let cursor = if selection.is_empty() && !line_mode {
 8726                    movement::left(map, selection.start)
 8727                } else {
 8728                    selection.start
 8729                };
 8730                selection.collapse_to(cursor, SelectionGoal::None);
 8731            });
 8732        })
 8733    }
 8734
 8735    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8736        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8737            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8738        })
 8739    }
 8740
 8741    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8742        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8743            let line_mode = s.line_mode;
 8744            s.move_with(|map, selection| {
 8745                let cursor = if selection.is_empty() && !line_mode {
 8746                    movement::right(map, selection.end)
 8747                } else {
 8748                    selection.end
 8749                };
 8750                selection.collapse_to(cursor, SelectionGoal::None)
 8751            });
 8752        })
 8753    }
 8754
 8755    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8756        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8757            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8758        })
 8759    }
 8760
 8761    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8762        if self.take_rename(true, window, cx).is_some() {
 8763            return;
 8764        }
 8765
 8766        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8767            cx.propagate();
 8768            return;
 8769        }
 8770
 8771        let text_layout_details = &self.text_layout_details(window);
 8772        let selection_count = self.selections.count();
 8773        let first_selection = self.selections.first_anchor();
 8774
 8775        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8776            let line_mode = s.line_mode;
 8777            s.move_with(|map, selection| {
 8778                if !selection.is_empty() && !line_mode {
 8779                    selection.goal = SelectionGoal::None;
 8780                }
 8781                let (cursor, goal) = movement::up(
 8782                    map,
 8783                    selection.start,
 8784                    selection.goal,
 8785                    false,
 8786                    text_layout_details,
 8787                );
 8788                selection.collapse_to(cursor, goal);
 8789            });
 8790        });
 8791
 8792        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8793        {
 8794            cx.propagate();
 8795        }
 8796    }
 8797
 8798    pub fn move_up_by_lines(
 8799        &mut self,
 8800        action: &MoveUpByLines,
 8801        window: &mut Window,
 8802        cx: &mut Context<Self>,
 8803    ) {
 8804        if self.take_rename(true, window, cx).is_some() {
 8805            return;
 8806        }
 8807
 8808        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8809            cx.propagate();
 8810            return;
 8811        }
 8812
 8813        let text_layout_details = &self.text_layout_details(window);
 8814
 8815        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8816            let line_mode = s.line_mode;
 8817            s.move_with(|map, selection| {
 8818                if !selection.is_empty() && !line_mode {
 8819                    selection.goal = SelectionGoal::None;
 8820                }
 8821                let (cursor, goal) = movement::up_by_rows(
 8822                    map,
 8823                    selection.start,
 8824                    action.lines,
 8825                    selection.goal,
 8826                    false,
 8827                    text_layout_details,
 8828                );
 8829                selection.collapse_to(cursor, goal);
 8830            });
 8831        })
 8832    }
 8833
 8834    pub fn move_down_by_lines(
 8835        &mut self,
 8836        action: &MoveDownByLines,
 8837        window: &mut Window,
 8838        cx: &mut Context<Self>,
 8839    ) {
 8840        if self.take_rename(true, window, cx).is_some() {
 8841            return;
 8842        }
 8843
 8844        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8845            cx.propagate();
 8846            return;
 8847        }
 8848
 8849        let text_layout_details = &self.text_layout_details(window);
 8850
 8851        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8852            let line_mode = s.line_mode;
 8853            s.move_with(|map, selection| {
 8854                if !selection.is_empty() && !line_mode {
 8855                    selection.goal = SelectionGoal::None;
 8856                }
 8857                let (cursor, goal) = movement::down_by_rows(
 8858                    map,
 8859                    selection.start,
 8860                    action.lines,
 8861                    selection.goal,
 8862                    false,
 8863                    text_layout_details,
 8864                );
 8865                selection.collapse_to(cursor, goal);
 8866            });
 8867        })
 8868    }
 8869
 8870    pub fn select_down_by_lines(
 8871        &mut self,
 8872        action: &SelectDownByLines,
 8873        window: &mut Window,
 8874        cx: &mut Context<Self>,
 8875    ) {
 8876        let text_layout_details = &self.text_layout_details(window);
 8877        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8878            s.move_heads_with(|map, head, goal| {
 8879                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8880            })
 8881        })
 8882    }
 8883
 8884    pub fn select_up_by_lines(
 8885        &mut self,
 8886        action: &SelectUpByLines,
 8887        window: &mut Window,
 8888        cx: &mut Context<Self>,
 8889    ) {
 8890        let text_layout_details = &self.text_layout_details(window);
 8891        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8892            s.move_heads_with(|map, head, goal| {
 8893                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8894            })
 8895        })
 8896    }
 8897
 8898    pub fn select_page_up(
 8899        &mut self,
 8900        _: &SelectPageUp,
 8901        window: &mut Window,
 8902        cx: &mut Context<Self>,
 8903    ) {
 8904        let Some(row_count) = self.visible_row_count() else {
 8905            return;
 8906        };
 8907
 8908        let text_layout_details = &self.text_layout_details(window);
 8909
 8910        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8911            s.move_heads_with(|map, head, goal| {
 8912                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8913            })
 8914        })
 8915    }
 8916
 8917    pub fn move_page_up(
 8918        &mut self,
 8919        action: &MovePageUp,
 8920        window: &mut Window,
 8921        cx: &mut Context<Self>,
 8922    ) {
 8923        if self.take_rename(true, window, cx).is_some() {
 8924            return;
 8925        }
 8926
 8927        if self
 8928            .context_menu
 8929            .borrow_mut()
 8930            .as_mut()
 8931            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8932            .unwrap_or(false)
 8933        {
 8934            return;
 8935        }
 8936
 8937        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8938            cx.propagate();
 8939            return;
 8940        }
 8941
 8942        let Some(row_count) = self.visible_row_count() else {
 8943            return;
 8944        };
 8945
 8946        let autoscroll = if action.center_cursor {
 8947            Autoscroll::center()
 8948        } else {
 8949            Autoscroll::fit()
 8950        };
 8951
 8952        let text_layout_details = &self.text_layout_details(window);
 8953
 8954        self.change_selections(Some(autoscroll), window, cx, |s| {
 8955            let line_mode = s.line_mode;
 8956            s.move_with(|map, selection| {
 8957                if !selection.is_empty() && !line_mode {
 8958                    selection.goal = SelectionGoal::None;
 8959                }
 8960                let (cursor, goal) = movement::up_by_rows(
 8961                    map,
 8962                    selection.end,
 8963                    row_count,
 8964                    selection.goal,
 8965                    false,
 8966                    text_layout_details,
 8967                );
 8968                selection.collapse_to(cursor, goal);
 8969            });
 8970        });
 8971    }
 8972
 8973    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8974        let text_layout_details = &self.text_layout_details(window);
 8975        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8976            s.move_heads_with(|map, head, goal| {
 8977                movement::up(map, head, goal, false, text_layout_details)
 8978            })
 8979        })
 8980    }
 8981
 8982    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8983        self.take_rename(true, window, cx);
 8984
 8985        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8986            cx.propagate();
 8987            return;
 8988        }
 8989
 8990        let text_layout_details = &self.text_layout_details(window);
 8991        let selection_count = self.selections.count();
 8992        let first_selection = self.selections.first_anchor();
 8993
 8994        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8995            let line_mode = s.line_mode;
 8996            s.move_with(|map, selection| {
 8997                if !selection.is_empty() && !line_mode {
 8998                    selection.goal = SelectionGoal::None;
 8999                }
 9000                let (cursor, goal) = movement::down(
 9001                    map,
 9002                    selection.end,
 9003                    selection.goal,
 9004                    false,
 9005                    text_layout_details,
 9006                );
 9007                selection.collapse_to(cursor, goal);
 9008            });
 9009        });
 9010
 9011        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9012        {
 9013            cx.propagate();
 9014        }
 9015    }
 9016
 9017    pub fn select_page_down(
 9018        &mut self,
 9019        _: &SelectPageDown,
 9020        window: &mut Window,
 9021        cx: &mut Context<Self>,
 9022    ) {
 9023        let Some(row_count) = self.visible_row_count() else {
 9024            return;
 9025        };
 9026
 9027        let text_layout_details = &self.text_layout_details(window);
 9028
 9029        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9030            s.move_heads_with(|map, head, goal| {
 9031                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9032            })
 9033        })
 9034    }
 9035
 9036    pub fn move_page_down(
 9037        &mut self,
 9038        action: &MovePageDown,
 9039        window: &mut Window,
 9040        cx: &mut Context<Self>,
 9041    ) {
 9042        if self.take_rename(true, window, cx).is_some() {
 9043            return;
 9044        }
 9045
 9046        if self
 9047            .context_menu
 9048            .borrow_mut()
 9049            .as_mut()
 9050            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9051            .unwrap_or(false)
 9052        {
 9053            return;
 9054        }
 9055
 9056        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9057            cx.propagate();
 9058            return;
 9059        }
 9060
 9061        let Some(row_count) = self.visible_row_count() else {
 9062            return;
 9063        };
 9064
 9065        let autoscroll = if action.center_cursor {
 9066            Autoscroll::center()
 9067        } else {
 9068            Autoscroll::fit()
 9069        };
 9070
 9071        let text_layout_details = &self.text_layout_details(window);
 9072        self.change_selections(Some(autoscroll), window, cx, |s| {
 9073            let line_mode = s.line_mode;
 9074            s.move_with(|map, selection| {
 9075                if !selection.is_empty() && !line_mode {
 9076                    selection.goal = SelectionGoal::None;
 9077                }
 9078                let (cursor, goal) = movement::down_by_rows(
 9079                    map,
 9080                    selection.end,
 9081                    row_count,
 9082                    selection.goal,
 9083                    false,
 9084                    text_layout_details,
 9085                );
 9086                selection.collapse_to(cursor, goal);
 9087            });
 9088        });
 9089    }
 9090
 9091    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9092        let text_layout_details = &self.text_layout_details(window);
 9093        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9094            s.move_heads_with(|map, head, goal| {
 9095                movement::down(map, head, goal, false, text_layout_details)
 9096            })
 9097        });
 9098    }
 9099
 9100    pub fn context_menu_first(
 9101        &mut self,
 9102        _: &ContextMenuFirst,
 9103        _window: &mut Window,
 9104        cx: &mut Context<Self>,
 9105    ) {
 9106        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9107            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9108        }
 9109    }
 9110
 9111    pub fn context_menu_prev(
 9112        &mut self,
 9113        _: &ContextMenuPrev,
 9114        _window: &mut Window,
 9115        cx: &mut Context<Self>,
 9116    ) {
 9117        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9118            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9119        }
 9120    }
 9121
 9122    pub fn context_menu_next(
 9123        &mut self,
 9124        _: &ContextMenuNext,
 9125        _window: &mut Window,
 9126        cx: &mut Context<Self>,
 9127    ) {
 9128        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9129            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9130        }
 9131    }
 9132
 9133    pub fn context_menu_last(
 9134        &mut self,
 9135        _: &ContextMenuLast,
 9136        _window: &mut Window,
 9137        cx: &mut Context<Self>,
 9138    ) {
 9139        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9140            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9141        }
 9142    }
 9143
 9144    pub fn move_to_previous_word_start(
 9145        &mut self,
 9146        _: &MoveToPreviousWordStart,
 9147        window: &mut Window,
 9148        cx: &mut Context<Self>,
 9149    ) {
 9150        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9151            s.move_cursors_with(|map, head, _| {
 9152                (
 9153                    movement::previous_word_start(map, head),
 9154                    SelectionGoal::None,
 9155                )
 9156            });
 9157        })
 9158    }
 9159
 9160    pub fn move_to_previous_subword_start(
 9161        &mut self,
 9162        _: &MoveToPreviousSubwordStart,
 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_subword_start(map, head),
 9170                    SelectionGoal::None,
 9171                )
 9172            });
 9173        })
 9174    }
 9175
 9176    pub fn select_to_previous_word_start(
 9177        &mut self,
 9178        _: &SelectToPreviousWordStart,
 9179        window: &mut Window,
 9180        cx: &mut Context<Self>,
 9181    ) {
 9182        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9183            s.move_heads_with(|map, head, _| {
 9184                (
 9185                    movement::previous_word_start(map, head),
 9186                    SelectionGoal::None,
 9187                )
 9188            });
 9189        })
 9190    }
 9191
 9192    pub fn select_to_previous_subword_start(
 9193        &mut self,
 9194        _: &SelectToPreviousSubwordStart,
 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_subword_start(map, head),
 9202                    SelectionGoal::None,
 9203                )
 9204            });
 9205        })
 9206    }
 9207
 9208    pub fn delete_to_previous_word_start(
 9209        &mut self,
 9210        action: &DeleteToPreviousWordStart,
 9211        window: &mut Window,
 9212        cx: &mut Context<Self>,
 9213    ) {
 9214        self.transact(window, cx, |this, window, cx| {
 9215            this.select_autoclose_pair(window, cx);
 9216            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9217                let line_mode = s.line_mode;
 9218                s.move_with(|map, selection| {
 9219                    if selection.is_empty() && !line_mode {
 9220                        let cursor = if action.ignore_newlines {
 9221                            movement::previous_word_start(map, selection.head())
 9222                        } else {
 9223                            movement::previous_word_start_or_newline(map, selection.head())
 9224                        };
 9225                        selection.set_head(cursor, SelectionGoal::None);
 9226                    }
 9227                });
 9228            });
 9229            this.insert("", window, cx);
 9230        });
 9231    }
 9232
 9233    pub fn delete_to_previous_subword_start(
 9234        &mut self,
 9235        _: &DeleteToPreviousSubwordStart,
 9236        window: &mut Window,
 9237        cx: &mut Context<Self>,
 9238    ) {
 9239        self.transact(window, cx, |this, window, cx| {
 9240            this.select_autoclose_pair(window, cx);
 9241            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9242                let line_mode = s.line_mode;
 9243                s.move_with(|map, selection| {
 9244                    if selection.is_empty() && !line_mode {
 9245                        let cursor = movement::previous_subword_start(map, selection.head());
 9246                        selection.set_head(cursor, SelectionGoal::None);
 9247                    }
 9248                });
 9249            });
 9250            this.insert("", window, cx);
 9251        });
 9252    }
 9253
 9254    pub fn move_to_next_word_end(
 9255        &mut self,
 9256        _: &MoveToNextWordEnd,
 9257        window: &mut Window,
 9258        cx: &mut Context<Self>,
 9259    ) {
 9260        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9261            s.move_cursors_with(|map, head, _| {
 9262                (movement::next_word_end(map, head), SelectionGoal::None)
 9263            });
 9264        })
 9265    }
 9266
 9267    pub fn move_to_next_subword_end(
 9268        &mut self,
 9269        _: &MoveToNextSubwordEnd,
 9270        window: &mut Window,
 9271        cx: &mut Context<Self>,
 9272    ) {
 9273        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9274            s.move_cursors_with(|map, head, _| {
 9275                (movement::next_subword_end(map, head), SelectionGoal::None)
 9276            });
 9277        })
 9278    }
 9279
 9280    pub fn select_to_next_word_end(
 9281        &mut self,
 9282        _: &SelectToNextWordEnd,
 9283        window: &mut Window,
 9284        cx: &mut Context<Self>,
 9285    ) {
 9286        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9287            s.move_heads_with(|map, head, _| {
 9288                (movement::next_word_end(map, head), SelectionGoal::None)
 9289            });
 9290        })
 9291    }
 9292
 9293    pub fn select_to_next_subword_end(
 9294        &mut self,
 9295        _: &SelectToNextSubwordEnd,
 9296        window: &mut Window,
 9297        cx: &mut Context<Self>,
 9298    ) {
 9299        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9300            s.move_heads_with(|map, head, _| {
 9301                (movement::next_subword_end(map, head), SelectionGoal::None)
 9302            });
 9303        })
 9304    }
 9305
 9306    pub fn delete_to_next_word_end(
 9307        &mut self,
 9308        action: &DeleteToNextWordEnd,
 9309        window: &mut Window,
 9310        cx: &mut Context<Self>,
 9311    ) {
 9312        self.transact(window, cx, |this, window, cx| {
 9313            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9314                let line_mode = s.line_mode;
 9315                s.move_with(|map, selection| {
 9316                    if selection.is_empty() && !line_mode {
 9317                        let cursor = if action.ignore_newlines {
 9318                            movement::next_word_end(map, selection.head())
 9319                        } else {
 9320                            movement::next_word_end_or_newline(map, selection.head())
 9321                        };
 9322                        selection.set_head(cursor, SelectionGoal::None);
 9323                    }
 9324                });
 9325            });
 9326            this.insert("", window, cx);
 9327        });
 9328    }
 9329
 9330    pub fn delete_to_next_subword_end(
 9331        &mut self,
 9332        _: &DeleteToNextSubwordEnd,
 9333        window: &mut Window,
 9334        cx: &mut Context<Self>,
 9335    ) {
 9336        self.transact(window, cx, |this, window, cx| {
 9337            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9338                s.move_with(|map, selection| {
 9339                    if selection.is_empty() {
 9340                        let cursor = movement::next_subword_end(map, selection.head());
 9341                        selection.set_head(cursor, SelectionGoal::None);
 9342                    }
 9343                });
 9344            });
 9345            this.insert("", window, cx);
 9346        });
 9347    }
 9348
 9349    pub fn move_to_beginning_of_line(
 9350        &mut self,
 9351        action: &MoveToBeginningOfLine,
 9352        window: &mut Window,
 9353        cx: &mut Context<Self>,
 9354    ) {
 9355        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9356            s.move_cursors_with(|map, head, _| {
 9357                (
 9358                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 9359                    SelectionGoal::None,
 9360                )
 9361            });
 9362        })
 9363    }
 9364
 9365    pub fn select_to_beginning_of_line(
 9366        &mut self,
 9367        action: &SelectToBeginningOfLine,
 9368        window: &mut Window,
 9369        cx: &mut Context<Self>,
 9370    ) {
 9371        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9372            s.move_heads_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 delete_to_beginning_of_line(
 9382        &mut self,
 9383        _: &DeleteToBeginningOfLine,
 9384        window: &mut Window,
 9385        cx: &mut Context<Self>,
 9386    ) {
 9387        self.transact(window, cx, |this, window, cx| {
 9388            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9389                s.move_with(|_, selection| {
 9390                    selection.reversed = true;
 9391                });
 9392            });
 9393
 9394            this.select_to_beginning_of_line(
 9395                &SelectToBeginningOfLine {
 9396                    stop_at_soft_wraps: false,
 9397                },
 9398                window,
 9399                cx,
 9400            );
 9401            this.backspace(&Backspace, window, cx);
 9402        });
 9403    }
 9404
 9405    pub fn move_to_end_of_line(
 9406        &mut self,
 9407        action: &MoveToEndOfLine,
 9408        window: &mut Window,
 9409        cx: &mut Context<Self>,
 9410    ) {
 9411        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9412            s.move_cursors_with(|map, head, _| {
 9413                (
 9414                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9415                    SelectionGoal::None,
 9416                )
 9417            });
 9418        })
 9419    }
 9420
 9421    pub fn select_to_end_of_line(
 9422        &mut self,
 9423        action: &SelectToEndOfLine,
 9424        window: &mut Window,
 9425        cx: &mut Context<Self>,
 9426    ) {
 9427        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9428            s.move_heads_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 delete_to_end_of_line(
 9438        &mut self,
 9439        _: &DeleteToEndOfLine,
 9440        window: &mut Window,
 9441        cx: &mut Context<Self>,
 9442    ) {
 9443        self.transact(window, cx, |this, window, cx| {
 9444            this.select_to_end_of_line(
 9445                &SelectToEndOfLine {
 9446                    stop_at_soft_wraps: false,
 9447                },
 9448                window,
 9449                cx,
 9450            );
 9451            this.delete(&Delete, window, cx);
 9452        });
 9453    }
 9454
 9455    pub fn cut_to_end_of_line(
 9456        &mut self,
 9457        _: &CutToEndOfLine,
 9458        window: &mut Window,
 9459        cx: &mut Context<Self>,
 9460    ) {
 9461        self.transact(window, cx, |this, window, cx| {
 9462            this.select_to_end_of_line(
 9463                &SelectToEndOfLine {
 9464                    stop_at_soft_wraps: false,
 9465                },
 9466                window,
 9467                cx,
 9468            );
 9469            this.cut(&Cut, window, cx);
 9470        });
 9471    }
 9472
 9473    pub fn move_to_start_of_paragraph(
 9474        &mut self,
 9475        _: &MoveToStartOfParagraph,
 9476        window: &mut Window,
 9477        cx: &mut Context<Self>,
 9478    ) {
 9479        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9480            cx.propagate();
 9481            return;
 9482        }
 9483
 9484        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9485            s.move_with(|map, selection| {
 9486                selection.collapse_to(
 9487                    movement::start_of_paragraph(map, selection.head(), 1),
 9488                    SelectionGoal::None,
 9489                )
 9490            });
 9491        })
 9492    }
 9493
 9494    pub fn move_to_end_of_paragraph(
 9495        &mut self,
 9496        _: &MoveToEndOfParagraph,
 9497        window: &mut Window,
 9498        cx: &mut Context<Self>,
 9499    ) {
 9500        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9501            cx.propagate();
 9502            return;
 9503        }
 9504
 9505        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9506            s.move_with(|map, selection| {
 9507                selection.collapse_to(
 9508                    movement::end_of_paragraph(map, selection.head(), 1),
 9509                    SelectionGoal::None,
 9510                )
 9511            });
 9512        })
 9513    }
 9514
 9515    pub fn select_to_start_of_paragraph(
 9516        &mut self,
 9517        _: &SelectToStartOfParagraph,
 9518        window: &mut Window,
 9519        cx: &mut Context<Self>,
 9520    ) {
 9521        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9522            cx.propagate();
 9523            return;
 9524        }
 9525
 9526        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9527            s.move_heads_with(|map, head, _| {
 9528                (
 9529                    movement::start_of_paragraph(map, head, 1),
 9530                    SelectionGoal::None,
 9531                )
 9532            });
 9533        })
 9534    }
 9535
 9536    pub fn select_to_end_of_paragraph(
 9537        &mut self,
 9538        _: &SelectToEndOfParagraph,
 9539        window: &mut Window,
 9540        cx: &mut Context<Self>,
 9541    ) {
 9542        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9543            cx.propagate();
 9544            return;
 9545        }
 9546
 9547        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9548            s.move_heads_with(|map, head, _| {
 9549                (
 9550                    movement::end_of_paragraph(map, head, 1),
 9551                    SelectionGoal::None,
 9552                )
 9553            });
 9554        })
 9555    }
 9556
 9557    pub fn move_to_start_of_excerpt(
 9558        &mut self,
 9559        _: &MoveToStartOfExcerpt,
 9560        window: &mut Window,
 9561        cx: &mut Context<Self>,
 9562    ) {
 9563        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9564            cx.propagate();
 9565            return;
 9566        }
 9567
 9568        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9569            s.move_with(|map, selection| {
 9570                selection.collapse_to(
 9571                    movement::start_of_excerpt(
 9572                        map,
 9573                        selection.head(),
 9574                        workspace::searchable::Direction::Prev,
 9575                    ),
 9576                    SelectionGoal::None,
 9577                )
 9578            });
 9579        })
 9580    }
 9581
 9582    pub fn move_to_end_of_excerpt(
 9583        &mut self,
 9584        _: &MoveToEndOfExcerpt,
 9585        window: &mut Window,
 9586        cx: &mut Context<Self>,
 9587    ) {
 9588        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9589            cx.propagate();
 9590            return;
 9591        }
 9592
 9593        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9594            s.move_with(|map, selection| {
 9595                selection.collapse_to(
 9596                    movement::end_of_excerpt(
 9597                        map,
 9598                        selection.head(),
 9599                        workspace::searchable::Direction::Next,
 9600                    ),
 9601                    SelectionGoal::None,
 9602                )
 9603            });
 9604        })
 9605    }
 9606
 9607    pub fn select_to_start_of_excerpt(
 9608        &mut self,
 9609        _: &SelectToStartOfExcerpt,
 9610        window: &mut Window,
 9611        cx: &mut Context<Self>,
 9612    ) {
 9613        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9614            cx.propagate();
 9615            return;
 9616        }
 9617
 9618        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9619            s.move_heads_with(|map, head, _| {
 9620                (
 9621                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9622                    SelectionGoal::None,
 9623                )
 9624            });
 9625        })
 9626    }
 9627
 9628    pub fn select_to_end_of_excerpt(
 9629        &mut self,
 9630        _: &SelectToEndOfExcerpt,
 9631        window: &mut Window,
 9632        cx: &mut Context<Self>,
 9633    ) {
 9634        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9635            cx.propagate();
 9636            return;
 9637        }
 9638
 9639        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9640            s.move_heads_with(|map, head, _| {
 9641                (
 9642                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9643                    SelectionGoal::None,
 9644                )
 9645            });
 9646        })
 9647    }
 9648
 9649    pub fn move_to_beginning(
 9650        &mut self,
 9651        _: &MoveToBeginning,
 9652        window: &mut Window,
 9653        cx: &mut Context<Self>,
 9654    ) {
 9655        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9656            cx.propagate();
 9657            return;
 9658        }
 9659
 9660        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9661            s.select_ranges(vec![0..0]);
 9662        });
 9663    }
 9664
 9665    pub fn select_to_beginning(
 9666        &mut self,
 9667        _: &SelectToBeginning,
 9668        window: &mut Window,
 9669        cx: &mut Context<Self>,
 9670    ) {
 9671        let mut selection = self.selections.last::<Point>(cx);
 9672        selection.set_head(Point::zero(), SelectionGoal::None);
 9673
 9674        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9675            s.select(vec![selection]);
 9676        });
 9677    }
 9678
 9679    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9680        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9681            cx.propagate();
 9682            return;
 9683        }
 9684
 9685        let cursor = self.buffer.read(cx).read(cx).len();
 9686        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9687            s.select_ranges(vec![cursor..cursor])
 9688        });
 9689    }
 9690
 9691    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9692        self.nav_history = nav_history;
 9693    }
 9694
 9695    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9696        self.nav_history.as_ref()
 9697    }
 9698
 9699    fn push_to_nav_history(
 9700        &mut self,
 9701        cursor_anchor: Anchor,
 9702        new_position: Option<Point>,
 9703        cx: &mut Context<Self>,
 9704    ) {
 9705        if let Some(nav_history) = self.nav_history.as_mut() {
 9706            let buffer = self.buffer.read(cx).read(cx);
 9707            let cursor_position = cursor_anchor.to_point(&buffer);
 9708            let scroll_state = self.scroll_manager.anchor();
 9709            let scroll_top_row = scroll_state.top_row(&buffer);
 9710            drop(buffer);
 9711
 9712            if let Some(new_position) = new_position {
 9713                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9714                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9715                    return;
 9716                }
 9717            }
 9718
 9719            nav_history.push(
 9720                Some(NavigationData {
 9721                    cursor_anchor,
 9722                    cursor_position,
 9723                    scroll_anchor: scroll_state,
 9724                    scroll_top_row,
 9725                }),
 9726                cx,
 9727            );
 9728        }
 9729    }
 9730
 9731    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9732        let buffer = self.buffer.read(cx).snapshot(cx);
 9733        let mut selection = self.selections.first::<usize>(cx);
 9734        selection.set_head(buffer.len(), SelectionGoal::None);
 9735        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9736            s.select(vec![selection]);
 9737        });
 9738    }
 9739
 9740    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9741        let end = self.buffer.read(cx).read(cx).len();
 9742        self.change_selections(None, window, cx, |s| {
 9743            s.select_ranges(vec![0..end]);
 9744        });
 9745    }
 9746
 9747    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9748        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9749        let mut selections = self.selections.all::<Point>(cx);
 9750        let max_point = display_map.buffer_snapshot.max_point();
 9751        for selection in &mut selections {
 9752            let rows = selection.spanned_rows(true, &display_map);
 9753            selection.start = Point::new(rows.start.0, 0);
 9754            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9755            selection.reversed = false;
 9756        }
 9757        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9758            s.select(selections);
 9759        });
 9760    }
 9761
 9762    pub fn split_selection_into_lines(
 9763        &mut self,
 9764        _: &SplitSelectionIntoLines,
 9765        window: &mut Window,
 9766        cx: &mut Context<Self>,
 9767    ) {
 9768        let selections = self
 9769            .selections
 9770            .all::<Point>(cx)
 9771            .into_iter()
 9772            .map(|selection| selection.start..selection.end)
 9773            .collect::<Vec<_>>();
 9774        self.unfold_ranges(&selections, true, true, cx);
 9775
 9776        let mut new_selection_ranges = Vec::new();
 9777        {
 9778            let buffer = self.buffer.read(cx).read(cx);
 9779            for selection in selections {
 9780                for row in selection.start.row..selection.end.row {
 9781                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9782                    new_selection_ranges.push(cursor..cursor);
 9783                }
 9784
 9785                let is_multiline_selection = selection.start.row != selection.end.row;
 9786                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9787                // so this action feels more ergonomic when paired with other selection operations
 9788                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9789                if !should_skip_last {
 9790                    new_selection_ranges.push(selection.end..selection.end);
 9791                }
 9792            }
 9793        }
 9794        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9795            s.select_ranges(new_selection_ranges);
 9796        });
 9797    }
 9798
 9799    pub fn add_selection_above(
 9800        &mut self,
 9801        _: &AddSelectionAbove,
 9802        window: &mut Window,
 9803        cx: &mut Context<Self>,
 9804    ) {
 9805        self.add_selection(true, window, cx);
 9806    }
 9807
 9808    pub fn add_selection_below(
 9809        &mut self,
 9810        _: &AddSelectionBelow,
 9811        window: &mut Window,
 9812        cx: &mut Context<Self>,
 9813    ) {
 9814        self.add_selection(false, window, cx);
 9815    }
 9816
 9817    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9818        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9819        let mut selections = self.selections.all::<Point>(cx);
 9820        let text_layout_details = self.text_layout_details(window);
 9821        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9822            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9823            let range = oldest_selection.display_range(&display_map).sorted();
 9824
 9825            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9826            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9827            let positions = start_x.min(end_x)..start_x.max(end_x);
 9828
 9829            selections.clear();
 9830            let mut stack = Vec::new();
 9831            for row in range.start.row().0..=range.end.row().0 {
 9832                if let Some(selection) = self.selections.build_columnar_selection(
 9833                    &display_map,
 9834                    DisplayRow(row),
 9835                    &positions,
 9836                    oldest_selection.reversed,
 9837                    &text_layout_details,
 9838                ) {
 9839                    stack.push(selection.id);
 9840                    selections.push(selection);
 9841                }
 9842            }
 9843
 9844            if above {
 9845                stack.reverse();
 9846            }
 9847
 9848            AddSelectionsState { above, stack }
 9849        });
 9850
 9851        let last_added_selection = *state.stack.last().unwrap();
 9852        let mut new_selections = Vec::new();
 9853        if above == state.above {
 9854            let end_row = if above {
 9855                DisplayRow(0)
 9856            } else {
 9857                display_map.max_point().row()
 9858            };
 9859
 9860            'outer: for selection in selections {
 9861                if selection.id == last_added_selection {
 9862                    let range = selection.display_range(&display_map).sorted();
 9863                    debug_assert_eq!(range.start.row(), range.end.row());
 9864                    let mut row = range.start.row();
 9865                    let positions =
 9866                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9867                            px(start)..px(end)
 9868                        } else {
 9869                            let start_x =
 9870                                display_map.x_for_display_point(range.start, &text_layout_details);
 9871                            let end_x =
 9872                                display_map.x_for_display_point(range.end, &text_layout_details);
 9873                            start_x.min(end_x)..start_x.max(end_x)
 9874                        };
 9875
 9876                    while row != end_row {
 9877                        if above {
 9878                            row.0 -= 1;
 9879                        } else {
 9880                            row.0 += 1;
 9881                        }
 9882
 9883                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9884                            &display_map,
 9885                            row,
 9886                            &positions,
 9887                            selection.reversed,
 9888                            &text_layout_details,
 9889                        ) {
 9890                            state.stack.push(new_selection.id);
 9891                            if above {
 9892                                new_selections.push(new_selection);
 9893                                new_selections.push(selection);
 9894                            } else {
 9895                                new_selections.push(selection);
 9896                                new_selections.push(new_selection);
 9897                            }
 9898
 9899                            continue 'outer;
 9900                        }
 9901                    }
 9902                }
 9903
 9904                new_selections.push(selection);
 9905            }
 9906        } else {
 9907            new_selections = selections;
 9908            new_selections.retain(|s| s.id != last_added_selection);
 9909            state.stack.pop();
 9910        }
 9911
 9912        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9913            s.select(new_selections);
 9914        });
 9915        if state.stack.len() > 1 {
 9916            self.add_selections_state = Some(state);
 9917        }
 9918    }
 9919
 9920    pub fn select_next_match_internal(
 9921        &mut self,
 9922        display_map: &DisplaySnapshot,
 9923        replace_newest: bool,
 9924        autoscroll: Option<Autoscroll>,
 9925        window: &mut Window,
 9926        cx: &mut Context<Self>,
 9927    ) -> Result<()> {
 9928        fn select_next_match_ranges(
 9929            this: &mut Editor,
 9930            range: Range<usize>,
 9931            replace_newest: bool,
 9932            auto_scroll: Option<Autoscroll>,
 9933            window: &mut Window,
 9934            cx: &mut Context<Editor>,
 9935        ) {
 9936            this.unfold_ranges(&[range.clone()], false, true, cx);
 9937            this.change_selections(auto_scroll, window, cx, |s| {
 9938                if replace_newest {
 9939                    s.delete(s.newest_anchor().id);
 9940                }
 9941                s.insert_range(range.clone());
 9942            });
 9943        }
 9944
 9945        let buffer = &display_map.buffer_snapshot;
 9946        let mut selections = self.selections.all::<usize>(cx);
 9947        if let Some(mut select_next_state) = self.select_next_state.take() {
 9948            let query = &select_next_state.query;
 9949            if !select_next_state.done {
 9950                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9951                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9952                let mut next_selected_range = None;
 9953
 9954                let bytes_after_last_selection =
 9955                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9956                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9957                let query_matches = query
 9958                    .stream_find_iter(bytes_after_last_selection)
 9959                    .map(|result| (last_selection.end, result))
 9960                    .chain(
 9961                        query
 9962                            .stream_find_iter(bytes_before_first_selection)
 9963                            .map(|result| (0, result)),
 9964                    );
 9965
 9966                for (start_offset, query_match) in query_matches {
 9967                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9968                    let offset_range =
 9969                        start_offset + query_match.start()..start_offset + query_match.end();
 9970                    let display_range = offset_range.start.to_display_point(display_map)
 9971                        ..offset_range.end.to_display_point(display_map);
 9972
 9973                    if !select_next_state.wordwise
 9974                        || (!movement::is_inside_word(display_map, display_range.start)
 9975                            && !movement::is_inside_word(display_map, display_range.end))
 9976                    {
 9977                        // TODO: This is n^2, because we might check all the selections
 9978                        if !selections
 9979                            .iter()
 9980                            .any(|selection| selection.range().overlaps(&offset_range))
 9981                        {
 9982                            next_selected_range = Some(offset_range);
 9983                            break;
 9984                        }
 9985                    }
 9986                }
 9987
 9988                if let Some(next_selected_range) = next_selected_range {
 9989                    select_next_match_ranges(
 9990                        self,
 9991                        next_selected_range,
 9992                        replace_newest,
 9993                        autoscroll,
 9994                        window,
 9995                        cx,
 9996                    );
 9997                } else {
 9998                    select_next_state.done = true;
 9999                }
10000            }
10001
10002            self.select_next_state = Some(select_next_state);
10003        } else {
10004            let mut only_carets = true;
10005            let mut same_text_selected = true;
10006            let mut selected_text = None;
10007
10008            let mut selections_iter = selections.iter().peekable();
10009            while let Some(selection) = selections_iter.next() {
10010                if selection.start != selection.end {
10011                    only_carets = false;
10012                }
10013
10014                if same_text_selected {
10015                    if selected_text.is_none() {
10016                        selected_text =
10017                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10018                    }
10019
10020                    if let Some(next_selection) = selections_iter.peek() {
10021                        if next_selection.range().len() == selection.range().len() {
10022                            let next_selected_text = buffer
10023                                .text_for_range(next_selection.range())
10024                                .collect::<String>();
10025                            if Some(next_selected_text) != selected_text {
10026                                same_text_selected = false;
10027                                selected_text = None;
10028                            }
10029                        } else {
10030                            same_text_selected = false;
10031                            selected_text = None;
10032                        }
10033                    }
10034                }
10035            }
10036
10037            if only_carets {
10038                for selection in &mut selections {
10039                    let word_range = movement::surrounding_word(
10040                        display_map,
10041                        selection.start.to_display_point(display_map),
10042                    );
10043                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10044                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10045                    selection.goal = SelectionGoal::None;
10046                    selection.reversed = false;
10047                    select_next_match_ranges(
10048                        self,
10049                        selection.start..selection.end,
10050                        replace_newest,
10051                        autoscroll,
10052                        window,
10053                        cx,
10054                    );
10055                }
10056
10057                if selections.len() == 1 {
10058                    let selection = selections
10059                        .last()
10060                        .expect("ensured that there's only one selection");
10061                    let query = buffer
10062                        .text_for_range(selection.start..selection.end)
10063                        .collect::<String>();
10064                    let is_empty = query.is_empty();
10065                    let select_state = SelectNextState {
10066                        query: AhoCorasick::new(&[query])?,
10067                        wordwise: true,
10068                        done: is_empty,
10069                    };
10070                    self.select_next_state = Some(select_state);
10071                } else {
10072                    self.select_next_state = None;
10073                }
10074            } else if let Some(selected_text) = selected_text {
10075                self.select_next_state = Some(SelectNextState {
10076                    query: AhoCorasick::new(&[selected_text])?,
10077                    wordwise: false,
10078                    done: false,
10079                });
10080                self.select_next_match_internal(
10081                    display_map,
10082                    replace_newest,
10083                    autoscroll,
10084                    window,
10085                    cx,
10086                )?;
10087            }
10088        }
10089        Ok(())
10090    }
10091
10092    pub fn select_all_matches(
10093        &mut self,
10094        _action: &SelectAllMatches,
10095        window: &mut Window,
10096        cx: &mut Context<Self>,
10097    ) -> Result<()> {
10098        self.push_to_selection_history();
10099        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10100
10101        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10102        let Some(select_next_state) = self.select_next_state.as_mut() else {
10103            return Ok(());
10104        };
10105        if select_next_state.done {
10106            return Ok(());
10107        }
10108
10109        let mut new_selections = self.selections.all::<usize>(cx);
10110
10111        let buffer = &display_map.buffer_snapshot;
10112        let query_matches = select_next_state
10113            .query
10114            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10115
10116        for query_match in query_matches {
10117            let query_match = query_match.unwrap(); // can only fail due to I/O
10118            let offset_range = query_match.start()..query_match.end();
10119            let display_range = offset_range.start.to_display_point(&display_map)
10120                ..offset_range.end.to_display_point(&display_map);
10121
10122            if !select_next_state.wordwise
10123                || (!movement::is_inside_word(&display_map, display_range.start)
10124                    && !movement::is_inside_word(&display_map, display_range.end))
10125            {
10126                self.selections.change_with(cx, |selections| {
10127                    new_selections.push(Selection {
10128                        id: selections.new_selection_id(),
10129                        start: offset_range.start,
10130                        end: offset_range.end,
10131                        reversed: false,
10132                        goal: SelectionGoal::None,
10133                    });
10134                });
10135            }
10136        }
10137
10138        new_selections.sort_by_key(|selection| selection.start);
10139        let mut ix = 0;
10140        while ix + 1 < new_selections.len() {
10141            let current_selection = &new_selections[ix];
10142            let next_selection = &new_selections[ix + 1];
10143            if current_selection.range().overlaps(&next_selection.range()) {
10144                if current_selection.id < next_selection.id {
10145                    new_selections.remove(ix + 1);
10146                } else {
10147                    new_selections.remove(ix);
10148                }
10149            } else {
10150                ix += 1;
10151            }
10152        }
10153
10154        let reversed = self.selections.oldest::<usize>(cx).reversed;
10155
10156        for selection in new_selections.iter_mut() {
10157            selection.reversed = reversed;
10158        }
10159
10160        select_next_state.done = true;
10161        self.unfold_ranges(
10162            &new_selections
10163                .iter()
10164                .map(|selection| selection.range())
10165                .collect::<Vec<_>>(),
10166            false,
10167            false,
10168            cx,
10169        );
10170        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10171            selections.select(new_selections)
10172        });
10173
10174        Ok(())
10175    }
10176
10177    pub fn select_next(
10178        &mut self,
10179        action: &SelectNext,
10180        window: &mut Window,
10181        cx: &mut Context<Self>,
10182    ) -> Result<()> {
10183        self.push_to_selection_history();
10184        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10185        self.select_next_match_internal(
10186            &display_map,
10187            action.replace_newest,
10188            Some(Autoscroll::newest()),
10189            window,
10190            cx,
10191        )?;
10192        Ok(())
10193    }
10194
10195    pub fn select_previous(
10196        &mut self,
10197        action: &SelectPrevious,
10198        window: &mut Window,
10199        cx: &mut Context<Self>,
10200    ) -> Result<()> {
10201        self.push_to_selection_history();
10202        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10203        let buffer = &display_map.buffer_snapshot;
10204        let mut selections = self.selections.all::<usize>(cx);
10205        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10206            let query = &select_prev_state.query;
10207            if !select_prev_state.done {
10208                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10209                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10210                let mut next_selected_range = None;
10211                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10212                let bytes_before_last_selection =
10213                    buffer.reversed_bytes_in_range(0..last_selection.start);
10214                let bytes_after_first_selection =
10215                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10216                let query_matches = query
10217                    .stream_find_iter(bytes_before_last_selection)
10218                    .map(|result| (last_selection.start, result))
10219                    .chain(
10220                        query
10221                            .stream_find_iter(bytes_after_first_selection)
10222                            .map(|result| (buffer.len(), result)),
10223                    );
10224                for (end_offset, query_match) in query_matches {
10225                    let query_match = query_match.unwrap(); // can only fail due to I/O
10226                    let offset_range =
10227                        end_offset - query_match.end()..end_offset - query_match.start();
10228                    let display_range = offset_range.start.to_display_point(&display_map)
10229                        ..offset_range.end.to_display_point(&display_map);
10230
10231                    if !select_prev_state.wordwise
10232                        || (!movement::is_inside_word(&display_map, display_range.start)
10233                            && !movement::is_inside_word(&display_map, display_range.end))
10234                    {
10235                        next_selected_range = Some(offset_range);
10236                        break;
10237                    }
10238                }
10239
10240                if let Some(next_selected_range) = next_selected_range {
10241                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10242                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10243                        if action.replace_newest {
10244                            s.delete(s.newest_anchor().id);
10245                        }
10246                        s.insert_range(next_selected_range);
10247                    });
10248                } else {
10249                    select_prev_state.done = true;
10250                }
10251            }
10252
10253            self.select_prev_state = Some(select_prev_state);
10254        } else {
10255            let mut only_carets = true;
10256            let mut same_text_selected = true;
10257            let mut selected_text = None;
10258
10259            let mut selections_iter = selections.iter().peekable();
10260            while let Some(selection) = selections_iter.next() {
10261                if selection.start != selection.end {
10262                    only_carets = false;
10263                }
10264
10265                if same_text_selected {
10266                    if selected_text.is_none() {
10267                        selected_text =
10268                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10269                    }
10270
10271                    if let Some(next_selection) = selections_iter.peek() {
10272                        if next_selection.range().len() == selection.range().len() {
10273                            let next_selected_text = buffer
10274                                .text_for_range(next_selection.range())
10275                                .collect::<String>();
10276                            if Some(next_selected_text) != selected_text {
10277                                same_text_selected = false;
10278                                selected_text = None;
10279                            }
10280                        } else {
10281                            same_text_selected = false;
10282                            selected_text = None;
10283                        }
10284                    }
10285                }
10286            }
10287
10288            if only_carets {
10289                for selection in &mut selections {
10290                    let word_range = movement::surrounding_word(
10291                        &display_map,
10292                        selection.start.to_display_point(&display_map),
10293                    );
10294                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10295                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10296                    selection.goal = SelectionGoal::None;
10297                    selection.reversed = false;
10298                }
10299                if selections.len() == 1 {
10300                    let selection = selections
10301                        .last()
10302                        .expect("ensured that there's only one selection");
10303                    let query = buffer
10304                        .text_for_range(selection.start..selection.end)
10305                        .collect::<String>();
10306                    let is_empty = query.is_empty();
10307                    let select_state = SelectNextState {
10308                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10309                        wordwise: true,
10310                        done: is_empty,
10311                    };
10312                    self.select_prev_state = Some(select_state);
10313                } else {
10314                    self.select_prev_state = None;
10315                }
10316
10317                self.unfold_ranges(
10318                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10319                    false,
10320                    true,
10321                    cx,
10322                );
10323                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10324                    s.select(selections);
10325                });
10326            } else if let Some(selected_text) = selected_text {
10327                self.select_prev_state = Some(SelectNextState {
10328                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10329                    wordwise: false,
10330                    done: false,
10331                });
10332                self.select_previous(action, window, cx)?;
10333            }
10334        }
10335        Ok(())
10336    }
10337
10338    pub fn toggle_comments(
10339        &mut self,
10340        action: &ToggleComments,
10341        window: &mut Window,
10342        cx: &mut Context<Self>,
10343    ) {
10344        if self.read_only(cx) {
10345            return;
10346        }
10347        let text_layout_details = &self.text_layout_details(window);
10348        self.transact(window, cx, |this, window, cx| {
10349            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10350            let mut edits = Vec::new();
10351            let mut selection_edit_ranges = Vec::new();
10352            let mut last_toggled_row = None;
10353            let snapshot = this.buffer.read(cx).read(cx);
10354            let empty_str: Arc<str> = Arc::default();
10355            let mut suffixes_inserted = Vec::new();
10356            let ignore_indent = action.ignore_indent;
10357
10358            fn comment_prefix_range(
10359                snapshot: &MultiBufferSnapshot,
10360                row: MultiBufferRow,
10361                comment_prefix: &str,
10362                comment_prefix_whitespace: &str,
10363                ignore_indent: bool,
10364            ) -> Range<Point> {
10365                let indent_size = if ignore_indent {
10366                    0
10367                } else {
10368                    snapshot.indent_size_for_line(row).len
10369                };
10370
10371                let start = Point::new(row.0, indent_size);
10372
10373                let mut line_bytes = snapshot
10374                    .bytes_in_range(start..snapshot.max_point())
10375                    .flatten()
10376                    .copied();
10377
10378                // If this line currently begins with the line comment prefix, then record
10379                // the range containing the prefix.
10380                if line_bytes
10381                    .by_ref()
10382                    .take(comment_prefix.len())
10383                    .eq(comment_prefix.bytes())
10384                {
10385                    // Include any whitespace that matches the comment prefix.
10386                    let matching_whitespace_len = line_bytes
10387                        .zip(comment_prefix_whitespace.bytes())
10388                        .take_while(|(a, b)| a == b)
10389                        .count() as u32;
10390                    let end = Point::new(
10391                        start.row,
10392                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10393                    );
10394                    start..end
10395                } else {
10396                    start..start
10397                }
10398            }
10399
10400            fn comment_suffix_range(
10401                snapshot: &MultiBufferSnapshot,
10402                row: MultiBufferRow,
10403                comment_suffix: &str,
10404                comment_suffix_has_leading_space: bool,
10405            ) -> Range<Point> {
10406                let end = Point::new(row.0, snapshot.line_len(row));
10407                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10408
10409                let mut line_end_bytes = snapshot
10410                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10411                    .flatten()
10412                    .copied();
10413
10414                let leading_space_len = if suffix_start_column > 0
10415                    && line_end_bytes.next() == Some(b' ')
10416                    && comment_suffix_has_leading_space
10417                {
10418                    1
10419                } else {
10420                    0
10421                };
10422
10423                // If this line currently begins with the line comment prefix, then record
10424                // the range containing the prefix.
10425                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10426                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10427                    start..end
10428                } else {
10429                    end..end
10430                }
10431            }
10432
10433            // TODO: Handle selections that cross excerpts
10434            for selection in &mut selections {
10435                let start_column = snapshot
10436                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10437                    .len;
10438                let language = if let Some(language) =
10439                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10440                {
10441                    language
10442                } else {
10443                    continue;
10444                };
10445
10446                selection_edit_ranges.clear();
10447
10448                // If multiple selections contain a given row, avoid processing that
10449                // row more than once.
10450                let mut start_row = MultiBufferRow(selection.start.row);
10451                if last_toggled_row == Some(start_row) {
10452                    start_row = start_row.next_row();
10453                }
10454                let end_row =
10455                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10456                        MultiBufferRow(selection.end.row - 1)
10457                    } else {
10458                        MultiBufferRow(selection.end.row)
10459                    };
10460                last_toggled_row = Some(end_row);
10461
10462                if start_row > end_row {
10463                    continue;
10464                }
10465
10466                // If the language has line comments, toggle those.
10467                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10468
10469                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10470                if ignore_indent {
10471                    full_comment_prefixes = full_comment_prefixes
10472                        .into_iter()
10473                        .map(|s| Arc::from(s.trim_end()))
10474                        .collect();
10475                }
10476
10477                if !full_comment_prefixes.is_empty() {
10478                    let first_prefix = full_comment_prefixes
10479                        .first()
10480                        .expect("prefixes is non-empty");
10481                    let prefix_trimmed_lengths = full_comment_prefixes
10482                        .iter()
10483                        .map(|p| p.trim_end_matches(' ').len())
10484                        .collect::<SmallVec<[usize; 4]>>();
10485
10486                    let mut all_selection_lines_are_comments = true;
10487
10488                    for row in start_row.0..=end_row.0 {
10489                        let row = MultiBufferRow(row);
10490                        if start_row < end_row && snapshot.is_line_blank(row) {
10491                            continue;
10492                        }
10493
10494                        let prefix_range = full_comment_prefixes
10495                            .iter()
10496                            .zip(prefix_trimmed_lengths.iter().copied())
10497                            .map(|(prefix, trimmed_prefix_len)| {
10498                                comment_prefix_range(
10499                                    snapshot.deref(),
10500                                    row,
10501                                    &prefix[..trimmed_prefix_len],
10502                                    &prefix[trimmed_prefix_len..],
10503                                    ignore_indent,
10504                                )
10505                            })
10506                            .max_by_key(|range| range.end.column - range.start.column)
10507                            .expect("prefixes is non-empty");
10508
10509                        if prefix_range.is_empty() {
10510                            all_selection_lines_are_comments = false;
10511                        }
10512
10513                        selection_edit_ranges.push(prefix_range);
10514                    }
10515
10516                    if all_selection_lines_are_comments {
10517                        edits.extend(
10518                            selection_edit_ranges
10519                                .iter()
10520                                .cloned()
10521                                .map(|range| (range, empty_str.clone())),
10522                        );
10523                    } else {
10524                        let min_column = selection_edit_ranges
10525                            .iter()
10526                            .map(|range| range.start.column)
10527                            .min()
10528                            .unwrap_or(0);
10529                        edits.extend(selection_edit_ranges.iter().map(|range| {
10530                            let position = Point::new(range.start.row, min_column);
10531                            (position..position, first_prefix.clone())
10532                        }));
10533                    }
10534                } else if let Some((full_comment_prefix, comment_suffix)) =
10535                    language.block_comment_delimiters()
10536                {
10537                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10538                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10539                    let prefix_range = comment_prefix_range(
10540                        snapshot.deref(),
10541                        start_row,
10542                        comment_prefix,
10543                        comment_prefix_whitespace,
10544                        ignore_indent,
10545                    );
10546                    let suffix_range = comment_suffix_range(
10547                        snapshot.deref(),
10548                        end_row,
10549                        comment_suffix.trim_start_matches(' '),
10550                        comment_suffix.starts_with(' '),
10551                    );
10552
10553                    if prefix_range.is_empty() || suffix_range.is_empty() {
10554                        edits.push((
10555                            prefix_range.start..prefix_range.start,
10556                            full_comment_prefix.clone(),
10557                        ));
10558                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10559                        suffixes_inserted.push((end_row, comment_suffix.len()));
10560                    } else {
10561                        edits.push((prefix_range, empty_str.clone()));
10562                        edits.push((suffix_range, empty_str.clone()));
10563                    }
10564                } else {
10565                    continue;
10566                }
10567            }
10568
10569            drop(snapshot);
10570            this.buffer.update(cx, |buffer, cx| {
10571                buffer.edit(edits, None, cx);
10572            });
10573
10574            // Adjust selections so that they end before any comment suffixes that
10575            // were inserted.
10576            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10577            let mut selections = this.selections.all::<Point>(cx);
10578            let snapshot = this.buffer.read(cx).read(cx);
10579            for selection in &mut selections {
10580                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10581                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10582                        Ordering::Less => {
10583                            suffixes_inserted.next();
10584                            continue;
10585                        }
10586                        Ordering::Greater => break,
10587                        Ordering::Equal => {
10588                            if selection.end.column == snapshot.line_len(row) {
10589                                if selection.is_empty() {
10590                                    selection.start.column -= suffix_len as u32;
10591                                }
10592                                selection.end.column -= suffix_len as u32;
10593                            }
10594                            break;
10595                        }
10596                    }
10597                }
10598            }
10599
10600            drop(snapshot);
10601            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10602                s.select(selections)
10603            });
10604
10605            let selections = this.selections.all::<Point>(cx);
10606            let selections_on_single_row = selections.windows(2).all(|selections| {
10607                selections[0].start.row == selections[1].start.row
10608                    && selections[0].end.row == selections[1].end.row
10609                    && selections[0].start.row == selections[0].end.row
10610            });
10611            let selections_selecting = selections
10612                .iter()
10613                .any(|selection| selection.start != selection.end);
10614            let advance_downwards = action.advance_downwards
10615                && selections_on_single_row
10616                && !selections_selecting
10617                && !matches!(this.mode, EditorMode::SingleLine { .. });
10618
10619            if advance_downwards {
10620                let snapshot = this.buffer.read(cx).snapshot(cx);
10621
10622                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10623                    s.move_cursors_with(|display_snapshot, display_point, _| {
10624                        let mut point = display_point.to_point(display_snapshot);
10625                        point.row += 1;
10626                        point = snapshot.clip_point(point, Bias::Left);
10627                        let display_point = point.to_display_point(display_snapshot);
10628                        let goal = SelectionGoal::HorizontalPosition(
10629                            display_snapshot
10630                                .x_for_display_point(display_point, text_layout_details)
10631                                .into(),
10632                        );
10633                        (display_point, goal)
10634                    })
10635                });
10636            }
10637        });
10638    }
10639
10640    pub fn select_enclosing_symbol(
10641        &mut self,
10642        _: &SelectEnclosingSymbol,
10643        window: &mut Window,
10644        cx: &mut Context<Self>,
10645    ) {
10646        let buffer = self.buffer.read(cx).snapshot(cx);
10647        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10648
10649        fn update_selection(
10650            selection: &Selection<usize>,
10651            buffer_snap: &MultiBufferSnapshot,
10652        ) -> Option<Selection<usize>> {
10653            let cursor = selection.head();
10654            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10655            for symbol in symbols.iter().rev() {
10656                let start = symbol.range.start.to_offset(buffer_snap);
10657                let end = symbol.range.end.to_offset(buffer_snap);
10658                let new_range = start..end;
10659                if start < selection.start || end > selection.end {
10660                    return Some(Selection {
10661                        id: selection.id,
10662                        start: new_range.start,
10663                        end: new_range.end,
10664                        goal: SelectionGoal::None,
10665                        reversed: selection.reversed,
10666                    });
10667                }
10668            }
10669            None
10670        }
10671
10672        let mut selected_larger_symbol = false;
10673        let new_selections = old_selections
10674            .iter()
10675            .map(|selection| match update_selection(selection, &buffer) {
10676                Some(new_selection) => {
10677                    if new_selection.range() != selection.range() {
10678                        selected_larger_symbol = true;
10679                    }
10680                    new_selection
10681                }
10682                None => selection.clone(),
10683            })
10684            .collect::<Vec<_>>();
10685
10686        if selected_larger_symbol {
10687            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10688                s.select(new_selections);
10689            });
10690        }
10691    }
10692
10693    pub fn select_larger_syntax_node(
10694        &mut self,
10695        _: &SelectLargerSyntaxNode,
10696        window: &mut Window,
10697        cx: &mut Context<Self>,
10698    ) {
10699        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10700        let buffer = self.buffer.read(cx).snapshot(cx);
10701        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10702
10703        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10704        let mut selected_larger_node = false;
10705        let new_selections = old_selections
10706            .iter()
10707            .map(|selection| {
10708                let old_range = selection.start..selection.end;
10709                let mut new_range = old_range.clone();
10710                let mut new_node = None;
10711                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10712                {
10713                    new_node = Some(node);
10714                    new_range = containing_range;
10715                    if !display_map.intersects_fold(new_range.start)
10716                        && !display_map.intersects_fold(new_range.end)
10717                    {
10718                        break;
10719                    }
10720                }
10721
10722                if let Some(node) = new_node {
10723                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10724                    // nodes. Parent and grandparent are also logged because this operation will not
10725                    // visit nodes that have the same range as their parent.
10726                    log::info!("Node: {node:?}");
10727                    let parent = node.parent();
10728                    log::info!("Parent: {parent:?}");
10729                    let grandparent = parent.and_then(|x| x.parent());
10730                    log::info!("Grandparent: {grandparent:?}");
10731                }
10732
10733                selected_larger_node |= new_range != old_range;
10734                Selection {
10735                    id: selection.id,
10736                    start: new_range.start,
10737                    end: new_range.end,
10738                    goal: SelectionGoal::None,
10739                    reversed: selection.reversed,
10740                }
10741            })
10742            .collect::<Vec<_>>();
10743
10744        if selected_larger_node {
10745            stack.push(old_selections);
10746            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10747                s.select(new_selections);
10748            });
10749        }
10750        self.select_larger_syntax_node_stack = stack;
10751    }
10752
10753    pub fn select_smaller_syntax_node(
10754        &mut self,
10755        _: &SelectSmallerSyntaxNode,
10756        window: &mut Window,
10757        cx: &mut Context<Self>,
10758    ) {
10759        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10760        if let Some(selections) = stack.pop() {
10761            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10762                s.select(selections.to_vec());
10763            });
10764        }
10765        self.select_larger_syntax_node_stack = stack;
10766    }
10767
10768    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10769        if !EditorSettings::get_global(cx).gutter.runnables {
10770            self.clear_tasks();
10771            return Task::ready(());
10772        }
10773        let project = self.project.as_ref().map(Entity::downgrade);
10774        cx.spawn_in(window, |this, mut cx| async move {
10775            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10776            let Some(project) = project.and_then(|p| p.upgrade()) else {
10777                return;
10778            };
10779            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10780                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10781            }) else {
10782                return;
10783            };
10784
10785            let hide_runnables = project
10786                .update(&mut cx, |project, cx| {
10787                    // Do not display any test indicators in non-dev server remote projects.
10788                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10789                })
10790                .unwrap_or(true);
10791            if hide_runnables {
10792                return;
10793            }
10794            let new_rows =
10795                cx.background_spawn({
10796                    let snapshot = display_snapshot.clone();
10797                    async move {
10798                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10799                    }
10800                })
10801                    .await;
10802
10803            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10804            this.update(&mut cx, |this, _| {
10805                this.clear_tasks();
10806                for (key, value) in rows {
10807                    this.insert_tasks(key, value);
10808                }
10809            })
10810            .ok();
10811        })
10812    }
10813    fn fetch_runnable_ranges(
10814        snapshot: &DisplaySnapshot,
10815        range: Range<Anchor>,
10816    ) -> Vec<language::RunnableRange> {
10817        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10818    }
10819
10820    fn runnable_rows(
10821        project: Entity<Project>,
10822        snapshot: DisplaySnapshot,
10823        runnable_ranges: Vec<RunnableRange>,
10824        mut cx: AsyncWindowContext,
10825    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10826        runnable_ranges
10827            .into_iter()
10828            .filter_map(|mut runnable| {
10829                let tasks = cx
10830                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10831                    .ok()?;
10832                if tasks.is_empty() {
10833                    return None;
10834                }
10835
10836                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10837
10838                let row = snapshot
10839                    .buffer_snapshot
10840                    .buffer_line_for_row(MultiBufferRow(point.row))?
10841                    .1
10842                    .start
10843                    .row;
10844
10845                let context_range =
10846                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10847                Some((
10848                    (runnable.buffer_id, row),
10849                    RunnableTasks {
10850                        templates: tasks,
10851                        offset: MultiBufferOffset(runnable.run_range.start),
10852                        context_range,
10853                        column: point.column,
10854                        extra_variables: runnable.extra_captures,
10855                    },
10856                ))
10857            })
10858            .collect()
10859    }
10860
10861    fn templates_with_tags(
10862        project: &Entity<Project>,
10863        runnable: &mut Runnable,
10864        cx: &mut App,
10865    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10866        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10867            let (worktree_id, file) = project
10868                .buffer_for_id(runnable.buffer, cx)
10869                .and_then(|buffer| buffer.read(cx).file())
10870                .map(|file| (file.worktree_id(cx), file.clone()))
10871                .unzip();
10872
10873            (
10874                project.task_store().read(cx).task_inventory().cloned(),
10875                worktree_id,
10876                file,
10877            )
10878        });
10879
10880        let tags = mem::take(&mut runnable.tags);
10881        let mut tags: Vec<_> = tags
10882            .into_iter()
10883            .flat_map(|tag| {
10884                let tag = tag.0.clone();
10885                inventory
10886                    .as_ref()
10887                    .into_iter()
10888                    .flat_map(|inventory| {
10889                        inventory.read(cx).list_tasks(
10890                            file.clone(),
10891                            Some(runnable.language.clone()),
10892                            worktree_id,
10893                            cx,
10894                        )
10895                    })
10896                    .filter(move |(_, template)| {
10897                        template.tags.iter().any(|source_tag| source_tag == &tag)
10898                    })
10899            })
10900            .sorted_by_key(|(kind, _)| kind.to_owned())
10901            .collect();
10902        if let Some((leading_tag_source, _)) = tags.first() {
10903            // Strongest source wins; if we have worktree tag binding, prefer that to
10904            // global and language bindings;
10905            // if we have a global binding, prefer that to language binding.
10906            let first_mismatch = tags
10907                .iter()
10908                .position(|(tag_source, _)| tag_source != leading_tag_source);
10909            if let Some(index) = first_mismatch {
10910                tags.truncate(index);
10911            }
10912        }
10913
10914        tags
10915    }
10916
10917    pub fn move_to_enclosing_bracket(
10918        &mut self,
10919        _: &MoveToEnclosingBracket,
10920        window: &mut Window,
10921        cx: &mut Context<Self>,
10922    ) {
10923        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10924            s.move_offsets_with(|snapshot, selection| {
10925                let Some(enclosing_bracket_ranges) =
10926                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10927                else {
10928                    return;
10929                };
10930
10931                let mut best_length = usize::MAX;
10932                let mut best_inside = false;
10933                let mut best_in_bracket_range = false;
10934                let mut best_destination = None;
10935                for (open, close) in enclosing_bracket_ranges {
10936                    let close = close.to_inclusive();
10937                    let length = close.end() - open.start;
10938                    let inside = selection.start >= open.end && selection.end <= *close.start();
10939                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10940                        || close.contains(&selection.head());
10941
10942                    // If best is next to a bracket and current isn't, skip
10943                    if !in_bracket_range && best_in_bracket_range {
10944                        continue;
10945                    }
10946
10947                    // Prefer smaller lengths unless best is inside and current isn't
10948                    if length > best_length && (best_inside || !inside) {
10949                        continue;
10950                    }
10951
10952                    best_length = length;
10953                    best_inside = inside;
10954                    best_in_bracket_range = in_bracket_range;
10955                    best_destination = Some(
10956                        if close.contains(&selection.start) && close.contains(&selection.end) {
10957                            if inside {
10958                                open.end
10959                            } else {
10960                                open.start
10961                            }
10962                        } else if inside {
10963                            *close.start()
10964                        } else {
10965                            *close.end()
10966                        },
10967                    );
10968                }
10969
10970                if let Some(destination) = best_destination {
10971                    selection.collapse_to(destination, SelectionGoal::None);
10972                }
10973            })
10974        });
10975    }
10976
10977    pub fn undo_selection(
10978        &mut self,
10979        _: &UndoSelection,
10980        window: &mut Window,
10981        cx: &mut Context<Self>,
10982    ) {
10983        self.end_selection(window, cx);
10984        self.selection_history.mode = SelectionHistoryMode::Undoing;
10985        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10986            self.change_selections(None, window, cx, |s| {
10987                s.select_anchors(entry.selections.to_vec())
10988            });
10989            self.select_next_state = entry.select_next_state;
10990            self.select_prev_state = entry.select_prev_state;
10991            self.add_selections_state = entry.add_selections_state;
10992            self.request_autoscroll(Autoscroll::newest(), cx);
10993        }
10994        self.selection_history.mode = SelectionHistoryMode::Normal;
10995    }
10996
10997    pub fn redo_selection(
10998        &mut self,
10999        _: &RedoSelection,
11000        window: &mut Window,
11001        cx: &mut Context<Self>,
11002    ) {
11003        self.end_selection(window, cx);
11004        self.selection_history.mode = SelectionHistoryMode::Redoing;
11005        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11006            self.change_selections(None, window, cx, |s| {
11007                s.select_anchors(entry.selections.to_vec())
11008            });
11009            self.select_next_state = entry.select_next_state;
11010            self.select_prev_state = entry.select_prev_state;
11011            self.add_selections_state = entry.add_selections_state;
11012            self.request_autoscroll(Autoscroll::newest(), cx);
11013        }
11014        self.selection_history.mode = SelectionHistoryMode::Normal;
11015    }
11016
11017    pub fn expand_excerpts(
11018        &mut self,
11019        action: &ExpandExcerpts,
11020        _: &mut Window,
11021        cx: &mut Context<Self>,
11022    ) {
11023        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11024    }
11025
11026    pub fn expand_excerpts_down(
11027        &mut self,
11028        action: &ExpandExcerptsDown,
11029        _: &mut Window,
11030        cx: &mut Context<Self>,
11031    ) {
11032        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11033    }
11034
11035    pub fn expand_excerpts_up(
11036        &mut self,
11037        action: &ExpandExcerptsUp,
11038        _: &mut Window,
11039        cx: &mut Context<Self>,
11040    ) {
11041        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11042    }
11043
11044    pub fn expand_excerpts_for_direction(
11045        &mut self,
11046        lines: u32,
11047        direction: ExpandExcerptDirection,
11048
11049        cx: &mut Context<Self>,
11050    ) {
11051        let selections = self.selections.disjoint_anchors();
11052
11053        let lines = if lines == 0 {
11054            EditorSettings::get_global(cx).expand_excerpt_lines
11055        } else {
11056            lines
11057        };
11058
11059        self.buffer.update(cx, |buffer, cx| {
11060            let snapshot = buffer.snapshot(cx);
11061            let mut excerpt_ids = selections
11062                .iter()
11063                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11064                .collect::<Vec<_>>();
11065            excerpt_ids.sort();
11066            excerpt_ids.dedup();
11067            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11068        })
11069    }
11070
11071    pub fn expand_excerpt(
11072        &mut self,
11073        excerpt: ExcerptId,
11074        direction: ExpandExcerptDirection,
11075        cx: &mut Context<Self>,
11076    ) {
11077        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11078        self.buffer.update(cx, |buffer, cx| {
11079            buffer.expand_excerpts([excerpt], lines, direction, cx)
11080        })
11081    }
11082
11083    pub fn go_to_singleton_buffer_point(
11084        &mut self,
11085        point: Point,
11086        window: &mut Window,
11087        cx: &mut Context<Self>,
11088    ) {
11089        self.go_to_singleton_buffer_range(point..point, window, cx);
11090    }
11091
11092    pub fn go_to_singleton_buffer_range(
11093        &mut self,
11094        range: Range<Point>,
11095        window: &mut Window,
11096        cx: &mut Context<Self>,
11097    ) {
11098        let multibuffer = self.buffer().read(cx);
11099        let Some(buffer) = multibuffer.as_singleton() else {
11100            return;
11101        };
11102        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11103            return;
11104        };
11105        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11106            return;
11107        };
11108        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11109            s.select_anchor_ranges([start..end])
11110        });
11111    }
11112
11113    fn go_to_diagnostic(
11114        &mut self,
11115        _: &GoToDiagnostic,
11116        window: &mut Window,
11117        cx: &mut Context<Self>,
11118    ) {
11119        self.go_to_diagnostic_impl(Direction::Next, window, cx)
11120    }
11121
11122    fn go_to_prev_diagnostic(
11123        &mut self,
11124        _: &GoToPrevDiagnostic,
11125        window: &mut Window,
11126        cx: &mut Context<Self>,
11127    ) {
11128        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11129    }
11130
11131    pub fn go_to_diagnostic_impl(
11132        &mut self,
11133        direction: Direction,
11134        window: &mut Window,
11135        cx: &mut Context<Self>,
11136    ) {
11137        let buffer = self.buffer.read(cx).snapshot(cx);
11138        let selection = self.selections.newest::<usize>(cx);
11139
11140        // If there is an active Diagnostic Popover jump to its diagnostic instead.
11141        if direction == Direction::Next {
11142            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11143                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11144                    return;
11145                };
11146                self.activate_diagnostics(
11147                    buffer_id,
11148                    popover.local_diagnostic.diagnostic.group_id,
11149                    window,
11150                    cx,
11151                );
11152                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11153                    let primary_range_start = active_diagnostics.primary_range.start;
11154                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11155                        let mut new_selection = s.newest_anchor().clone();
11156                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11157                        s.select_anchors(vec![new_selection.clone()]);
11158                    });
11159                    self.refresh_inline_completion(false, true, window, cx);
11160                }
11161                return;
11162            }
11163        }
11164
11165        let active_group_id = self
11166            .active_diagnostics
11167            .as_ref()
11168            .map(|active_group| active_group.group_id);
11169        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11170            active_diagnostics
11171                .primary_range
11172                .to_offset(&buffer)
11173                .to_inclusive()
11174        });
11175        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11176            if active_primary_range.contains(&selection.head()) {
11177                *active_primary_range.start()
11178            } else {
11179                selection.head()
11180            }
11181        } else {
11182            selection.head()
11183        };
11184
11185        let snapshot = self.snapshot(window, cx);
11186        let primary_diagnostics_before = buffer
11187            .diagnostics_in_range::<usize>(0..search_start)
11188            .filter(|entry| entry.diagnostic.is_primary)
11189            .filter(|entry| entry.range.start != entry.range.end)
11190            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11191            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11192            .collect::<Vec<_>>();
11193        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11194            primary_diagnostics_before
11195                .iter()
11196                .position(|entry| entry.diagnostic.group_id == active_group_id)
11197        });
11198
11199        let primary_diagnostics_after = buffer
11200            .diagnostics_in_range::<usize>(search_start..buffer.len())
11201            .filter(|entry| entry.diagnostic.is_primary)
11202            .filter(|entry| entry.range.start != entry.range.end)
11203            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11204            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11205            .collect::<Vec<_>>();
11206        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11207            primary_diagnostics_after
11208                .iter()
11209                .enumerate()
11210                .rev()
11211                .find_map(|(i, entry)| {
11212                    if entry.diagnostic.group_id == active_group_id {
11213                        Some(i)
11214                    } else {
11215                        None
11216                    }
11217                })
11218        });
11219
11220        let next_primary_diagnostic = match direction {
11221            Direction::Prev => primary_diagnostics_before
11222                .iter()
11223                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11224                .rev()
11225                .next(),
11226            Direction::Next => primary_diagnostics_after
11227                .iter()
11228                .skip(
11229                    last_same_group_diagnostic_after
11230                        .map(|index| index + 1)
11231                        .unwrap_or(0),
11232                )
11233                .next(),
11234        };
11235
11236        // Cycle around to the start of the buffer, potentially moving back to the start of
11237        // the currently active diagnostic.
11238        let cycle_around = || match direction {
11239            Direction::Prev => primary_diagnostics_after
11240                .iter()
11241                .rev()
11242                .chain(primary_diagnostics_before.iter().rev())
11243                .next(),
11244            Direction::Next => primary_diagnostics_before
11245                .iter()
11246                .chain(primary_diagnostics_after.iter())
11247                .next(),
11248        };
11249
11250        if let Some((primary_range, group_id)) = next_primary_diagnostic
11251            .or_else(cycle_around)
11252            .map(|entry| (&entry.range, entry.diagnostic.group_id))
11253        {
11254            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11255                return;
11256            };
11257            self.activate_diagnostics(buffer_id, group_id, window, cx);
11258            if self.active_diagnostics.is_some() {
11259                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11260                    s.select(vec![Selection {
11261                        id: selection.id,
11262                        start: primary_range.start,
11263                        end: primary_range.start,
11264                        reversed: false,
11265                        goal: SelectionGoal::None,
11266                    }]);
11267                });
11268                self.refresh_inline_completion(false, true, window, cx);
11269            }
11270        }
11271    }
11272
11273    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11274        let snapshot = self.snapshot(window, cx);
11275        let selection = self.selections.newest::<Point>(cx);
11276        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
11277    }
11278
11279    fn go_to_hunk_after_position(
11280        &mut self,
11281        snapshot: &EditorSnapshot,
11282        position: Point,
11283        window: &mut Window,
11284        cx: &mut Context<Editor>,
11285    ) -> Option<MultiBufferDiffHunk> {
11286        let mut hunk = snapshot
11287            .buffer_snapshot
11288            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11289            .find(|hunk| hunk.row_range.start.0 > position.row);
11290        if hunk.is_none() {
11291            hunk = snapshot
11292                .buffer_snapshot
11293                .diff_hunks_in_range(Point::zero()..position)
11294                .find(|hunk| hunk.row_range.end.0 < position.row)
11295        }
11296        if let Some(hunk) = &hunk {
11297            let destination = Point::new(hunk.row_range.start.0, 0);
11298            self.unfold_ranges(&[destination..destination], false, false, cx);
11299            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11300                s.select_ranges(vec![destination..destination]);
11301            });
11302        }
11303
11304        hunk
11305    }
11306
11307    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
11308        let snapshot = self.snapshot(window, cx);
11309        let selection = self.selections.newest::<Point>(cx);
11310        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
11311    }
11312
11313    fn go_to_hunk_before_position(
11314        &mut self,
11315        snapshot: &EditorSnapshot,
11316        position: Point,
11317        window: &mut Window,
11318        cx: &mut Context<Editor>,
11319    ) -> Option<MultiBufferDiffHunk> {
11320        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
11321        if hunk.is_none() {
11322            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
11323        }
11324        if let Some(hunk) = &hunk {
11325            let destination = Point::new(hunk.row_range.start.0, 0);
11326            self.unfold_ranges(&[destination..destination], false, false, cx);
11327            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11328                s.select_ranges(vec![destination..destination]);
11329            });
11330        }
11331
11332        hunk
11333    }
11334
11335    pub fn go_to_definition(
11336        &mut self,
11337        _: &GoToDefinition,
11338        window: &mut Window,
11339        cx: &mut Context<Self>,
11340    ) -> Task<Result<Navigated>> {
11341        let definition =
11342            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11343        cx.spawn_in(window, |editor, mut cx| async move {
11344            if definition.await? == Navigated::Yes {
11345                return Ok(Navigated::Yes);
11346            }
11347            match editor.update_in(&mut cx, |editor, window, cx| {
11348                editor.find_all_references(&FindAllReferences, window, cx)
11349            })? {
11350                Some(references) => references.await,
11351                None => Ok(Navigated::No),
11352            }
11353        })
11354    }
11355
11356    pub fn go_to_declaration(
11357        &mut self,
11358        _: &GoToDeclaration,
11359        window: &mut Window,
11360        cx: &mut Context<Self>,
11361    ) -> Task<Result<Navigated>> {
11362        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11363    }
11364
11365    pub fn go_to_declaration_split(
11366        &mut self,
11367        _: &GoToDeclaration,
11368        window: &mut Window,
11369        cx: &mut Context<Self>,
11370    ) -> Task<Result<Navigated>> {
11371        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11372    }
11373
11374    pub fn go_to_implementation(
11375        &mut self,
11376        _: &GoToImplementation,
11377        window: &mut Window,
11378        cx: &mut Context<Self>,
11379    ) -> Task<Result<Navigated>> {
11380        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11381    }
11382
11383    pub fn go_to_implementation_split(
11384        &mut self,
11385        _: &GoToImplementationSplit,
11386        window: &mut Window,
11387        cx: &mut Context<Self>,
11388    ) -> Task<Result<Navigated>> {
11389        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11390    }
11391
11392    pub fn go_to_type_definition(
11393        &mut self,
11394        _: &GoToTypeDefinition,
11395        window: &mut Window,
11396        cx: &mut Context<Self>,
11397    ) -> Task<Result<Navigated>> {
11398        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11399    }
11400
11401    pub fn go_to_definition_split(
11402        &mut self,
11403        _: &GoToDefinitionSplit,
11404        window: &mut Window,
11405        cx: &mut Context<Self>,
11406    ) -> Task<Result<Navigated>> {
11407        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11408    }
11409
11410    pub fn go_to_type_definition_split(
11411        &mut self,
11412        _: &GoToTypeDefinitionSplit,
11413        window: &mut Window,
11414        cx: &mut Context<Self>,
11415    ) -> Task<Result<Navigated>> {
11416        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11417    }
11418
11419    fn go_to_definition_of_kind(
11420        &mut self,
11421        kind: GotoDefinitionKind,
11422        split: bool,
11423        window: &mut Window,
11424        cx: &mut Context<Self>,
11425    ) -> Task<Result<Navigated>> {
11426        let Some(provider) = self.semantics_provider.clone() else {
11427            return Task::ready(Ok(Navigated::No));
11428        };
11429        let head = self.selections.newest::<usize>(cx).head();
11430        let buffer = self.buffer.read(cx);
11431        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11432            text_anchor
11433        } else {
11434            return Task::ready(Ok(Navigated::No));
11435        };
11436
11437        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11438            return Task::ready(Ok(Navigated::No));
11439        };
11440
11441        cx.spawn_in(window, |editor, mut cx| async move {
11442            let definitions = definitions.await?;
11443            let navigated = editor
11444                .update_in(&mut cx, |editor, window, cx| {
11445                    editor.navigate_to_hover_links(
11446                        Some(kind),
11447                        definitions
11448                            .into_iter()
11449                            .filter(|location| {
11450                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11451                            })
11452                            .map(HoverLink::Text)
11453                            .collect::<Vec<_>>(),
11454                        split,
11455                        window,
11456                        cx,
11457                    )
11458                })?
11459                .await?;
11460            anyhow::Ok(navigated)
11461        })
11462    }
11463
11464    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11465        let selection = self.selections.newest_anchor();
11466        let head = selection.head();
11467        let tail = selection.tail();
11468
11469        let Some((buffer, start_position)) =
11470            self.buffer.read(cx).text_anchor_for_position(head, cx)
11471        else {
11472            return;
11473        };
11474
11475        let end_position = if head != tail {
11476            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11477                return;
11478            };
11479            Some(pos)
11480        } else {
11481            None
11482        };
11483
11484        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11485            let url = if let Some(end_pos) = end_position {
11486                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11487            } else {
11488                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11489            };
11490
11491            if let Some(url) = url {
11492                editor.update(&mut cx, |_, cx| {
11493                    cx.open_url(&url);
11494                })
11495            } else {
11496                Ok(())
11497            }
11498        });
11499
11500        url_finder.detach();
11501    }
11502
11503    pub fn open_selected_filename(
11504        &mut self,
11505        _: &OpenSelectedFilename,
11506        window: &mut Window,
11507        cx: &mut Context<Self>,
11508    ) {
11509        let Some(workspace) = self.workspace() else {
11510            return;
11511        };
11512
11513        let position = self.selections.newest_anchor().head();
11514
11515        let Some((buffer, buffer_position)) =
11516            self.buffer.read(cx).text_anchor_for_position(position, cx)
11517        else {
11518            return;
11519        };
11520
11521        let project = self.project.clone();
11522
11523        cx.spawn_in(window, |_, mut cx| async move {
11524            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11525
11526            if let Some((_, path)) = result {
11527                workspace
11528                    .update_in(&mut cx, |workspace, window, cx| {
11529                        workspace.open_resolved_path(path, window, cx)
11530                    })?
11531                    .await?;
11532            }
11533            anyhow::Ok(())
11534        })
11535        .detach();
11536    }
11537
11538    pub(crate) fn navigate_to_hover_links(
11539        &mut self,
11540        kind: Option<GotoDefinitionKind>,
11541        mut definitions: Vec<HoverLink>,
11542        split: bool,
11543        window: &mut Window,
11544        cx: &mut Context<Editor>,
11545    ) -> Task<Result<Navigated>> {
11546        // If there is one definition, just open it directly
11547        if definitions.len() == 1 {
11548            let definition = definitions.pop().unwrap();
11549
11550            enum TargetTaskResult {
11551                Location(Option<Location>),
11552                AlreadyNavigated,
11553            }
11554
11555            let target_task = match definition {
11556                HoverLink::Text(link) => {
11557                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11558                }
11559                HoverLink::InlayHint(lsp_location, server_id) => {
11560                    let computation =
11561                        self.compute_target_location(lsp_location, server_id, window, cx);
11562                    cx.background_spawn(async move {
11563                        let location = computation.await?;
11564                        Ok(TargetTaskResult::Location(location))
11565                    })
11566                }
11567                HoverLink::Url(url) => {
11568                    cx.open_url(&url);
11569                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11570                }
11571                HoverLink::File(path) => {
11572                    if let Some(workspace) = self.workspace() {
11573                        cx.spawn_in(window, |_, mut cx| async move {
11574                            workspace
11575                                .update_in(&mut cx, |workspace, window, cx| {
11576                                    workspace.open_resolved_path(path, window, cx)
11577                                })?
11578                                .await
11579                                .map(|_| TargetTaskResult::AlreadyNavigated)
11580                        })
11581                    } else {
11582                        Task::ready(Ok(TargetTaskResult::Location(None)))
11583                    }
11584                }
11585            };
11586            cx.spawn_in(window, |editor, mut cx| async move {
11587                let target = match target_task.await.context("target resolution task")? {
11588                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11589                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11590                    TargetTaskResult::Location(Some(target)) => target,
11591                };
11592
11593                editor.update_in(&mut cx, |editor, window, cx| {
11594                    let Some(workspace) = editor.workspace() else {
11595                        return Navigated::No;
11596                    };
11597                    let pane = workspace.read(cx).active_pane().clone();
11598
11599                    let range = target.range.to_point(target.buffer.read(cx));
11600                    let range = editor.range_for_match(&range);
11601                    let range = collapse_multiline_range(range);
11602
11603                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11604                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11605                    } else {
11606                        window.defer(cx, move |window, cx| {
11607                            let target_editor: Entity<Self> =
11608                                workspace.update(cx, |workspace, cx| {
11609                                    let pane = if split {
11610                                        workspace.adjacent_pane(window, cx)
11611                                    } else {
11612                                        workspace.active_pane().clone()
11613                                    };
11614
11615                                    workspace.open_project_item(
11616                                        pane,
11617                                        target.buffer.clone(),
11618                                        true,
11619                                        true,
11620                                        window,
11621                                        cx,
11622                                    )
11623                                });
11624                            target_editor.update(cx, |target_editor, cx| {
11625                                // When selecting a definition in a different buffer, disable the nav history
11626                                // to avoid creating a history entry at the previous cursor location.
11627                                pane.update(cx, |pane, _| pane.disable_history());
11628                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11629                                pane.update(cx, |pane, _| pane.enable_history());
11630                            });
11631                        });
11632                    }
11633                    Navigated::Yes
11634                })
11635            })
11636        } else if !definitions.is_empty() {
11637            cx.spawn_in(window, |editor, mut cx| async move {
11638                let (title, location_tasks, workspace) = editor
11639                    .update_in(&mut cx, |editor, window, cx| {
11640                        let tab_kind = match kind {
11641                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11642                            _ => "Definitions",
11643                        };
11644                        let title = definitions
11645                            .iter()
11646                            .find_map(|definition| match definition {
11647                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11648                                    let buffer = origin.buffer.read(cx);
11649                                    format!(
11650                                        "{} for {}",
11651                                        tab_kind,
11652                                        buffer
11653                                            .text_for_range(origin.range.clone())
11654                                            .collect::<String>()
11655                                    )
11656                                }),
11657                                HoverLink::InlayHint(_, _) => None,
11658                                HoverLink::Url(_) => None,
11659                                HoverLink::File(_) => None,
11660                            })
11661                            .unwrap_or(tab_kind.to_string());
11662                        let location_tasks = definitions
11663                            .into_iter()
11664                            .map(|definition| match definition {
11665                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11666                                HoverLink::InlayHint(lsp_location, server_id) => editor
11667                                    .compute_target_location(lsp_location, server_id, window, cx),
11668                                HoverLink::Url(_) => Task::ready(Ok(None)),
11669                                HoverLink::File(_) => Task::ready(Ok(None)),
11670                            })
11671                            .collect::<Vec<_>>();
11672                        (title, location_tasks, editor.workspace().clone())
11673                    })
11674                    .context("location tasks preparation")?;
11675
11676                let locations = future::join_all(location_tasks)
11677                    .await
11678                    .into_iter()
11679                    .filter_map(|location| location.transpose())
11680                    .collect::<Result<_>>()
11681                    .context("location tasks")?;
11682
11683                let Some(workspace) = workspace else {
11684                    return Ok(Navigated::No);
11685                };
11686                let opened = workspace
11687                    .update_in(&mut cx, |workspace, window, cx| {
11688                        Self::open_locations_in_multibuffer(
11689                            workspace,
11690                            locations,
11691                            title,
11692                            split,
11693                            MultibufferSelectionMode::First,
11694                            window,
11695                            cx,
11696                        )
11697                    })
11698                    .ok();
11699
11700                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11701            })
11702        } else {
11703            Task::ready(Ok(Navigated::No))
11704        }
11705    }
11706
11707    fn compute_target_location(
11708        &self,
11709        lsp_location: lsp::Location,
11710        server_id: LanguageServerId,
11711        window: &mut Window,
11712        cx: &mut Context<Self>,
11713    ) -> Task<anyhow::Result<Option<Location>>> {
11714        let Some(project) = self.project.clone() else {
11715            return Task::ready(Ok(None));
11716        };
11717
11718        cx.spawn_in(window, move |editor, mut cx| async move {
11719            let location_task = editor.update(&mut cx, |_, cx| {
11720                project.update(cx, |project, cx| {
11721                    let language_server_name = project
11722                        .language_server_statuses(cx)
11723                        .find(|(id, _)| server_id == *id)
11724                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11725                    language_server_name.map(|language_server_name| {
11726                        project.open_local_buffer_via_lsp(
11727                            lsp_location.uri.clone(),
11728                            server_id,
11729                            language_server_name,
11730                            cx,
11731                        )
11732                    })
11733                })
11734            })?;
11735            let location = match location_task {
11736                Some(task) => Some({
11737                    let target_buffer_handle = task.await.context("open local buffer")?;
11738                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11739                        let target_start = target_buffer
11740                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11741                        let target_end = target_buffer
11742                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11743                        target_buffer.anchor_after(target_start)
11744                            ..target_buffer.anchor_before(target_end)
11745                    })?;
11746                    Location {
11747                        buffer: target_buffer_handle,
11748                        range,
11749                    }
11750                }),
11751                None => None,
11752            };
11753            Ok(location)
11754        })
11755    }
11756
11757    pub fn find_all_references(
11758        &mut self,
11759        _: &FindAllReferences,
11760        window: &mut Window,
11761        cx: &mut Context<Self>,
11762    ) -> Option<Task<Result<Navigated>>> {
11763        let selection = self.selections.newest::<usize>(cx);
11764        let multi_buffer = self.buffer.read(cx);
11765        let head = selection.head();
11766
11767        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11768        let head_anchor = multi_buffer_snapshot.anchor_at(
11769            head,
11770            if head < selection.tail() {
11771                Bias::Right
11772            } else {
11773                Bias::Left
11774            },
11775        );
11776
11777        match self
11778            .find_all_references_task_sources
11779            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11780        {
11781            Ok(_) => {
11782                log::info!(
11783                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11784                );
11785                return None;
11786            }
11787            Err(i) => {
11788                self.find_all_references_task_sources.insert(i, head_anchor);
11789            }
11790        }
11791
11792        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11793        let workspace = self.workspace()?;
11794        let project = workspace.read(cx).project().clone();
11795        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11796        Some(cx.spawn_in(window, |editor, mut cx| async move {
11797            let _cleanup = defer({
11798                let mut cx = cx.clone();
11799                move || {
11800                    let _ = editor.update(&mut cx, |editor, _| {
11801                        if let Ok(i) =
11802                            editor
11803                                .find_all_references_task_sources
11804                                .binary_search_by(|anchor| {
11805                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11806                                })
11807                        {
11808                            editor.find_all_references_task_sources.remove(i);
11809                        }
11810                    });
11811                }
11812            });
11813
11814            let locations = references.await?;
11815            if locations.is_empty() {
11816                return anyhow::Ok(Navigated::No);
11817            }
11818
11819            workspace.update_in(&mut cx, |workspace, window, cx| {
11820                let title = locations
11821                    .first()
11822                    .as_ref()
11823                    .map(|location| {
11824                        let buffer = location.buffer.read(cx);
11825                        format!(
11826                            "References to `{}`",
11827                            buffer
11828                                .text_for_range(location.range.clone())
11829                                .collect::<String>()
11830                        )
11831                    })
11832                    .unwrap();
11833                Self::open_locations_in_multibuffer(
11834                    workspace,
11835                    locations,
11836                    title,
11837                    false,
11838                    MultibufferSelectionMode::First,
11839                    window,
11840                    cx,
11841                );
11842                Navigated::Yes
11843            })
11844        }))
11845    }
11846
11847    /// Opens a multibuffer with the given project locations in it
11848    pub fn open_locations_in_multibuffer(
11849        workspace: &mut Workspace,
11850        mut locations: Vec<Location>,
11851        title: String,
11852        split: bool,
11853        multibuffer_selection_mode: MultibufferSelectionMode,
11854        window: &mut Window,
11855        cx: &mut Context<Workspace>,
11856    ) {
11857        // If there are multiple definitions, open them in a multibuffer
11858        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11859        let mut locations = locations.into_iter().peekable();
11860        let mut ranges = Vec::new();
11861        let capability = workspace.project().read(cx).capability();
11862
11863        let excerpt_buffer = cx.new(|cx| {
11864            let mut multibuffer = MultiBuffer::new(capability);
11865            while let Some(location) = locations.next() {
11866                let buffer = location.buffer.read(cx);
11867                let mut ranges_for_buffer = Vec::new();
11868                let range = location.range.to_offset(buffer);
11869                ranges_for_buffer.push(range.clone());
11870
11871                while let Some(next_location) = locations.peek() {
11872                    if next_location.buffer == location.buffer {
11873                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11874                        locations.next();
11875                    } else {
11876                        break;
11877                    }
11878                }
11879
11880                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11881                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11882                    location.buffer.clone(),
11883                    ranges_for_buffer,
11884                    DEFAULT_MULTIBUFFER_CONTEXT,
11885                    cx,
11886                ))
11887            }
11888
11889            multibuffer.with_title(title)
11890        });
11891
11892        let editor = cx.new(|cx| {
11893            Editor::for_multibuffer(
11894                excerpt_buffer,
11895                Some(workspace.project().clone()),
11896                true,
11897                window,
11898                cx,
11899            )
11900        });
11901        editor.update(cx, |editor, cx| {
11902            match multibuffer_selection_mode {
11903                MultibufferSelectionMode::First => {
11904                    if let Some(first_range) = ranges.first() {
11905                        editor.change_selections(None, window, cx, |selections| {
11906                            selections.clear_disjoint();
11907                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11908                        });
11909                    }
11910                    editor.highlight_background::<Self>(
11911                        &ranges,
11912                        |theme| theme.editor_highlighted_line_background,
11913                        cx,
11914                    );
11915                }
11916                MultibufferSelectionMode::All => {
11917                    editor.change_selections(None, window, cx, |selections| {
11918                        selections.clear_disjoint();
11919                        selections.select_anchor_ranges(ranges);
11920                    });
11921                }
11922            }
11923            editor.register_buffers_with_language_servers(cx);
11924        });
11925
11926        let item = Box::new(editor);
11927        let item_id = item.item_id();
11928
11929        if split {
11930            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11931        } else {
11932            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11933                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11934                    pane.close_current_preview_item(window, cx)
11935                } else {
11936                    None
11937                }
11938            });
11939            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11940        }
11941        workspace.active_pane().update(cx, |pane, cx| {
11942            pane.set_preview_item_id(Some(item_id), cx);
11943        });
11944    }
11945
11946    pub fn rename(
11947        &mut self,
11948        _: &Rename,
11949        window: &mut Window,
11950        cx: &mut Context<Self>,
11951    ) -> Option<Task<Result<()>>> {
11952        use language::ToOffset as _;
11953
11954        let provider = self.semantics_provider.clone()?;
11955        let selection = self.selections.newest_anchor().clone();
11956        let (cursor_buffer, cursor_buffer_position) = self
11957            .buffer
11958            .read(cx)
11959            .text_anchor_for_position(selection.head(), cx)?;
11960        let (tail_buffer, cursor_buffer_position_end) = self
11961            .buffer
11962            .read(cx)
11963            .text_anchor_for_position(selection.tail(), cx)?;
11964        if tail_buffer != cursor_buffer {
11965            return None;
11966        }
11967
11968        let snapshot = cursor_buffer.read(cx).snapshot();
11969        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11970        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11971        let prepare_rename = provider
11972            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11973            .unwrap_or_else(|| Task::ready(Ok(None)));
11974        drop(snapshot);
11975
11976        Some(cx.spawn_in(window, |this, mut cx| async move {
11977            let rename_range = if let Some(range) = prepare_rename.await? {
11978                Some(range)
11979            } else {
11980                this.update(&mut cx, |this, cx| {
11981                    let buffer = this.buffer.read(cx).snapshot(cx);
11982                    let mut buffer_highlights = this
11983                        .document_highlights_for_position(selection.head(), &buffer)
11984                        .filter(|highlight| {
11985                            highlight.start.excerpt_id == selection.head().excerpt_id
11986                                && highlight.end.excerpt_id == selection.head().excerpt_id
11987                        });
11988                    buffer_highlights
11989                        .next()
11990                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11991                })?
11992            };
11993            if let Some(rename_range) = rename_range {
11994                this.update_in(&mut cx, |this, window, cx| {
11995                    let snapshot = cursor_buffer.read(cx).snapshot();
11996                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11997                    let cursor_offset_in_rename_range =
11998                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11999                    let cursor_offset_in_rename_range_end =
12000                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12001
12002                    this.take_rename(false, window, cx);
12003                    let buffer = this.buffer.read(cx).read(cx);
12004                    let cursor_offset = selection.head().to_offset(&buffer);
12005                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12006                    let rename_end = rename_start + rename_buffer_range.len();
12007                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12008                    let mut old_highlight_id = None;
12009                    let old_name: Arc<str> = buffer
12010                        .chunks(rename_start..rename_end, true)
12011                        .map(|chunk| {
12012                            if old_highlight_id.is_none() {
12013                                old_highlight_id = chunk.syntax_highlight_id;
12014                            }
12015                            chunk.text
12016                        })
12017                        .collect::<String>()
12018                        .into();
12019
12020                    drop(buffer);
12021
12022                    // Position the selection in the rename editor so that it matches the current selection.
12023                    this.show_local_selections = false;
12024                    let rename_editor = cx.new(|cx| {
12025                        let mut editor = Editor::single_line(window, cx);
12026                        editor.buffer.update(cx, |buffer, cx| {
12027                            buffer.edit([(0..0, old_name.clone())], None, cx)
12028                        });
12029                        let rename_selection_range = match cursor_offset_in_rename_range
12030                            .cmp(&cursor_offset_in_rename_range_end)
12031                        {
12032                            Ordering::Equal => {
12033                                editor.select_all(&SelectAll, window, cx);
12034                                return editor;
12035                            }
12036                            Ordering::Less => {
12037                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12038                            }
12039                            Ordering::Greater => {
12040                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12041                            }
12042                        };
12043                        if rename_selection_range.end > old_name.len() {
12044                            editor.select_all(&SelectAll, window, cx);
12045                        } else {
12046                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12047                                s.select_ranges([rename_selection_range]);
12048                            });
12049                        }
12050                        editor
12051                    });
12052                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12053                        if e == &EditorEvent::Focused {
12054                            cx.emit(EditorEvent::FocusedIn)
12055                        }
12056                    })
12057                    .detach();
12058
12059                    let write_highlights =
12060                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12061                    let read_highlights =
12062                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12063                    let ranges = write_highlights
12064                        .iter()
12065                        .flat_map(|(_, ranges)| ranges.iter())
12066                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12067                        .cloned()
12068                        .collect();
12069
12070                    this.highlight_text::<Rename>(
12071                        ranges,
12072                        HighlightStyle {
12073                            fade_out: Some(0.6),
12074                            ..Default::default()
12075                        },
12076                        cx,
12077                    );
12078                    let rename_focus_handle = rename_editor.focus_handle(cx);
12079                    window.focus(&rename_focus_handle);
12080                    let block_id = this.insert_blocks(
12081                        [BlockProperties {
12082                            style: BlockStyle::Flex,
12083                            placement: BlockPlacement::Below(range.start),
12084                            height: 1,
12085                            render: Arc::new({
12086                                let rename_editor = rename_editor.clone();
12087                                move |cx: &mut BlockContext| {
12088                                    let mut text_style = cx.editor_style.text.clone();
12089                                    if let Some(highlight_style) = old_highlight_id
12090                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12091                                    {
12092                                        text_style = text_style.highlight(highlight_style);
12093                                    }
12094                                    div()
12095                                        .block_mouse_down()
12096                                        .pl(cx.anchor_x)
12097                                        .child(EditorElement::new(
12098                                            &rename_editor,
12099                                            EditorStyle {
12100                                                background: cx.theme().system().transparent,
12101                                                local_player: cx.editor_style.local_player,
12102                                                text: text_style,
12103                                                scrollbar_width: cx.editor_style.scrollbar_width,
12104                                                syntax: cx.editor_style.syntax.clone(),
12105                                                status: cx.editor_style.status.clone(),
12106                                                inlay_hints_style: HighlightStyle {
12107                                                    font_weight: Some(FontWeight::BOLD),
12108                                                    ..make_inlay_hints_style(cx.app)
12109                                                },
12110                                                inline_completion_styles: make_suggestion_styles(
12111                                                    cx.app,
12112                                                ),
12113                                                ..EditorStyle::default()
12114                                            },
12115                                        ))
12116                                        .into_any_element()
12117                                }
12118                            }),
12119                            priority: 0,
12120                        }],
12121                        Some(Autoscroll::fit()),
12122                        cx,
12123                    )[0];
12124                    this.pending_rename = Some(RenameState {
12125                        range,
12126                        old_name,
12127                        editor: rename_editor,
12128                        block_id,
12129                    });
12130                })?;
12131            }
12132
12133            Ok(())
12134        }))
12135    }
12136
12137    pub fn confirm_rename(
12138        &mut self,
12139        _: &ConfirmRename,
12140        window: &mut Window,
12141        cx: &mut Context<Self>,
12142    ) -> Option<Task<Result<()>>> {
12143        let rename = self.take_rename(false, window, cx)?;
12144        let workspace = self.workspace()?.downgrade();
12145        let (buffer, start) = self
12146            .buffer
12147            .read(cx)
12148            .text_anchor_for_position(rename.range.start, cx)?;
12149        let (end_buffer, _) = self
12150            .buffer
12151            .read(cx)
12152            .text_anchor_for_position(rename.range.end, cx)?;
12153        if buffer != end_buffer {
12154            return None;
12155        }
12156
12157        let old_name = rename.old_name;
12158        let new_name = rename.editor.read(cx).text(cx);
12159
12160        let rename = self.semantics_provider.as_ref()?.perform_rename(
12161            &buffer,
12162            start,
12163            new_name.clone(),
12164            cx,
12165        )?;
12166
12167        Some(cx.spawn_in(window, |editor, mut cx| async move {
12168            let project_transaction = rename.await?;
12169            Self::open_project_transaction(
12170                &editor,
12171                workspace,
12172                project_transaction,
12173                format!("Rename: {}{}", old_name, new_name),
12174                cx.clone(),
12175            )
12176            .await?;
12177
12178            editor.update(&mut cx, |editor, cx| {
12179                editor.refresh_document_highlights(cx);
12180            })?;
12181            Ok(())
12182        }))
12183    }
12184
12185    fn take_rename(
12186        &mut self,
12187        moving_cursor: bool,
12188        window: &mut Window,
12189        cx: &mut Context<Self>,
12190    ) -> Option<RenameState> {
12191        let rename = self.pending_rename.take()?;
12192        if rename.editor.focus_handle(cx).is_focused(window) {
12193            window.focus(&self.focus_handle);
12194        }
12195
12196        self.remove_blocks(
12197            [rename.block_id].into_iter().collect(),
12198            Some(Autoscroll::fit()),
12199            cx,
12200        );
12201        self.clear_highlights::<Rename>(cx);
12202        self.show_local_selections = true;
12203
12204        if moving_cursor {
12205            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12206                editor.selections.newest::<usize>(cx).head()
12207            });
12208
12209            // Update the selection to match the position of the selection inside
12210            // the rename editor.
12211            let snapshot = self.buffer.read(cx).read(cx);
12212            let rename_range = rename.range.to_offset(&snapshot);
12213            let cursor_in_editor = snapshot
12214                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12215                .min(rename_range.end);
12216            drop(snapshot);
12217
12218            self.change_selections(None, window, cx, |s| {
12219                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12220            });
12221        } else {
12222            self.refresh_document_highlights(cx);
12223        }
12224
12225        Some(rename)
12226    }
12227
12228    pub fn pending_rename(&self) -> Option<&RenameState> {
12229        self.pending_rename.as_ref()
12230    }
12231
12232    fn format(
12233        &mut self,
12234        _: &Format,
12235        window: &mut Window,
12236        cx: &mut Context<Self>,
12237    ) -> Option<Task<Result<()>>> {
12238        let project = match &self.project {
12239            Some(project) => project.clone(),
12240            None => return None,
12241        };
12242
12243        Some(self.perform_format(
12244            project,
12245            FormatTrigger::Manual,
12246            FormatTarget::Buffers,
12247            window,
12248            cx,
12249        ))
12250    }
12251
12252    fn format_selections(
12253        &mut self,
12254        _: &FormatSelections,
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        let ranges = self
12264            .selections
12265            .all_adjusted(cx)
12266            .into_iter()
12267            .map(|selection| selection.range())
12268            .collect_vec();
12269
12270        Some(self.perform_format(
12271            project,
12272            FormatTrigger::Manual,
12273            FormatTarget::Ranges(ranges),
12274            window,
12275            cx,
12276        ))
12277    }
12278
12279    fn perform_format(
12280        &mut self,
12281        project: Entity<Project>,
12282        trigger: FormatTrigger,
12283        target: FormatTarget,
12284        window: &mut Window,
12285        cx: &mut Context<Self>,
12286    ) -> Task<Result<()>> {
12287        let buffer = self.buffer.clone();
12288        let (buffers, target) = match target {
12289            FormatTarget::Buffers => {
12290                let mut buffers = buffer.read(cx).all_buffers();
12291                if trigger == FormatTrigger::Save {
12292                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12293                }
12294                (buffers, LspFormatTarget::Buffers)
12295            }
12296            FormatTarget::Ranges(selection_ranges) => {
12297                let multi_buffer = buffer.read(cx);
12298                let snapshot = multi_buffer.read(cx);
12299                let mut buffers = HashSet::default();
12300                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12301                    BTreeMap::new();
12302                for selection_range in selection_ranges {
12303                    for (buffer, buffer_range, _) in
12304                        snapshot.range_to_buffer_ranges(selection_range)
12305                    {
12306                        let buffer_id = buffer.remote_id();
12307                        let start = buffer.anchor_before(buffer_range.start);
12308                        let end = buffer.anchor_after(buffer_range.end);
12309                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12310                        buffer_id_to_ranges
12311                            .entry(buffer_id)
12312                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12313                            .or_insert_with(|| vec![start..end]);
12314                    }
12315                }
12316                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12317            }
12318        };
12319
12320        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12321        let format = project.update(cx, |project, cx| {
12322            project.format(buffers, target, true, trigger, cx)
12323        });
12324
12325        cx.spawn_in(window, |_, mut cx| async move {
12326            let transaction = futures::select_biased! {
12327                () = timeout => {
12328                    log::warn!("timed out waiting for formatting");
12329                    None
12330                }
12331                transaction = format.log_err().fuse() => transaction,
12332            };
12333
12334            buffer
12335                .update(&mut cx, |buffer, cx| {
12336                    if let Some(transaction) = transaction {
12337                        if !buffer.is_singleton() {
12338                            buffer.push_transaction(&transaction.0, cx);
12339                        }
12340                    }
12341
12342                    cx.notify();
12343                })
12344                .ok();
12345
12346            Ok(())
12347        })
12348    }
12349
12350    fn restart_language_server(
12351        &mut self,
12352        _: &RestartLanguageServer,
12353        _: &mut Window,
12354        cx: &mut Context<Self>,
12355    ) {
12356        if let Some(project) = self.project.clone() {
12357            self.buffer.update(cx, |multi_buffer, cx| {
12358                project.update(cx, |project, cx| {
12359                    project.restart_language_servers_for_buffers(
12360                        multi_buffer.all_buffers().into_iter().collect(),
12361                        cx,
12362                    );
12363                });
12364            })
12365        }
12366    }
12367
12368    fn cancel_language_server_work(
12369        workspace: &mut Workspace,
12370        _: &actions::CancelLanguageServerWork,
12371        _: &mut Window,
12372        cx: &mut Context<Workspace>,
12373    ) {
12374        let project = workspace.project();
12375        let buffers = workspace
12376            .active_item(cx)
12377            .and_then(|item| item.act_as::<Editor>(cx))
12378            .map_or(HashSet::default(), |editor| {
12379                editor.read(cx).buffer.read(cx).all_buffers()
12380            });
12381        project.update(cx, |project, cx| {
12382            project.cancel_language_server_work_for_buffers(buffers, cx);
12383        });
12384    }
12385
12386    fn show_character_palette(
12387        &mut self,
12388        _: &ShowCharacterPalette,
12389        window: &mut Window,
12390        _: &mut Context<Self>,
12391    ) {
12392        window.show_character_palette();
12393    }
12394
12395    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12396        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12397            let buffer = self.buffer.read(cx).snapshot(cx);
12398            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12399            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12400            let is_valid = buffer
12401                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12402                .any(|entry| {
12403                    entry.diagnostic.is_primary
12404                        && !entry.range.is_empty()
12405                        && entry.range.start == primary_range_start
12406                        && entry.diagnostic.message == active_diagnostics.primary_message
12407                });
12408
12409            if is_valid != active_diagnostics.is_valid {
12410                active_diagnostics.is_valid = is_valid;
12411                let mut new_styles = HashMap::default();
12412                for (block_id, diagnostic) in &active_diagnostics.blocks {
12413                    new_styles.insert(
12414                        *block_id,
12415                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
12416                    );
12417                }
12418                self.display_map.update(cx, |display_map, _cx| {
12419                    display_map.replace_blocks(new_styles)
12420                });
12421            }
12422        }
12423    }
12424
12425    fn activate_diagnostics(
12426        &mut self,
12427        buffer_id: BufferId,
12428        group_id: usize,
12429        window: &mut Window,
12430        cx: &mut Context<Self>,
12431    ) {
12432        self.dismiss_diagnostics(cx);
12433        let snapshot = self.snapshot(window, cx);
12434        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12435            let buffer = self.buffer.read(cx).snapshot(cx);
12436
12437            let mut primary_range = None;
12438            let mut primary_message = None;
12439            let diagnostic_group = buffer
12440                .diagnostic_group(buffer_id, group_id)
12441                .filter_map(|entry| {
12442                    let start = entry.range.start;
12443                    let end = entry.range.end;
12444                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12445                        && (start.row == end.row
12446                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12447                    {
12448                        return None;
12449                    }
12450                    if entry.diagnostic.is_primary {
12451                        primary_range = Some(entry.range.clone());
12452                        primary_message = Some(entry.diagnostic.message.clone());
12453                    }
12454                    Some(entry)
12455                })
12456                .collect::<Vec<_>>();
12457            let primary_range = primary_range?;
12458            let primary_message = primary_message?;
12459
12460            let blocks = display_map
12461                .insert_blocks(
12462                    diagnostic_group.iter().map(|entry| {
12463                        let diagnostic = entry.diagnostic.clone();
12464                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12465                        BlockProperties {
12466                            style: BlockStyle::Fixed,
12467                            placement: BlockPlacement::Below(
12468                                buffer.anchor_after(entry.range.start),
12469                            ),
12470                            height: message_height,
12471                            render: diagnostic_block_renderer(diagnostic, None, true, true),
12472                            priority: 0,
12473                        }
12474                    }),
12475                    cx,
12476                )
12477                .into_iter()
12478                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12479                .collect();
12480
12481            Some(ActiveDiagnosticGroup {
12482                primary_range: buffer.anchor_before(primary_range.start)
12483                    ..buffer.anchor_after(primary_range.end),
12484                primary_message,
12485                group_id,
12486                blocks,
12487                is_valid: true,
12488            })
12489        });
12490    }
12491
12492    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12493        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12494            self.display_map.update(cx, |display_map, cx| {
12495                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12496            });
12497            cx.notify();
12498        }
12499    }
12500
12501    /// Disable inline diagnostics rendering for this editor.
12502    pub fn disable_inline_diagnostics(&mut self) {
12503        self.inline_diagnostics_enabled = false;
12504        self.inline_diagnostics_update = Task::ready(());
12505        self.inline_diagnostics.clear();
12506    }
12507
12508    pub fn inline_diagnostics_enabled(&self) -> bool {
12509        self.inline_diagnostics_enabled
12510    }
12511
12512    pub fn show_inline_diagnostics(&self) -> bool {
12513        self.show_inline_diagnostics
12514    }
12515
12516    pub fn toggle_inline_diagnostics(
12517        &mut self,
12518        _: &ToggleInlineDiagnostics,
12519        window: &mut Window,
12520        cx: &mut Context<'_, Editor>,
12521    ) {
12522        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12523        self.refresh_inline_diagnostics(false, window, cx);
12524    }
12525
12526    fn refresh_inline_diagnostics(
12527        &mut self,
12528        debounce: bool,
12529        window: &mut Window,
12530        cx: &mut Context<Self>,
12531    ) {
12532        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12533            self.inline_diagnostics_update = Task::ready(());
12534            self.inline_diagnostics.clear();
12535            return;
12536        }
12537
12538        let debounce_ms = ProjectSettings::get_global(cx)
12539            .diagnostics
12540            .inline
12541            .update_debounce_ms;
12542        let debounce = if debounce && debounce_ms > 0 {
12543            Some(Duration::from_millis(debounce_ms))
12544        } else {
12545            None
12546        };
12547        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12548            if let Some(debounce) = debounce {
12549                cx.background_executor().timer(debounce).await;
12550            }
12551            let Some(snapshot) = editor
12552                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12553                .ok()
12554            else {
12555                return;
12556            };
12557
12558            let new_inline_diagnostics = cx
12559                .background_spawn(async move {
12560                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12561                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12562                        let message = diagnostic_entry
12563                            .diagnostic
12564                            .message
12565                            .split_once('\n')
12566                            .map(|(line, _)| line)
12567                            .map(SharedString::new)
12568                            .unwrap_or_else(|| {
12569                                SharedString::from(diagnostic_entry.diagnostic.message)
12570                            });
12571                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12572                        let (Ok(i) | Err(i)) = inline_diagnostics
12573                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12574                        inline_diagnostics.insert(
12575                            i,
12576                            (
12577                                start_anchor,
12578                                InlineDiagnostic {
12579                                    message,
12580                                    group_id: diagnostic_entry.diagnostic.group_id,
12581                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12582                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12583                                    severity: diagnostic_entry.diagnostic.severity,
12584                                },
12585                            ),
12586                        );
12587                    }
12588                    inline_diagnostics
12589                })
12590                .await;
12591
12592            editor
12593                .update(&mut cx, |editor, cx| {
12594                    editor.inline_diagnostics = new_inline_diagnostics;
12595                    cx.notify();
12596                })
12597                .ok();
12598        });
12599    }
12600
12601    pub fn set_selections_from_remote(
12602        &mut self,
12603        selections: Vec<Selection<Anchor>>,
12604        pending_selection: Option<Selection<Anchor>>,
12605        window: &mut Window,
12606        cx: &mut Context<Self>,
12607    ) {
12608        let old_cursor_position = self.selections.newest_anchor().head();
12609        self.selections.change_with(cx, |s| {
12610            s.select_anchors(selections);
12611            if let Some(pending_selection) = pending_selection {
12612                s.set_pending(pending_selection, SelectMode::Character);
12613            } else {
12614                s.clear_pending();
12615            }
12616        });
12617        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12618    }
12619
12620    fn push_to_selection_history(&mut self) {
12621        self.selection_history.push(SelectionHistoryEntry {
12622            selections: self.selections.disjoint_anchors(),
12623            select_next_state: self.select_next_state.clone(),
12624            select_prev_state: self.select_prev_state.clone(),
12625            add_selections_state: self.add_selections_state.clone(),
12626        });
12627    }
12628
12629    pub fn transact(
12630        &mut self,
12631        window: &mut Window,
12632        cx: &mut Context<Self>,
12633        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12634    ) -> Option<TransactionId> {
12635        self.start_transaction_at(Instant::now(), window, cx);
12636        update(self, window, cx);
12637        self.end_transaction_at(Instant::now(), cx)
12638    }
12639
12640    pub fn start_transaction_at(
12641        &mut self,
12642        now: Instant,
12643        window: &mut Window,
12644        cx: &mut Context<Self>,
12645    ) {
12646        self.end_selection(window, cx);
12647        if let Some(tx_id) = self
12648            .buffer
12649            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12650        {
12651            self.selection_history
12652                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12653            cx.emit(EditorEvent::TransactionBegun {
12654                transaction_id: tx_id,
12655            })
12656        }
12657    }
12658
12659    pub fn end_transaction_at(
12660        &mut self,
12661        now: Instant,
12662        cx: &mut Context<Self>,
12663    ) -> Option<TransactionId> {
12664        if let Some(transaction_id) = self
12665            .buffer
12666            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12667        {
12668            if let Some((_, end_selections)) =
12669                self.selection_history.transaction_mut(transaction_id)
12670            {
12671                *end_selections = Some(self.selections.disjoint_anchors());
12672            } else {
12673                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12674            }
12675
12676            cx.emit(EditorEvent::Edited { transaction_id });
12677            Some(transaction_id)
12678        } else {
12679            None
12680        }
12681    }
12682
12683    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12684        if self.selection_mark_mode {
12685            self.change_selections(None, window, cx, |s| {
12686                s.move_with(|_, sel| {
12687                    sel.collapse_to(sel.head(), SelectionGoal::None);
12688                });
12689            })
12690        }
12691        self.selection_mark_mode = true;
12692        cx.notify();
12693    }
12694
12695    pub fn swap_selection_ends(
12696        &mut self,
12697        _: &actions::SwapSelectionEnds,
12698        window: &mut Window,
12699        cx: &mut Context<Self>,
12700    ) {
12701        self.change_selections(None, window, cx, |s| {
12702            s.move_with(|_, sel| {
12703                if sel.start != sel.end {
12704                    sel.reversed = !sel.reversed
12705                }
12706            });
12707        });
12708        self.request_autoscroll(Autoscroll::newest(), cx);
12709        cx.notify();
12710    }
12711
12712    pub fn toggle_fold(
12713        &mut self,
12714        _: &actions::ToggleFold,
12715        window: &mut Window,
12716        cx: &mut Context<Self>,
12717    ) {
12718        if self.is_singleton(cx) {
12719            let selection = self.selections.newest::<Point>(cx);
12720
12721            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12722            let range = if selection.is_empty() {
12723                let point = selection.head().to_display_point(&display_map);
12724                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12725                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12726                    .to_point(&display_map);
12727                start..end
12728            } else {
12729                selection.range()
12730            };
12731            if display_map.folds_in_range(range).next().is_some() {
12732                self.unfold_lines(&Default::default(), window, cx)
12733            } else {
12734                self.fold(&Default::default(), window, cx)
12735            }
12736        } else {
12737            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12738            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12739                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12740                .map(|(snapshot, _, _)| snapshot.remote_id())
12741                .collect();
12742
12743            for buffer_id in buffer_ids {
12744                if self.is_buffer_folded(buffer_id, cx) {
12745                    self.unfold_buffer(buffer_id, cx);
12746                } else {
12747                    self.fold_buffer(buffer_id, cx);
12748                }
12749            }
12750        }
12751    }
12752
12753    pub fn toggle_fold_recursive(
12754        &mut self,
12755        _: &actions::ToggleFoldRecursive,
12756        window: &mut Window,
12757        cx: &mut Context<Self>,
12758    ) {
12759        let selection = self.selections.newest::<Point>(cx);
12760
12761        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12762        let range = if selection.is_empty() {
12763            let point = selection.head().to_display_point(&display_map);
12764            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12765            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12766                .to_point(&display_map);
12767            start..end
12768        } else {
12769            selection.range()
12770        };
12771        if display_map.folds_in_range(range).next().is_some() {
12772            self.unfold_recursive(&Default::default(), window, cx)
12773        } else {
12774            self.fold_recursive(&Default::default(), window, cx)
12775        }
12776    }
12777
12778    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12779        if self.is_singleton(cx) {
12780            let mut to_fold = Vec::new();
12781            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12782            let selections = self.selections.all_adjusted(cx);
12783
12784            for selection in selections {
12785                let range = selection.range().sorted();
12786                let buffer_start_row = range.start.row;
12787
12788                if range.start.row != range.end.row {
12789                    let mut found = false;
12790                    let mut row = range.start.row;
12791                    while row <= range.end.row {
12792                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12793                        {
12794                            found = true;
12795                            row = crease.range().end.row + 1;
12796                            to_fold.push(crease);
12797                        } else {
12798                            row += 1
12799                        }
12800                    }
12801                    if found {
12802                        continue;
12803                    }
12804                }
12805
12806                for row in (0..=range.start.row).rev() {
12807                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12808                        if crease.range().end.row >= buffer_start_row {
12809                            to_fold.push(crease);
12810                            if row <= range.start.row {
12811                                break;
12812                            }
12813                        }
12814                    }
12815                }
12816            }
12817
12818            self.fold_creases(to_fold, true, window, cx);
12819        } else {
12820            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12821
12822            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12823                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12824                .map(|(snapshot, _, _)| snapshot.remote_id())
12825                .collect();
12826            for buffer_id in buffer_ids {
12827                self.fold_buffer(buffer_id, cx);
12828            }
12829        }
12830    }
12831
12832    fn fold_at_level(
12833        &mut self,
12834        fold_at: &FoldAtLevel,
12835        window: &mut Window,
12836        cx: &mut Context<Self>,
12837    ) {
12838        if !self.buffer.read(cx).is_singleton() {
12839            return;
12840        }
12841
12842        let fold_at_level = fold_at.0;
12843        let snapshot = self.buffer.read(cx).snapshot(cx);
12844        let mut to_fold = Vec::new();
12845        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12846
12847        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12848            while start_row < end_row {
12849                match self
12850                    .snapshot(window, cx)
12851                    .crease_for_buffer_row(MultiBufferRow(start_row))
12852                {
12853                    Some(crease) => {
12854                        let nested_start_row = crease.range().start.row + 1;
12855                        let nested_end_row = crease.range().end.row;
12856
12857                        if current_level < fold_at_level {
12858                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12859                        } else if current_level == fold_at_level {
12860                            to_fold.push(crease);
12861                        }
12862
12863                        start_row = nested_end_row + 1;
12864                    }
12865                    None => start_row += 1,
12866                }
12867            }
12868        }
12869
12870        self.fold_creases(to_fold, true, window, cx);
12871    }
12872
12873    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12874        if self.buffer.read(cx).is_singleton() {
12875            let mut fold_ranges = Vec::new();
12876            let snapshot = self.buffer.read(cx).snapshot(cx);
12877
12878            for row in 0..snapshot.max_row().0 {
12879                if let Some(foldable_range) = self
12880                    .snapshot(window, cx)
12881                    .crease_for_buffer_row(MultiBufferRow(row))
12882                {
12883                    fold_ranges.push(foldable_range);
12884                }
12885            }
12886
12887            self.fold_creases(fold_ranges, true, window, cx);
12888        } else {
12889            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12890                editor
12891                    .update_in(&mut cx, |editor, _, cx| {
12892                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12893                            editor.fold_buffer(buffer_id, cx);
12894                        }
12895                    })
12896                    .ok();
12897            });
12898        }
12899    }
12900
12901    pub fn fold_function_bodies(
12902        &mut self,
12903        _: &actions::FoldFunctionBodies,
12904        window: &mut Window,
12905        cx: &mut Context<Self>,
12906    ) {
12907        let snapshot = self.buffer.read(cx).snapshot(cx);
12908
12909        let ranges = snapshot
12910            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12911            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12912            .collect::<Vec<_>>();
12913
12914        let creases = ranges
12915            .into_iter()
12916            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12917            .collect();
12918
12919        self.fold_creases(creases, true, window, cx);
12920    }
12921
12922    pub fn fold_recursive(
12923        &mut self,
12924        _: &actions::FoldRecursive,
12925        window: &mut Window,
12926        cx: &mut Context<Self>,
12927    ) {
12928        let mut to_fold = Vec::new();
12929        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12930        let selections = self.selections.all_adjusted(cx);
12931
12932        for selection in selections {
12933            let range = selection.range().sorted();
12934            let buffer_start_row = range.start.row;
12935
12936            if range.start.row != range.end.row {
12937                let mut found = false;
12938                for row in range.start.row..=range.end.row {
12939                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12940                        found = true;
12941                        to_fold.push(crease);
12942                    }
12943                }
12944                if found {
12945                    continue;
12946                }
12947            }
12948
12949            for row in (0..=range.start.row).rev() {
12950                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12951                    if crease.range().end.row >= buffer_start_row {
12952                        to_fold.push(crease);
12953                    } else {
12954                        break;
12955                    }
12956                }
12957            }
12958        }
12959
12960        self.fold_creases(to_fold, true, window, cx);
12961    }
12962
12963    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12964        let buffer_row = fold_at.buffer_row;
12965        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12966
12967        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12968            let autoscroll = self
12969                .selections
12970                .all::<Point>(cx)
12971                .iter()
12972                .any(|selection| crease.range().overlaps(&selection.range()));
12973
12974            self.fold_creases(vec![crease], autoscroll, window, cx);
12975        }
12976    }
12977
12978    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12979        if self.is_singleton(cx) {
12980            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12981            let buffer = &display_map.buffer_snapshot;
12982            let selections = self.selections.all::<Point>(cx);
12983            let ranges = selections
12984                .iter()
12985                .map(|s| {
12986                    let range = s.display_range(&display_map).sorted();
12987                    let mut start = range.start.to_point(&display_map);
12988                    let mut end = range.end.to_point(&display_map);
12989                    start.column = 0;
12990                    end.column = buffer.line_len(MultiBufferRow(end.row));
12991                    start..end
12992                })
12993                .collect::<Vec<_>>();
12994
12995            self.unfold_ranges(&ranges, true, true, cx);
12996        } else {
12997            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12998            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12999                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
13000                .map(|(snapshot, _, _)| snapshot.remote_id())
13001                .collect();
13002            for buffer_id in buffer_ids {
13003                self.unfold_buffer(buffer_id, cx);
13004            }
13005        }
13006    }
13007
13008    pub fn unfold_recursive(
13009        &mut self,
13010        _: &UnfoldRecursive,
13011        _window: &mut Window,
13012        cx: &mut Context<Self>,
13013    ) {
13014        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13015        let selections = self.selections.all::<Point>(cx);
13016        let ranges = selections
13017            .iter()
13018            .map(|s| {
13019                let mut range = s.display_range(&display_map).sorted();
13020                *range.start.column_mut() = 0;
13021                *range.end.column_mut() = display_map.line_len(range.end.row());
13022                let start = range.start.to_point(&display_map);
13023                let end = range.end.to_point(&display_map);
13024                start..end
13025            })
13026            .collect::<Vec<_>>();
13027
13028        self.unfold_ranges(&ranges, true, true, cx);
13029    }
13030
13031    pub fn unfold_at(
13032        &mut self,
13033        unfold_at: &UnfoldAt,
13034        _window: &mut Window,
13035        cx: &mut Context<Self>,
13036    ) {
13037        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13038
13039        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13040            ..Point::new(
13041                unfold_at.buffer_row.0,
13042                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13043            );
13044
13045        let autoscroll = self
13046            .selections
13047            .all::<Point>(cx)
13048            .iter()
13049            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13050
13051        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13052    }
13053
13054    pub fn unfold_all(
13055        &mut self,
13056        _: &actions::UnfoldAll,
13057        _window: &mut Window,
13058        cx: &mut Context<Self>,
13059    ) {
13060        if self.buffer.read(cx).is_singleton() {
13061            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13062            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13063        } else {
13064            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13065                editor
13066                    .update(&mut cx, |editor, cx| {
13067                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13068                            editor.unfold_buffer(buffer_id, cx);
13069                        }
13070                    })
13071                    .ok();
13072            });
13073        }
13074    }
13075
13076    pub fn fold_selected_ranges(
13077        &mut self,
13078        _: &FoldSelectedRanges,
13079        window: &mut Window,
13080        cx: &mut Context<Self>,
13081    ) {
13082        let selections = self.selections.all::<Point>(cx);
13083        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13084        let line_mode = self.selections.line_mode;
13085        let ranges = selections
13086            .into_iter()
13087            .map(|s| {
13088                if line_mode {
13089                    let start = Point::new(s.start.row, 0);
13090                    let end = Point::new(
13091                        s.end.row,
13092                        display_map
13093                            .buffer_snapshot
13094                            .line_len(MultiBufferRow(s.end.row)),
13095                    );
13096                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13097                } else {
13098                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13099                }
13100            })
13101            .collect::<Vec<_>>();
13102        self.fold_creases(ranges, true, window, cx);
13103    }
13104
13105    pub fn fold_ranges<T: ToOffset + Clone>(
13106        &mut self,
13107        ranges: Vec<Range<T>>,
13108        auto_scroll: bool,
13109        window: &mut Window,
13110        cx: &mut Context<Self>,
13111    ) {
13112        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13113        let ranges = ranges
13114            .into_iter()
13115            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13116            .collect::<Vec<_>>();
13117        self.fold_creases(ranges, auto_scroll, window, cx);
13118    }
13119
13120    pub fn fold_creases<T: ToOffset + Clone>(
13121        &mut self,
13122        creases: Vec<Crease<T>>,
13123        auto_scroll: bool,
13124        window: &mut Window,
13125        cx: &mut Context<Self>,
13126    ) {
13127        if creases.is_empty() {
13128            return;
13129        }
13130
13131        let mut buffers_affected = HashSet::default();
13132        let multi_buffer = self.buffer().read(cx);
13133        for crease in &creases {
13134            if let Some((_, buffer, _)) =
13135                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13136            {
13137                buffers_affected.insert(buffer.read(cx).remote_id());
13138            };
13139        }
13140
13141        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13142
13143        if auto_scroll {
13144            self.request_autoscroll(Autoscroll::fit(), cx);
13145        }
13146
13147        cx.notify();
13148
13149        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13150            // Clear diagnostics block when folding a range that contains it.
13151            let snapshot = self.snapshot(window, cx);
13152            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13153                drop(snapshot);
13154                self.active_diagnostics = Some(active_diagnostics);
13155                self.dismiss_diagnostics(cx);
13156            } else {
13157                self.active_diagnostics = Some(active_diagnostics);
13158            }
13159        }
13160
13161        self.scrollbar_marker_state.dirty = true;
13162    }
13163
13164    /// Removes any folds whose ranges intersect any of the given ranges.
13165    pub fn unfold_ranges<T: ToOffset + Clone>(
13166        &mut self,
13167        ranges: &[Range<T>],
13168        inclusive: bool,
13169        auto_scroll: bool,
13170        cx: &mut Context<Self>,
13171    ) {
13172        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13173            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13174        });
13175    }
13176
13177    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13178        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13179            return;
13180        }
13181        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13182        self.display_map
13183            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13184        cx.emit(EditorEvent::BufferFoldToggled {
13185            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13186            folded: true,
13187        });
13188        cx.notify();
13189    }
13190
13191    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13192        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13193            return;
13194        }
13195        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13196        self.display_map.update(cx, |display_map, cx| {
13197            display_map.unfold_buffer(buffer_id, cx);
13198        });
13199        cx.emit(EditorEvent::BufferFoldToggled {
13200            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13201            folded: false,
13202        });
13203        cx.notify();
13204    }
13205
13206    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13207        self.display_map.read(cx).is_buffer_folded(buffer)
13208    }
13209
13210    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13211        self.display_map.read(cx).folded_buffers()
13212    }
13213
13214    /// Removes any folds with the given ranges.
13215    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13216        &mut self,
13217        ranges: &[Range<T>],
13218        type_id: TypeId,
13219        auto_scroll: bool,
13220        cx: &mut Context<Self>,
13221    ) {
13222        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13223            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13224        });
13225    }
13226
13227    fn remove_folds_with<T: ToOffset + Clone>(
13228        &mut self,
13229        ranges: &[Range<T>],
13230        auto_scroll: bool,
13231        cx: &mut Context<Self>,
13232        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13233    ) {
13234        if ranges.is_empty() {
13235            return;
13236        }
13237
13238        let mut buffers_affected = HashSet::default();
13239        let multi_buffer = self.buffer().read(cx);
13240        for range in ranges {
13241            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13242                buffers_affected.insert(buffer.read(cx).remote_id());
13243            };
13244        }
13245
13246        self.display_map.update(cx, update);
13247
13248        if auto_scroll {
13249            self.request_autoscroll(Autoscroll::fit(), cx);
13250        }
13251
13252        cx.notify();
13253        self.scrollbar_marker_state.dirty = true;
13254        self.active_indent_guides_state.dirty = true;
13255    }
13256
13257    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13258        self.display_map.read(cx).fold_placeholder.clone()
13259    }
13260
13261    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13262        self.buffer.update(cx, |buffer, cx| {
13263            buffer.set_all_diff_hunks_expanded(cx);
13264        });
13265    }
13266
13267    pub fn expand_all_diff_hunks(
13268        &mut self,
13269        _: &ExpandAllDiffHunks,
13270        _window: &mut Window,
13271        cx: &mut Context<Self>,
13272    ) {
13273        self.buffer.update(cx, |buffer, cx| {
13274            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13275        });
13276    }
13277
13278    pub fn toggle_selected_diff_hunks(
13279        &mut self,
13280        _: &ToggleSelectedDiffHunks,
13281        _window: &mut Window,
13282        cx: &mut Context<Self>,
13283    ) {
13284        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13285        self.toggle_diff_hunks_in_ranges(ranges, cx);
13286    }
13287
13288    pub fn diff_hunks_in_ranges<'a>(
13289        &'a self,
13290        ranges: &'a [Range<Anchor>],
13291        buffer: &'a MultiBufferSnapshot,
13292    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13293        ranges.iter().flat_map(move |range| {
13294            let end_excerpt_id = range.end.excerpt_id;
13295            let range = range.to_point(buffer);
13296            let mut peek_end = range.end;
13297            if range.end.row < buffer.max_row().0 {
13298                peek_end = Point::new(range.end.row + 1, 0);
13299            }
13300            buffer
13301                .diff_hunks_in_range(range.start..peek_end)
13302                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13303        })
13304    }
13305
13306    pub fn has_stageable_diff_hunks_in_ranges(
13307        &self,
13308        ranges: &[Range<Anchor>],
13309        snapshot: &MultiBufferSnapshot,
13310    ) -> bool {
13311        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13312        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
13313    }
13314
13315    pub fn toggle_staged_selected_diff_hunks(
13316        &mut self,
13317        _: &::git::ToggleStaged,
13318        _window: &mut Window,
13319        cx: &mut Context<Self>,
13320    ) {
13321        let snapshot = self.buffer.read(cx).snapshot(cx);
13322        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13323        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13324        self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
13325    }
13326
13327    pub fn stage_and_next(
13328        &mut self,
13329        _: &::git::StageAndNext,
13330        window: &mut Window,
13331        cx: &mut Context<Self>,
13332    ) {
13333        self.do_stage_or_unstage_and_next(true, window, cx);
13334    }
13335
13336    pub fn unstage_and_next(
13337        &mut self,
13338        _: &::git::UnstageAndNext,
13339        window: &mut Window,
13340        cx: &mut Context<Self>,
13341    ) {
13342        self.do_stage_or_unstage_and_next(false, window, cx);
13343    }
13344
13345    pub fn stage_or_unstage_diff_hunks(
13346        &mut self,
13347        stage: bool,
13348        ranges: &[Range<Anchor>],
13349        cx: &mut Context<Self>,
13350    ) {
13351        let snapshot = self.buffer.read(cx).snapshot(cx);
13352        let Some(project) = &self.project else {
13353            return;
13354        };
13355
13356        let chunk_by = self
13357            .diff_hunks_in_ranges(&ranges, &snapshot)
13358            .chunk_by(|hunk| hunk.buffer_id);
13359        for (buffer_id, hunks) in &chunk_by {
13360            Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
13361        }
13362    }
13363
13364    fn do_stage_or_unstage_and_next(
13365        &mut self,
13366        stage: bool,
13367        window: &mut Window,
13368        cx: &mut Context<Self>,
13369    ) {
13370        let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13371        if ranges.iter().any(|range| range.start != range.end) {
13372            self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13373            return;
13374        }
13375
13376        if !self.buffer().read(cx).is_singleton() {
13377            if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13378                if buffer.read(cx).is_empty() {
13379                    let buffer = buffer.read(cx);
13380                    let Some(file) = buffer.file() else {
13381                        return;
13382                    };
13383                    let project_path = project::ProjectPath {
13384                        worktree_id: file.worktree_id(cx),
13385                        path: file.path().clone(),
13386                    };
13387                    let Some(project) = self.project.as_ref() else {
13388                        return;
13389                    };
13390                    let project = project.read(cx);
13391
13392                    let Some(repo) = project.git_store().read(cx).active_repository() else {
13393                        return;
13394                    };
13395
13396                    repo.update(cx, |repo, cx| {
13397                        let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13398                            return;
13399                        };
13400                        let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13401                            return;
13402                        };
13403                        if stage && status.status == FileStatus::Untracked {
13404                            repo.stage_entries(vec![repo_path], cx)
13405                                .detach_and_log_err(cx);
13406                            return;
13407                        }
13408                    })
13409                }
13410                ranges = vec![multi_buffer::Anchor::range_in_buffer(
13411                    excerpt_id,
13412                    buffer.read(cx).remote_id(),
13413                    range,
13414                )];
13415                self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13416                let snapshot = self.buffer().read(cx).snapshot(cx);
13417                let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13418                if point.row < snapshot.max_row().0 {
13419                    point.row += 1;
13420                    point.column = 0;
13421                    point = snapshot.clip_point(point, Bias::Right);
13422                    self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13423                        s.select_ranges([point..point]);
13424                    })
13425                }
13426                return;
13427            }
13428        }
13429        self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13430        self.go_to_next_hunk(&Default::default(), window, cx);
13431    }
13432
13433    fn do_stage_or_unstage(
13434        project: &Entity<Project>,
13435        stage: bool,
13436        buffer_id: BufferId,
13437        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13438        snapshot: &MultiBufferSnapshot,
13439        cx: &mut Context<Self>,
13440    ) {
13441        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13442            log::debug!("no buffer for id");
13443            return;
13444        };
13445        let buffer_snapshot = buffer.read(cx).snapshot();
13446        let Some((repo, path)) = project
13447            .read(cx)
13448            .repository_and_path_for_buffer_id(buffer_id, cx)
13449        else {
13450            log::debug!("no git repo for buffer id");
13451            return;
13452        };
13453        let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13454            log::debug!("no diff for buffer id");
13455            return;
13456        };
13457        let Some(secondary_diff) = diff.secondary_diff() else {
13458            log::debug!("no secondary diff for buffer id");
13459            return;
13460        };
13461
13462        let edits = diff.secondary_edits_for_stage_or_unstage(
13463            stage,
13464            hunks.filter_map(|hunk| {
13465                if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13466                    return None;
13467                } else if !stage
13468                    && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13469                {
13470                    return None;
13471                }
13472                Some((
13473                    hunk.diff_base_byte_range.clone(),
13474                    hunk.secondary_diff_base_byte_range.clone(),
13475                    hunk.buffer_range.clone(),
13476                ))
13477            }),
13478            &buffer_snapshot,
13479        );
13480
13481        let Some(index_base) = secondary_diff
13482            .base_text()
13483            .map(|snapshot| snapshot.text.as_rope().clone())
13484        else {
13485            log::debug!("no index base");
13486            return;
13487        };
13488        let index_buffer = cx.new(|cx| {
13489            Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
13490        });
13491        let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
13492            index_buffer.edit(edits, None, cx);
13493            index_buffer.snapshot().as_rope().to_string()
13494        });
13495        let new_index_text = if new_index_text.is_empty()
13496            && !stage
13497            && (diff.is_single_insertion
13498                || buffer_snapshot
13499                    .file()
13500                    .map_or(false, |file| file.disk_state() == DiskState::New))
13501        {
13502            log::debug!("removing from index");
13503            None
13504        } else {
13505            Some(new_index_text)
13506        };
13507        let buffer_store = project.read(cx).buffer_store().clone();
13508        buffer_store
13509            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13510            .detach_and_log_err(cx);
13511
13512        cx.background_spawn(
13513            repo.read(cx)
13514                .set_index_text(&path, new_index_text)
13515                .log_err(),
13516        )
13517        .detach();
13518    }
13519
13520    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13521        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13522        self.buffer
13523            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13524    }
13525
13526    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13527        self.buffer.update(cx, |buffer, cx| {
13528            let ranges = vec![Anchor::min()..Anchor::max()];
13529            if !buffer.all_diff_hunks_expanded()
13530                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13531            {
13532                buffer.collapse_diff_hunks(ranges, cx);
13533                true
13534            } else {
13535                false
13536            }
13537        })
13538    }
13539
13540    fn toggle_diff_hunks_in_ranges(
13541        &mut self,
13542        ranges: Vec<Range<Anchor>>,
13543        cx: &mut Context<'_, Editor>,
13544    ) {
13545        self.buffer.update(cx, |buffer, cx| {
13546            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13547            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13548        })
13549    }
13550
13551    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13552        self.buffer.update(cx, |buffer, cx| {
13553            let snapshot = buffer.snapshot(cx);
13554            let excerpt_id = range.end.excerpt_id;
13555            let point_range = range.to_point(&snapshot);
13556            let expand = !buffer.single_hunk_is_expanded(range, cx);
13557            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13558        })
13559    }
13560
13561    pub(crate) fn apply_all_diff_hunks(
13562        &mut self,
13563        _: &ApplyAllDiffHunks,
13564        window: &mut Window,
13565        cx: &mut Context<Self>,
13566    ) {
13567        let buffers = self.buffer.read(cx).all_buffers();
13568        for branch_buffer in buffers {
13569            branch_buffer.update(cx, |branch_buffer, cx| {
13570                branch_buffer.merge_into_base(Vec::new(), cx);
13571            });
13572        }
13573
13574        if let Some(project) = self.project.clone() {
13575            self.save(true, project, window, cx).detach_and_log_err(cx);
13576        }
13577    }
13578
13579    pub(crate) fn apply_selected_diff_hunks(
13580        &mut self,
13581        _: &ApplyDiffHunk,
13582        window: &mut Window,
13583        cx: &mut Context<Self>,
13584    ) {
13585        let snapshot = self.snapshot(window, cx);
13586        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13587        let mut ranges_by_buffer = HashMap::default();
13588        self.transact(window, cx, |editor, _window, cx| {
13589            for hunk in hunks {
13590                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13591                    ranges_by_buffer
13592                        .entry(buffer.clone())
13593                        .or_insert_with(Vec::new)
13594                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13595                }
13596            }
13597
13598            for (buffer, ranges) in ranges_by_buffer {
13599                buffer.update(cx, |buffer, cx| {
13600                    buffer.merge_into_base(ranges, cx);
13601                });
13602            }
13603        });
13604
13605        if let Some(project) = self.project.clone() {
13606            self.save(true, project, window, cx).detach_and_log_err(cx);
13607        }
13608    }
13609
13610    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13611        if hovered != self.gutter_hovered {
13612            self.gutter_hovered = hovered;
13613            cx.notify();
13614        }
13615    }
13616
13617    pub fn insert_blocks(
13618        &mut self,
13619        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13620        autoscroll: Option<Autoscroll>,
13621        cx: &mut Context<Self>,
13622    ) -> Vec<CustomBlockId> {
13623        let blocks = self
13624            .display_map
13625            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13626        if let Some(autoscroll) = autoscroll {
13627            self.request_autoscroll(autoscroll, cx);
13628        }
13629        cx.notify();
13630        blocks
13631    }
13632
13633    pub fn resize_blocks(
13634        &mut self,
13635        heights: HashMap<CustomBlockId, u32>,
13636        autoscroll: Option<Autoscroll>,
13637        cx: &mut Context<Self>,
13638    ) {
13639        self.display_map
13640            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13641        if let Some(autoscroll) = autoscroll {
13642            self.request_autoscroll(autoscroll, cx);
13643        }
13644        cx.notify();
13645    }
13646
13647    pub fn replace_blocks(
13648        &mut self,
13649        renderers: HashMap<CustomBlockId, RenderBlock>,
13650        autoscroll: Option<Autoscroll>,
13651        cx: &mut Context<Self>,
13652    ) {
13653        self.display_map
13654            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13655        if let Some(autoscroll) = autoscroll {
13656            self.request_autoscroll(autoscroll, cx);
13657        }
13658        cx.notify();
13659    }
13660
13661    pub fn remove_blocks(
13662        &mut self,
13663        block_ids: HashSet<CustomBlockId>,
13664        autoscroll: Option<Autoscroll>,
13665        cx: &mut Context<Self>,
13666    ) {
13667        self.display_map.update(cx, |display_map, cx| {
13668            display_map.remove_blocks(block_ids, cx)
13669        });
13670        if let Some(autoscroll) = autoscroll {
13671            self.request_autoscroll(autoscroll, cx);
13672        }
13673        cx.notify();
13674    }
13675
13676    pub fn row_for_block(
13677        &self,
13678        block_id: CustomBlockId,
13679        cx: &mut Context<Self>,
13680    ) -> Option<DisplayRow> {
13681        self.display_map
13682            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13683    }
13684
13685    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13686        self.focused_block = Some(focused_block);
13687    }
13688
13689    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13690        self.focused_block.take()
13691    }
13692
13693    pub fn insert_creases(
13694        &mut self,
13695        creases: impl IntoIterator<Item = Crease<Anchor>>,
13696        cx: &mut Context<Self>,
13697    ) -> Vec<CreaseId> {
13698        self.display_map
13699            .update(cx, |map, cx| map.insert_creases(creases, cx))
13700    }
13701
13702    pub fn remove_creases(
13703        &mut self,
13704        ids: impl IntoIterator<Item = CreaseId>,
13705        cx: &mut Context<Self>,
13706    ) {
13707        self.display_map
13708            .update(cx, |map, cx| map.remove_creases(ids, cx));
13709    }
13710
13711    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13712        self.display_map
13713            .update(cx, |map, cx| map.snapshot(cx))
13714            .longest_row()
13715    }
13716
13717    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13718        self.display_map
13719            .update(cx, |map, cx| map.snapshot(cx))
13720            .max_point()
13721    }
13722
13723    pub fn text(&self, cx: &App) -> String {
13724        self.buffer.read(cx).read(cx).text()
13725    }
13726
13727    pub fn is_empty(&self, cx: &App) -> bool {
13728        self.buffer.read(cx).read(cx).is_empty()
13729    }
13730
13731    pub fn text_option(&self, cx: &App) -> Option<String> {
13732        let text = self.text(cx);
13733        let text = text.trim();
13734
13735        if text.is_empty() {
13736            return None;
13737        }
13738
13739        Some(text.to_string())
13740    }
13741
13742    pub fn set_text(
13743        &mut self,
13744        text: impl Into<Arc<str>>,
13745        window: &mut Window,
13746        cx: &mut Context<Self>,
13747    ) {
13748        self.transact(window, cx, |this, _, cx| {
13749            this.buffer
13750                .read(cx)
13751                .as_singleton()
13752                .expect("you can only call set_text on editors for singleton buffers")
13753                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13754        });
13755    }
13756
13757    pub fn display_text(&self, cx: &mut App) -> String {
13758        self.display_map
13759            .update(cx, |map, cx| map.snapshot(cx))
13760            .text()
13761    }
13762
13763    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13764        let mut wrap_guides = smallvec::smallvec![];
13765
13766        if self.show_wrap_guides == Some(false) {
13767            return wrap_guides;
13768        }
13769
13770        let settings = self.buffer.read(cx).settings_at(0, cx);
13771        if settings.show_wrap_guides {
13772            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13773                wrap_guides.push((soft_wrap as usize, true));
13774            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13775                wrap_guides.push((soft_wrap as usize, true));
13776            }
13777            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13778        }
13779
13780        wrap_guides
13781    }
13782
13783    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13784        let settings = self.buffer.read(cx).settings_at(0, cx);
13785        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13786        match mode {
13787            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13788                SoftWrap::None
13789            }
13790            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13791            language_settings::SoftWrap::PreferredLineLength => {
13792                SoftWrap::Column(settings.preferred_line_length)
13793            }
13794            language_settings::SoftWrap::Bounded => {
13795                SoftWrap::Bounded(settings.preferred_line_length)
13796            }
13797        }
13798    }
13799
13800    pub fn set_soft_wrap_mode(
13801        &mut self,
13802        mode: language_settings::SoftWrap,
13803
13804        cx: &mut Context<Self>,
13805    ) {
13806        self.soft_wrap_mode_override = Some(mode);
13807        cx.notify();
13808    }
13809
13810    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13811        self.text_style_refinement = Some(style);
13812    }
13813
13814    /// called by the Element so we know what style we were most recently rendered with.
13815    pub(crate) fn set_style(
13816        &mut self,
13817        style: EditorStyle,
13818        window: &mut Window,
13819        cx: &mut Context<Self>,
13820    ) {
13821        let rem_size = window.rem_size();
13822        self.display_map.update(cx, |map, cx| {
13823            map.set_font(
13824                style.text.font(),
13825                style.text.font_size.to_pixels(rem_size),
13826                cx,
13827            )
13828        });
13829        self.style = Some(style);
13830    }
13831
13832    pub fn style(&self) -> Option<&EditorStyle> {
13833        self.style.as_ref()
13834    }
13835
13836    // Called by the element. This method is not designed to be called outside of the editor
13837    // element's layout code because it does not notify when rewrapping is computed synchronously.
13838    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13839        self.display_map
13840            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13841    }
13842
13843    pub fn set_soft_wrap(&mut self) {
13844        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13845    }
13846
13847    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13848        if self.soft_wrap_mode_override.is_some() {
13849            self.soft_wrap_mode_override.take();
13850        } else {
13851            let soft_wrap = match self.soft_wrap_mode(cx) {
13852                SoftWrap::GitDiff => return,
13853                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13854                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13855                    language_settings::SoftWrap::None
13856                }
13857            };
13858            self.soft_wrap_mode_override = Some(soft_wrap);
13859        }
13860        cx.notify();
13861    }
13862
13863    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13864        let Some(workspace) = self.workspace() else {
13865            return;
13866        };
13867        let fs = workspace.read(cx).app_state().fs.clone();
13868        let current_show = TabBarSettings::get_global(cx).show;
13869        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13870            setting.show = Some(!current_show);
13871        });
13872    }
13873
13874    pub fn toggle_indent_guides(
13875        &mut self,
13876        _: &ToggleIndentGuides,
13877        _: &mut Window,
13878        cx: &mut Context<Self>,
13879    ) {
13880        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13881            self.buffer
13882                .read(cx)
13883                .settings_at(0, cx)
13884                .indent_guides
13885                .enabled
13886        });
13887        self.show_indent_guides = Some(!currently_enabled);
13888        cx.notify();
13889    }
13890
13891    fn should_show_indent_guides(&self) -> Option<bool> {
13892        self.show_indent_guides
13893    }
13894
13895    pub fn toggle_line_numbers(
13896        &mut self,
13897        _: &ToggleLineNumbers,
13898        _: &mut Window,
13899        cx: &mut Context<Self>,
13900    ) {
13901        let mut editor_settings = EditorSettings::get_global(cx).clone();
13902        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13903        EditorSettings::override_global(editor_settings, cx);
13904    }
13905
13906    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13907        self.use_relative_line_numbers
13908            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13909    }
13910
13911    pub fn toggle_relative_line_numbers(
13912        &mut self,
13913        _: &ToggleRelativeLineNumbers,
13914        _: &mut Window,
13915        cx: &mut Context<Self>,
13916    ) {
13917        let is_relative = self.should_use_relative_line_numbers(cx);
13918        self.set_relative_line_number(Some(!is_relative), cx)
13919    }
13920
13921    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13922        self.use_relative_line_numbers = is_relative;
13923        cx.notify();
13924    }
13925
13926    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13927        self.show_gutter = show_gutter;
13928        cx.notify();
13929    }
13930
13931    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13932        self.show_scrollbars = show_scrollbars;
13933        cx.notify();
13934    }
13935
13936    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13937        self.show_line_numbers = Some(show_line_numbers);
13938        cx.notify();
13939    }
13940
13941    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13942        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13943        cx.notify();
13944    }
13945
13946    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13947        self.show_code_actions = Some(show_code_actions);
13948        cx.notify();
13949    }
13950
13951    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13952        self.show_runnables = Some(show_runnables);
13953        cx.notify();
13954    }
13955
13956    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13957        if self.display_map.read(cx).masked != masked {
13958            self.display_map.update(cx, |map, _| map.masked = masked);
13959        }
13960        cx.notify()
13961    }
13962
13963    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13964        self.show_wrap_guides = Some(show_wrap_guides);
13965        cx.notify();
13966    }
13967
13968    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13969        self.show_indent_guides = Some(show_indent_guides);
13970        cx.notify();
13971    }
13972
13973    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13974        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13975            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13976                if let Some(dir) = file.abs_path(cx).parent() {
13977                    return Some(dir.to_owned());
13978                }
13979            }
13980
13981            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13982                return Some(project_path.path.to_path_buf());
13983            }
13984        }
13985
13986        None
13987    }
13988
13989    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13990        self.active_excerpt(cx)?
13991            .1
13992            .read(cx)
13993            .file()
13994            .and_then(|f| f.as_local())
13995    }
13996
13997    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13998        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13999            let buffer = buffer.read(cx);
14000            if let Some(project_path) = buffer.project_path(cx) {
14001                let project = self.project.as_ref()?.read(cx);
14002                project.absolute_path(&project_path, cx)
14003            } else {
14004                buffer
14005                    .file()
14006                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14007            }
14008        })
14009    }
14010
14011    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14012        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14013            let project_path = buffer.read(cx).project_path(cx)?;
14014            let project = self.project.as_ref()?.read(cx);
14015            let entry = project.entry_for_path(&project_path, cx)?;
14016            let path = entry.path.to_path_buf();
14017            Some(path)
14018        })
14019    }
14020
14021    pub fn reveal_in_finder(
14022        &mut self,
14023        _: &RevealInFileManager,
14024        _window: &mut Window,
14025        cx: &mut Context<Self>,
14026    ) {
14027        if let Some(target) = self.target_file(cx) {
14028            cx.reveal_path(&target.abs_path(cx));
14029        }
14030    }
14031
14032    pub fn copy_path(
14033        &mut self,
14034        _: &zed_actions::workspace::CopyPath,
14035        _window: &mut Window,
14036        cx: &mut Context<Self>,
14037    ) {
14038        if let Some(path) = self.target_file_abs_path(cx) {
14039            if let Some(path) = path.to_str() {
14040                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14041            }
14042        }
14043    }
14044
14045    pub fn copy_relative_path(
14046        &mut self,
14047        _: &zed_actions::workspace::CopyRelativePath,
14048        _window: &mut Window,
14049        cx: &mut Context<Self>,
14050    ) {
14051        if let Some(path) = self.target_file_path(cx) {
14052            if let Some(path) = path.to_str() {
14053                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14054            }
14055        }
14056    }
14057
14058    pub fn copy_file_name_without_extension(
14059        &mut self,
14060        _: &CopyFileNameWithoutExtension,
14061        _: &mut Window,
14062        cx: &mut Context<Self>,
14063    ) {
14064        if let Some(file) = self.target_file(cx) {
14065            if let Some(file_stem) = file.path().file_stem() {
14066                if let Some(name) = file_stem.to_str() {
14067                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14068                }
14069            }
14070        }
14071    }
14072
14073    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14074        if let Some(file) = self.target_file(cx) {
14075            if let Some(file_name) = file.path().file_name() {
14076                if let Some(name) = file_name.to_str() {
14077                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14078                }
14079            }
14080        }
14081    }
14082
14083    pub fn toggle_git_blame(
14084        &mut self,
14085        _: &ToggleGitBlame,
14086        window: &mut Window,
14087        cx: &mut Context<Self>,
14088    ) {
14089        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14090
14091        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14092            self.start_git_blame(true, window, cx);
14093        }
14094
14095        cx.notify();
14096    }
14097
14098    pub fn toggle_git_blame_inline(
14099        &mut self,
14100        _: &ToggleGitBlameInline,
14101        window: &mut Window,
14102        cx: &mut Context<Self>,
14103    ) {
14104        self.toggle_git_blame_inline_internal(true, window, cx);
14105        cx.notify();
14106    }
14107
14108    pub fn git_blame_inline_enabled(&self) -> bool {
14109        self.git_blame_inline_enabled
14110    }
14111
14112    pub fn toggle_selection_menu(
14113        &mut self,
14114        _: &ToggleSelectionMenu,
14115        _: &mut Window,
14116        cx: &mut Context<Self>,
14117    ) {
14118        self.show_selection_menu = self
14119            .show_selection_menu
14120            .map(|show_selections_menu| !show_selections_menu)
14121            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14122
14123        cx.notify();
14124    }
14125
14126    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14127        self.show_selection_menu
14128            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14129    }
14130
14131    fn start_git_blame(
14132        &mut self,
14133        user_triggered: bool,
14134        window: &mut Window,
14135        cx: &mut Context<Self>,
14136    ) {
14137        if let Some(project) = self.project.as_ref() {
14138            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14139                return;
14140            };
14141
14142            if buffer.read(cx).file().is_none() {
14143                return;
14144            }
14145
14146            let focused = self.focus_handle(cx).contains_focused(window, cx);
14147
14148            let project = project.clone();
14149            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14150            self.blame_subscription =
14151                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14152            self.blame = Some(blame);
14153        }
14154    }
14155
14156    fn toggle_git_blame_inline_internal(
14157        &mut self,
14158        user_triggered: bool,
14159        window: &mut Window,
14160        cx: &mut Context<Self>,
14161    ) {
14162        if self.git_blame_inline_enabled {
14163            self.git_blame_inline_enabled = false;
14164            self.show_git_blame_inline = false;
14165            self.show_git_blame_inline_delay_task.take();
14166        } else {
14167            self.git_blame_inline_enabled = true;
14168            self.start_git_blame_inline(user_triggered, window, cx);
14169        }
14170
14171        cx.notify();
14172    }
14173
14174    fn start_git_blame_inline(
14175        &mut self,
14176        user_triggered: bool,
14177        window: &mut Window,
14178        cx: &mut Context<Self>,
14179    ) {
14180        self.start_git_blame(user_triggered, window, cx);
14181
14182        if ProjectSettings::get_global(cx)
14183            .git
14184            .inline_blame_delay()
14185            .is_some()
14186        {
14187            self.start_inline_blame_timer(window, cx);
14188        } else {
14189            self.show_git_blame_inline = true
14190        }
14191    }
14192
14193    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14194        self.blame.as_ref()
14195    }
14196
14197    pub fn show_git_blame_gutter(&self) -> bool {
14198        self.show_git_blame_gutter
14199    }
14200
14201    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14202        self.show_git_blame_gutter && self.has_blame_entries(cx)
14203    }
14204
14205    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14206        self.show_git_blame_inline
14207            && (self.focus_handle.is_focused(window)
14208                || self
14209                    .git_blame_inline_tooltip
14210                    .as_ref()
14211                    .and_then(|t| t.upgrade())
14212                    .is_some())
14213            && !self.newest_selection_head_on_empty_line(cx)
14214            && self.has_blame_entries(cx)
14215    }
14216
14217    fn has_blame_entries(&self, cx: &App) -> bool {
14218        self.blame()
14219            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14220    }
14221
14222    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14223        let cursor_anchor = self.selections.newest_anchor().head();
14224
14225        let snapshot = self.buffer.read(cx).snapshot(cx);
14226        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14227
14228        snapshot.line_len(buffer_row) == 0
14229    }
14230
14231    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14232        let buffer_and_selection = maybe!({
14233            let selection = self.selections.newest::<Point>(cx);
14234            let selection_range = selection.range();
14235
14236            let multi_buffer = self.buffer().read(cx);
14237            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14238            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14239
14240            let (buffer, range, _) = if selection.reversed {
14241                buffer_ranges.first()
14242            } else {
14243                buffer_ranges.last()
14244            }?;
14245
14246            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14247                ..text::ToPoint::to_point(&range.end, &buffer).row;
14248            Some((
14249                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14250                selection,
14251            ))
14252        });
14253
14254        let Some((buffer, selection)) = buffer_and_selection else {
14255            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14256        };
14257
14258        let Some(project) = self.project.as_ref() else {
14259            return Task::ready(Err(anyhow!("editor does not have project")));
14260        };
14261
14262        project.update(cx, |project, cx| {
14263            project.get_permalink_to_line(&buffer, selection, cx)
14264        })
14265    }
14266
14267    pub fn copy_permalink_to_line(
14268        &mut self,
14269        _: &CopyPermalinkToLine,
14270        window: &mut Window,
14271        cx: &mut Context<Self>,
14272    ) {
14273        let permalink_task = self.get_permalink_to_line(cx);
14274        let workspace = self.workspace();
14275
14276        cx.spawn_in(window, |_, mut cx| async move {
14277            match permalink_task.await {
14278                Ok(permalink) => {
14279                    cx.update(|_, cx| {
14280                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14281                    })
14282                    .ok();
14283                }
14284                Err(err) => {
14285                    let message = format!("Failed to copy permalink: {err}");
14286
14287                    Err::<(), anyhow::Error>(err).log_err();
14288
14289                    if let Some(workspace) = workspace {
14290                        workspace
14291                            .update_in(&mut cx, |workspace, _, cx| {
14292                                struct CopyPermalinkToLine;
14293
14294                                workspace.show_toast(
14295                                    Toast::new(
14296                                        NotificationId::unique::<CopyPermalinkToLine>(),
14297                                        message,
14298                                    ),
14299                                    cx,
14300                                )
14301                            })
14302                            .ok();
14303                    }
14304                }
14305            }
14306        })
14307        .detach();
14308    }
14309
14310    pub fn copy_file_location(
14311        &mut self,
14312        _: &CopyFileLocation,
14313        _: &mut Window,
14314        cx: &mut Context<Self>,
14315    ) {
14316        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14317        if let Some(file) = self.target_file(cx) {
14318            if let Some(path) = file.path().to_str() {
14319                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14320            }
14321        }
14322    }
14323
14324    pub fn open_permalink_to_line(
14325        &mut self,
14326        _: &OpenPermalinkToLine,
14327        window: &mut Window,
14328        cx: &mut Context<Self>,
14329    ) {
14330        let permalink_task = self.get_permalink_to_line(cx);
14331        let workspace = self.workspace();
14332
14333        cx.spawn_in(window, |_, mut cx| async move {
14334            match permalink_task.await {
14335                Ok(permalink) => {
14336                    cx.update(|_, cx| {
14337                        cx.open_url(permalink.as_ref());
14338                    })
14339                    .ok();
14340                }
14341                Err(err) => {
14342                    let message = format!("Failed to open permalink: {err}");
14343
14344                    Err::<(), anyhow::Error>(err).log_err();
14345
14346                    if let Some(workspace) = workspace {
14347                        workspace
14348                            .update(&mut cx, |workspace, cx| {
14349                                struct OpenPermalinkToLine;
14350
14351                                workspace.show_toast(
14352                                    Toast::new(
14353                                        NotificationId::unique::<OpenPermalinkToLine>(),
14354                                        message,
14355                                    ),
14356                                    cx,
14357                                )
14358                            })
14359                            .ok();
14360                    }
14361                }
14362            }
14363        })
14364        .detach();
14365    }
14366
14367    pub fn insert_uuid_v4(
14368        &mut self,
14369        _: &InsertUuidV4,
14370        window: &mut Window,
14371        cx: &mut Context<Self>,
14372    ) {
14373        self.insert_uuid(UuidVersion::V4, window, cx);
14374    }
14375
14376    pub fn insert_uuid_v7(
14377        &mut self,
14378        _: &InsertUuidV7,
14379        window: &mut Window,
14380        cx: &mut Context<Self>,
14381    ) {
14382        self.insert_uuid(UuidVersion::V7, window, cx);
14383    }
14384
14385    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14386        self.transact(window, cx, |this, window, cx| {
14387            let edits = this
14388                .selections
14389                .all::<Point>(cx)
14390                .into_iter()
14391                .map(|selection| {
14392                    let uuid = match version {
14393                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14394                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14395                    };
14396
14397                    (selection.range(), uuid.to_string())
14398                });
14399            this.edit(edits, cx);
14400            this.refresh_inline_completion(true, false, window, cx);
14401        });
14402    }
14403
14404    pub fn open_selections_in_multibuffer(
14405        &mut self,
14406        _: &OpenSelectionsInMultibuffer,
14407        window: &mut Window,
14408        cx: &mut Context<Self>,
14409    ) {
14410        let multibuffer = self.buffer.read(cx);
14411
14412        let Some(buffer) = multibuffer.as_singleton() else {
14413            return;
14414        };
14415
14416        let Some(workspace) = self.workspace() else {
14417            return;
14418        };
14419
14420        let locations = self
14421            .selections
14422            .disjoint_anchors()
14423            .iter()
14424            .map(|range| Location {
14425                buffer: buffer.clone(),
14426                range: range.start.text_anchor..range.end.text_anchor,
14427            })
14428            .collect::<Vec<_>>();
14429
14430        let title = multibuffer.title(cx).to_string();
14431
14432        cx.spawn_in(window, |_, mut cx| async move {
14433            workspace.update_in(&mut cx, |workspace, window, cx| {
14434                Self::open_locations_in_multibuffer(
14435                    workspace,
14436                    locations,
14437                    format!("Selections for '{title}'"),
14438                    false,
14439                    MultibufferSelectionMode::All,
14440                    window,
14441                    cx,
14442                );
14443            })
14444        })
14445        .detach();
14446    }
14447
14448    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14449    /// last highlight added will be used.
14450    ///
14451    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14452    pub fn highlight_rows<T: 'static>(
14453        &mut self,
14454        range: Range<Anchor>,
14455        color: Hsla,
14456        should_autoscroll: bool,
14457        cx: &mut Context<Self>,
14458    ) {
14459        let snapshot = self.buffer().read(cx).snapshot(cx);
14460        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14461        let ix = row_highlights.binary_search_by(|highlight| {
14462            Ordering::Equal
14463                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14464                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14465        });
14466
14467        if let Err(mut ix) = ix {
14468            let index = post_inc(&mut self.highlight_order);
14469
14470            // If this range intersects with the preceding highlight, then merge it with
14471            // the preceding highlight. Otherwise insert a new highlight.
14472            let mut merged = false;
14473            if ix > 0 {
14474                let prev_highlight = &mut row_highlights[ix - 1];
14475                if prev_highlight
14476                    .range
14477                    .end
14478                    .cmp(&range.start, &snapshot)
14479                    .is_ge()
14480                {
14481                    ix -= 1;
14482                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14483                        prev_highlight.range.end = range.end;
14484                    }
14485                    merged = true;
14486                    prev_highlight.index = index;
14487                    prev_highlight.color = color;
14488                    prev_highlight.should_autoscroll = should_autoscroll;
14489                }
14490            }
14491
14492            if !merged {
14493                row_highlights.insert(
14494                    ix,
14495                    RowHighlight {
14496                        range: range.clone(),
14497                        index,
14498                        color,
14499                        should_autoscroll,
14500                    },
14501                );
14502            }
14503
14504            // If any of the following highlights intersect with this one, merge them.
14505            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14506                let highlight = &row_highlights[ix];
14507                if next_highlight
14508                    .range
14509                    .start
14510                    .cmp(&highlight.range.end, &snapshot)
14511                    .is_le()
14512                {
14513                    if next_highlight
14514                        .range
14515                        .end
14516                        .cmp(&highlight.range.end, &snapshot)
14517                        .is_gt()
14518                    {
14519                        row_highlights[ix].range.end = next_highlight.range.end;
14520                    }
14521                    row_highlights.remove(ix + 1);
14522                } else {
14523                    break;
14524                }
14525            }
14526        }
14527    }
14528
14529    /// Remove any highlighted row ranges of the given type that intersect the
14530    /// given ranges.
14531    pub fn remove_highlighted_rows<T: 'static>(
14532        &mut self,
14533        ranges_to_remove: Vec<Range<Anchor>>,
14534        cx: &mut Context<Self>,
14535    ) {
14536        let snapshot = self.buffer().read(cx).snapshot(cx);
14537        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14538        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14539        row_highlights.retain(|highlight| {
14540            while let Some(range_to_remove) = ranges_to_remove.peek() {
14541                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14542                    Ordering::Less | Ordering::Equal => {
14543                        ranges_to_remove.next();
14544                    }
14545                    Ordering::Greater => {
14546                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14547                            Ordering::Less | Ordering::Equal => {
14548                                return false;
14549                            }
14550                            Ordering::Greater => break,
14551                        }
14552                    }
14553                }
14554            }
14555
14556            true
14557        })
14558    }
14559
14560    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14561    pub fn clear_row_highlights<T: 'static>(&mut self) {
14562        self.highlighted_rows.remove(&TypeId::of::<T>());
14563    }
14564
14565    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14566    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14567        self.highlighted_rows
14568            .get(&TypeId::of::<T>())
14569            .map_or(&[] as &[_], |vec| vec.as_slice())
14570            .iter()
14571            .map(|highlight| (highlight.range.clone(), highlight.color))
14572    }
14573
14574    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14575    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14576    /// Allows to ignore certain kinds of highlights.
14577    pub fn highlighted_display_rows(
14578        &self,
14579        window: &mut Window,
14580        cx: &mut App,
14581    ) -> BTreeMap<DisplayRow, Background> {
14582        let snapshot = self.snapshot(window, cx);
14583        let mut used_highlight_orders = HashMap::default();
14584        self.highlighted_rows
14585            .iter()
14586            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14587            .fold(
14588                BTreeMap::<DisplayRow, Background>::new(),
14589                |mut unique_rows, highlight| {
14590                    let start = highlight.range.start.to_display_point(&snapshot);
14591                    let end = highlight.range.end.to_display_point(&snapshot);
14592                    let start_row = start.row().0;
14593                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14594                        && end.column() == 0
14595                    {
14596                        end.row().0.saturating_sub(1)
14597                    } else {
14598                        end.row().0
14599                    };
14600                    for row in start_row..=end_row {
14601                        let used_index =
14602                            used_highlight_orders.entry(row).or_insert(highlight.index);
14603                        if highlight.index >= *used_index {
14604                            *used_index = highlight.index;
14605                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14606                        }
14607                    }
14608                    unique_rows
14609                },
14610            )
14611    }
14612
14613    pub fn highlighted_display_row_for_autoscroll(
14614        &self,
14615        snapshot: &DisplaySnapshot,
14616    ) -> Option<DisplayRow> {
14617        self.highlighted_rows
14618            .values()
14619            .flat_map(|highlighted_rows| highlighted_rows.iter())
14620            .filter_map(|highlight| {
14621                if highlight.should_autoscroll {
14622                    Some(highlight.range.start.to_display_point(snapshot).row())
14623                } else {
14624                    None
14625                }
14626            })
14627            .min()
14628    }
14629
14630    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14631        self.highlight_background::<SearchWithinRange>(
14632            ranges,
14633            |colors| colors.editor_document_highlight_read_background,
14634            cx,
14635        )
14636    }
14637
14638    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14639        self.breadcrumb_header = Some(new_header);
14640    }
14641
14642    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14643        self.clear_background_highlights::<SearchWithinRange>(cx);
14644    }
14645
14646    pub fn highlight_background<T: 'static>(
14647        &mut self,
14648        ranges: &[Range<Anchor>],
14649        color_fetcher: fn(&ThemeColors) -> Hsla,
14650        cx: &mut Context<Self>,
14651    ) {
14652        self.background_highlights
14653            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14654        self.scrollbar_marker_state.dirty = true;
14655        cx.notify();
14656    }
14657
14658    pub fn clear_background_highlights<T: 'static>(
14659        &mut self,
14660        cx: &mut Context<Self>,
14661    ) -> Option<BackgroundHighlight> {
14662        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14663        if !text_highlights.1.is_empty() {
14664            self.scrollbar_marker_state.dirty = true;
14665            cx.notify();
14666        }
14667        Some(text_highlights)
14668    }
14669
14670    pub fn highlight_gutter<T: 'static>(
14671        &mut self,
14672        ranges: &[Range<Anchor>],
14673        color_fetcher: fn(&App) -> Hsla,
14674        cx: &mut Context<Self>,
14675    ) {
14676        self.gutter_highlights
14677            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14678        cx.notify();
14679    }
14680
14681    pub fn clear_gutter_highlights<T: 'static>(
14682        &mut self,
14683        cx: &mut Context<Self>,
14684    ) -> Option<GutterHighlight> {
14685        cx.notify();
14686        self.gutter_highlights.remove(&TypeId::of::<T>())
14687    }
14688
14689    #[cfg(feature = "test-support")]
14690    pub fn all_text_background_highlights(
14691        &self,
14692        window: &mut Window,
14693        cx: &mut Context<Self>,
14694    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14695        let snapshot = self.snapshot(window, cx);
14696        let buffer = &snapshot.buffer_snapshot;
14697        let start = buffer.anchor_before(0);
14698        let end = buffer.anchor_after(buffer.len());
14699        let theme = cx.theme().colors();
14700        self.background_highlights_in_range(start..end, &snapshot, theme)
14701    }
14702
14703    #[cfg(feature = "test-support")]
14704    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14705        let snapshot = self.buffer().read(cx).snapshot(cx);
14706
14707        let highlights = self
14708            .background_highlights
14709            .get(&TypeId::of::<items::BufferSearchHighlights>());
14710
14711        if let Some((_color, ranges)) = highlights {
14712            ranges
14713                .iter()
14714                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14715                .collect_vec()
14716        } else {
14717            vec![]
14718        }
14719    }
14720
14721    fn document_highlights_for_position<'a>(
14722        &'a self,
14723        position: Anchor,
14724        buffer: &'a MultiBufferSnapshot,
14725    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14726        let read_highlights = self
14727            .background_highlights
14728            .get(&TypeId::of::<DocumentHighlightRead>())
14729            .map(|h| &h.1);
14730        let write_highlights = self
14731            .background_highlights
14732            .get(&TypeId::of::<DocumentHighlightWrite>())
14733            .map(|h| &h.1);
14734        let left_position = position.bias_left(buffer);
14735        let right_position = position.bias_right(buffer);
14736        read_highlights
14737            .into_iter()
14738            .chain(write_highlights)
14739            .flat_map(move |ranges| {
14740                let start_ix = match ranges.binary_search_by(|probe| {
14741                    let cmp = probe.end.cmp(&left_position, buffer);
14742                    if cmp.is_ge() {
14743                        Ordering::Greater
14744                    } else {
14745                        Ordering::Less
14746                    }
14747                }) {
14748                    Ok(i) | Err(i) => i,
14749                };
14750
14751                ranges[start_ix..]
14752                    .iter()
14753                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14754            })
14755    }
14756
14757    pub fn has_background_highlights<T: 'static>(&self) -> bool {
14758        self.background_highlights
14759            .get(&TypeId::of::<T>())
14760            .map_or(false, |(_, highlights)| !highlights.is_empty())
14761    }
14762
14763    pub fn background_highlights_in_range(
14764        &self,
14765        search_range: Range<Anchor>,
14766        display_snapshot: &DisplaySnapshot,
14767        theme: &ThemeColors,
14768    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14769        let mut results = Vec::new();
14770        for (color_fetcher, ranges) in self.background_highlights.values() {
14771            let color = color_fetcher(theme);
14772            let start_ix = match ranges.binary_search_by(|probe| {
14773                let cmp = probe
14774                    .end
14775                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14776                if cmp.is_gt() {
14777                    Ordering::Greater
14778                } else {
14779                    Ordering::Less
14780                }
14781            }) {
14782                Ok(i) | Err(i) => i,
14783            };
14784            for range in &ranges[start_ix..] {
14785                if range
14786                    .start
14787                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14788                    .is_ge()
14789                {
14790                    break;
14791                }
14792
14793                let start = range.start.to_display_point(display_snapshot);
14794                let end = range.end.to_display_point(display_snapshot);
14795                results.push((start..end, color))
14796            }
14797        }
14798        results
14799    }
14800
14801    pub fn background_highlight_row_ranges<T: 'static>(
14802        &self,
14803        search_range: Range<Anchor>,
14804        display_snapshot: &DisplaySnapshot,
14805        count: usize,
14806    ) -> Vec<RangeInclusive<DisplayPoint>> {
14807        let mut results = Vec::new();
14808        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14809            return vec![];
14810        };
14811
14812        let start_ix = match ranges.binary_search_by(|probe| {
14813            let cmp = probe
14814                .end
14815                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14816            if cmp.is_gt() {
14817                Ordering::Greater
14818            } else {
14819                Ordering::Less
14820            }
14821        }) {
14822            Ok(i) | Err(i) => i,
14823        };
14824        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14825            if let (Some(start_display), Some(end_display)) = (start, end) {
14826                results.push(
14827                    start_display.to_display_point(display_snapshot)
14828                        ..=end_display.to_display_point(display_snapshot),
14829                );
14830            }
14831        };
14832        let mut start_row: Option<Point> = None;
14833        let mut end_row: Option<Point> = None;
14834        if ranges.len() > count {
14835            return Vec::new();
14836        }
14837        for range in &ranges[start_ix..] {
14838            if range
14839                .start
14840                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14841                .is_ge()
14842            {
14843                break;
14844            }
14845            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14846            if let Some(current_row) = &end_row {
14847                if end.row == current_row.row {
14848                    continue;
14849                }
14850            }
14851            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14852            if start_row.is_none() {
14853                assert_eq!(end_row, None);
14854                start_row = Some(start);
14855                end_row = Some(end);
14856                continue;
14857            }
14858            if let Some(current_end) = end_row.as_mut() {
14859                if start.row > current_end.row + 1 {
14860                    push_region(start_row, end_row);
14861                    start_row = Some(start);
14862                    end_row = Some(end);
14863                } else {
14864                    // Merge two hunks.
14865                    *current_end = end;
14866                }
14867            } else {
14868                unreachable!();
14869            }
14870        }
14871        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14872        push_region(start_row, end_row);
14873        results
14874    }
14875
14876    pub fn gutter_highlights_in_range(
14877        &self,
14878        search_range: Range<Anchor>,
14879        display_snapshot: &DisplaySnapshot,
14880        cx: &App,
14881    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14882        let mut results = Vec::new();
14883        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14884            let color = color_fetcher(cx);
14885            let start_ix = match ranges.binary_search_by(|probe| {
14886                let cmp = probe
14887                    .end
14888                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14889                if cmp.is_gt() {
14890                    Ordering::Greater
14891                } else {
14892                    Ordering::Less
14893                }
14894            }) {
14895                Ok(i) | Err(i) => i,
14896            };
14897            for range in &ranges[start_ix..] {
14898                if range
14899                    .start
14900                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14901                    .is_ge()
14902                {
14903                    break;
14904                }
14905
14906                let start = range.start.to_display_point(display_snapshot);
14907                let end = range.end.to_display_point(display_snapshot);
14908                results.push((start..end, color))
14909            }
14910        }
14911        results
14912    }
14913
14914    /// Get the text ranges corresponding to the redaction query
14915    pub fn redacted_ranges(
14916        &self,
14917        search_range: Range<Anchor>,
14918        display_snapshot: &DisplaySnapshot,
14919        cx: &App,
14920    ) -> Vec<Range<DisplayPoint>> {
14921        display_snapshot
14922            .buffer_snapshot
14923            .redacted_ranges(search_range, |file| {
14924                if let Some(file) = file {
14925                    file.is_private()
14926                        && EditorSettings::get(
14927                            Some(SettingsLocation {
14928                                worktree_id: file.worktree_id(cx),
14929                                path: file.path().as_ref(),
14930                            }),
14931                            cx,
14932                        )
14933                        .redact_private_values
14934                } else {
14935                    false
14936                }
14937            })
14938            .map(|range| {
14939                range.start.to_display_point(display_snapshot)
14940                    ..range.end.to_display_point(display_snapshot)
14941            })
14942            .collect()
14943    }
14944
14945    pub fn highlight_text<T: 'static>(
14946        &mut self,
14947        ranges: Vec<Range<Anchor>>,
14948        style: HighlightStyle,
14949        cx: &mut Context<Self>,
14950    ) {
14951        self.display_map.update(cx, |map, _| {
14952            map.highlight_text(TypeId::of::<T>(), ranges, style)
14953        });
14954        cx.notify();
14955    }
14956
14957    pub(crate) fn highlight_inlays<T: 'static>(
14958        &mut self,
14959        highlights: Vec<InlayHighlight>,
14960        style: HighlightStyle,
14961        cx: &mut Context<Self>,
14962    ) {
14963        self.display_map.update(cx, |map, _| {
14964            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14965        });
14966        cx.notify();
14967    }
14968
14969    pub fn text_highlights<'a, T: 'static>(
14970        &'a self,
14971        cx: &'a App,
14972    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14973        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14974    }
14975
14976    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14977        let cleared = self
14978            .display_map
14979            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14980        if cleared {
14981            cx.notify();
14982        }
14983    }
14984
14985    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14986        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14987            && self.focus_handle.is_focused(window)
14988    }
14989
14990    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14991        self.show_cursor_when_unfocused = is_enabled;
14992        cx.notify();
14993    }
14994
14995    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14996        cx.notify();
14997    }
14998
14999    fn on_buffer_event(
15000        &mut self,
15001        multibuffer: &Entity<MultiBuffer>,
15002        event: &multi_buffer::Event,
15003        window: &mut Window,
15004        cx: &mut Context<Self>,
15005    ) {
15006        match event {
15007            multi_buffer::Event::Edited {
15008                singleton_buffer_edited,
15009                edited_buffer: buffer_edited,
15010            } => {
15011                self.scrollbar_marker_state.dirty = true;
15012                self.active_indent_guides_state.dirty = true;
15013                self.refresh_active_diagnostics(cx);
15014                self.refresh_code_actions(window, cx);
15015                if self.has_active_inline_completion() {
15016                    self.update_visible_inline_completion(window, cx);
15017                }
15018                if let Some(buffer) = buffer_edited {
15019                    let buffer_id = buffer.read(cx).remote_id();
15020                    if !self.registered_buffers.contains_key(&buffer_id) {
15021                        if let Some(project) = self.project.as_ref() {
15022                            project.update(cx, |project, cx| {
15023                                self.registered_buffers.insert(
15024                                    buffer_id,
15025                                    project.register_buffer_with_language_servers(&buffer, cx),
15026                                );
15027                            })
15028                        }
15029                    }
15030                }
15031                cx.emit(EditorEvent::BufferEdited);
15032                cx.emit(SearchEvent::MatchesInvalidated);
15033                if *singleton_buffer_edited {
15034                    if let Some(project) = &self.project {
15035                        #[allow(clippy::mutable_key_type)]
15036                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15037                            multibuffer
15038                                .all_buffers()
15039                                .into_iter()
15040                                .filter_map(|buffer| {
15041                                    buffer.update(cx, |buffer, cx| {
15042                                        let language = buffer.language()?;
15043                                        let should_discard = project.update(cx, |project, cx| {
15044                                            project.is_local()
15045                                                && !project.has_language_servers_for(buffer, cx)
15046                                        });
15047                                        should_discard.not().then_some(language.clone())
15048                                    })
15049                                })
15050                                .collect::<HashSet<_>>()
15051                        });
15052                        if !languages_affected.is_empty() {
15053                            self.refresh_inlay_hints(
15054                                InlayHintRefreshReason::BufferEdited(languages_affected),
15055                                cx,
15056                            );
15057                        }
15058                    }
15059                }
15060
15061                let Some(project) = &self.project else { return };
15062                let (telemetry, is_via_ssh) = {
15063                    let project = project.read(cx);
15064                    let telemetry = project.client().telemetry().clone();
15065                    let is_via_ssh = project.is_via_ssh();
15066                    (telemetry, is_via_ssh)
15067                };
15068                refresh_linked_ranges(self, window, cx);
15069                telemetry.log_edit_event("editor", is_via_ssh);
15070            }
15071            multi_buffer::Event::ExcerptsAdded {
15072                buffer,
15073                predecessor,
15074                excerpts,
15075            } => {
15076                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15077                let buffer_id = buffer.read(cx).remote_id();
15078                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15079                    if let Some(project) = &self.project {
15080                        get_uncommitted_diff_for_buffer(
15081                            project,
15082                            [buffer.clone()],
15083                            self.buffer.clone(),
15084                            cx,
15085                        )
15086                        .detach();
15087                    }
15088                }
15089                cx.emit(EditorEvent::ExcerptsAdded {
15090                    buffer: buffer.clone(),
15091                    predecessor: *predecessor,
15092                    excerpts: excerpts.clone(),
15093                });
15094                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15095            }
15096            multi_buffer::Event::ExcerptsRemoved { ids } => {
15097                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15098                let buffer = self.buffer.read(cx);
15099                self.registered_buffers
15100                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15101                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15102            }
15103            multi_buffer::Event::ExcerptsEdited { ids } => {
15104                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15105            }
15106            multi_buffer::Event::ExcerptsExpanded { ids } => {
15107                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15108                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15109            }
15110            multi_buffer::Event::Reparsed(buffer_id) => {
15111                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15112
15113                cx.emit(EditorEvent::Reparsed(*buffer_id));
15114            }
15115            multi_buffer::Event::DiffHunksToggled => {
15116                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15117            }
15118            multi_buffer::Event::LanguageChanged(buffer_id) => {
15119                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15120                cx.emit(EditorEvent::Reparsed(*buffer_id));
15121                cx.notify();
15122            }
15123            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15124            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15125            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15126                cx.emit(EditorEvent::TitleChanged)
15127            }
15128            // multi_buffer::Event::DiffBaseChanged => {
15129            //     self.scrollbar_marker_state.dirty = true;
15130            //     cx.emit(EditorEvent::DiffBaseChanged);
15131            //     cx.notify();
15132            // }
15133            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15134            multi_buffer::Event::DiagnosticsUpdated => {
15135                self.refresh_active_diagnostics(cx);
15136                self.refresh_inline_diagnostics(true, window, cx);
15137                self.scrollbar_marker_state.dirty = true;
15138                cx.notify();
15139            }
15140            _ => {}
15141        };
15142    }
15143
15144    fn on_display_map_changed(
15145        &mut self,
15146        _: Entity<DisplayMap>,
15147        _: &mut Window,
15148        cx: &mut Context<Self>,
15149    ) {
15150        cx.notify();
15151    }
15152
15153    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15154        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15155        self.refresh_inline_completion(true, false, window, cx);
15156        self.refresh_inlay_hints(
15157            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15158                self.selections.newest_anchor().head(),
15159                &self.buffer.read(cx).snapshot(cx),
15160                cx,
15161            )),
15162            cx,
15163        );
15164
15165        let old_cursor_shape = self.cursor_shape;
15166
15167        {
15168            let editor_settings = EditorSettings::get_global(cx);
15169            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15170            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15171            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15172        }
15173
15174        if old_cursor_shape != self.cursor_shape {
15175            cx.emit(EditorEvent::CursorShapeChanged);
15176        }
15177
15178        let project_settings = ProjectSettings::get_global(cx);
15179        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15180
15181        if self.mode == EditorMode::Full {
15182            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15183            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15184            if self.show_inline_diagnostics != show_inline_diagnostics {
15185                self.show_inline_diagnostics = show_inline_diagnostics;
15186                self.refresh_inline_diagnostics(false, window, cx);
15187            }
15188
15189            if self.git_blame_inline_enabled != inline_blame_enabled {
15190                self.toggle_git_blame_inline_internal(false, window, cx);
15191            }
15192        }
15193
15194        cx.notify();
15195    }
15196
15197    pub fn set_searchable(&mut self, searchable: bool) {
15198        self.searchable = searchable;
15199    }
15200
15201    pub fn searchable(&self) -> bool {
15202        self.searchable
15203    }
15204
15205    fn open_proposed_changes_editor(
15206        &mut self,
15207        _: &OpenProposedChangesEditor,
15208        window: &mut Window,
15209        cx: &mut Context<Self>,
15210    ) {
15211        let Some(workspace) = self.workspace() else {
15212            cx.propagate();
15213            return;
15214        };
15215
15216        let selections = self.selections.all::<usize>(cx);
15217        let multi_buffer = self.buffer.read(cx);
15218        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15219        let mut new_selections_by_buffer = HashMap::default();
15220        for selection in selections {
15221            for (buffer, range, _) in
15222                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15223            {
15224                let mut range = range.to_point(buffer);
15225                range.start.column = 0;
15226                range.end.column = buffer.line_len(range.end.row);
15227                new_selections_by_buffer
15228                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15229                    .or_insert(Vec::new())
15230                    .push(range)
15231            }
15232        }
15233
15234        let proposed_changes_buffers = new_selections_by_buffer
15235            .into_iter()
15236            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15237            .collect::<Vec<_>>();
15238        let proposed_changes_editor = cx.new(|cx| {
15239            ProposedChangesEditor::new(
15240                "Proposed changes",
15241                proposed_changes_buffers,
15242                self.project.clone(),
15243                window,
15244                cx,
15245            )
15246        });
15247
15248        window.defer(cx, move |window, cx| {
15249            workspace.update(cx, |workspace, cx| {
15250                workspace.active_pane().update(cx, |pane, cx| {
15251                    pane.add_item(
15252                        Box::new(proposed_changes_editor),
15253                        true,
15254                        true,
15255                        None,
15256                        window,
15257                        cx,
15258                    );
15259                });
15260            });
15261        });
15262    }
15263
15264    pub fn open_excerpts_in_split(
15265        &mut self,
15266        _: &OpenExcerptsSplit,
15267        window: &mut Window,
15268        cx: &mut Context<Self>,
15269    ) {
15270        self.open_excerpts_common(None, true, window, cx)
15271    }
15272
15273    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15274        self.open_excerpts_common(None, false, window, cx)
15275    }
15276
15277    fn open_excerpts_common(
15278        &mut self,
15279        jump_data: Option<JumpData>,
15280        split: bool,
15281        window: &mut Window,
15282        cx: &mut Context<Self>,
15283    ) {
15284        let Some(workspace) = self.workspace() else {
15285            cx.propagate();
15286            return;
15287        };
15288
15289        if self.buffer.read(cx).is_singleton() {
15290            cx.propagate();
15291            return;
15292        }
15293
15294        let mut new_selections_by_buffer = HashMap::default();
15295        match &jump_data {
15296            Some(JumpData::MultiBufferPoint {
15297                excerpt_id,
15298                position,
15299                anchor,
15300                line_offset_from_top,
15301            }) => {
15302                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15303                if let Some(buffer) = multi_buffer_snapshot
15304                    .buffer_id_for_excerpt(*excerpt_id)
15305                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15306                {
15307                    let buffer_snapshot = buffer.read(cx).snapshot();
15308                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15309                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15310                    } else {
15311                        buffer_snapshot.clip_point(*position, Bias::Left)
15312                    };
15313                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15314                    new_selections_by_buffer.insert(
15315                        buffer,
15316                        (
15317                            vec![jump_to_offset..jump_to_offset],
15318                            Some(*line_offset_from_top),
15319                        ),
15320                    );
15321                }
15322            }
15323            Some(JumpData::MultiBufferRow {
15324                row,
15325                line_offset_from_top,
15326            }) => {
15327                let point = MultiBufferPoint::new(row.0, 0);
15328                if let Some((buffer, buffer_point, _)) =
15329                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15330                {
15331                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15332                    new_selections_by_buffer
15333                        .entry(buffer)
15334                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15335                        .0
15336                        .push(buffer_offset..buffer_offset)
15337                }
15338            }
15339            None => {
15340                let selections = self.selections.all::<usize>(cx);
15341                let multi_buffer = self.buffer.read(cx);
15342                for selection in selections {
15343                    for (buffer, mut range, _) in multi_buffer
15344                        .snapshot(cx)
15345                        .range_to_buffer_ranges(selection.range())
15346                    {
15347                        // When editing branch buffers, jump to the corresponding location
15348                        // in their base buffer.
15349                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
15350                        let buffer = buffer_handle.read(cx);
15351                        if let Some(base_buffer) = buffer.base_buffer() {
15352                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
15353                            buffer_handle = base_buffer;
15354                        }
15355
15356                        if selection.reversed {
15357                            mem::swap(&mut range.start, &mut range.end);
15358                        }
15359                        new_selections_by_buffer
15360                            .entry(buffer_handle)
15361                            .or_insert((Vec::new(), None))
15362                            .0
15363                            .push(range)
15364                    }
15365                }
15366            }
15367        }
15368
15369        if new_selections_by_buffer.is_empty() {
15370            return;
15371        }
15372
15373        // We defer the pane interaction because we ourselves are a workspace item
15374        // and activating a new item causes the pane to call a method on us reentrantly,
15375        // which panics if we're on the stack.
15376        window.defer(cx, move |window, cx| {
15377            workspace.update(cx, |workspace, cx| {
15378                let pane = if split {
15379                    workspace.adjacent_pane(window, cx)
15380                } else {
15381                    workspace.active_pane().clone()
15382                };
15383
15384                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15385                    let editor = buffer
15386                        .read(cx)
15387                        .file()
15388                        .is_none()
15389                        .then(|| {
15390                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15391                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15392                            // Instead, we try to activate the existing editor in the pane first.
15393                            let (editor, pane_item_index) =
15394                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15395                                    let editor = item.downcast::<Editor>()?;
15396                                    let singleton_buffer =
15397                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15398                                    if singleton_buffer == buffer {
15399                                        Some((editor, i))
15400                                    } else {
15401                                        None
15402                                    }
15403                                })?;
15404                            pane.update(cx, |pane, cx| {
15405                                pane.activate_item(pane_item_index, true, true, window, cx)
15406                            });
15407                            Some(editor)
15408                        })
15409                        .flatten()
15410                        .unwrap_or_else(|| {
15411                            workspace.open_project_item::<Self>(
15412                                pane.clone(),
15413                                buffer,
15414                                true,
15415                                true,
15416                                window,
15417                                cx,
15418                            )
15419                        });
15420
15421                    editor.update(cx, |editor, cx| {
15422                        let autoscroll = match scroll_offset {
15423                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15424                            None => Autoscroll::newest(),
15425                        };
15426                        let nav_history = editor.nav_history.take();
15427                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15428                            s.select_ranges(ranges);
15429                        });
15430                        editor.nav_history = nav_history;
15431                    });
15432                }
15433            })
15434        });
15435    }
15436
15437    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15438        let snapshot = self.buffer.read(cx).read(cx);
15439        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15440        Some(
15441            ranges
15442                .iter()
15443                .map(move |range| {
15444                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15445                })
15446                .collect(),
15447        )
15448    }
15449
15450    fn selection_replacement_ranges(
15451        &self,
15452        range: Range<OffsetUtf16>,
15453        cx: &mut App,
15454    ) -> Vec<Range<OffsetUtf16>> {
15455        let selections = self.selections.all::<OffsetUtf16>(cx);
15456        let newest_selection = selections
15457            .iter()
15458            .max_by_key(|selection| selection.id)
15459            .unwrap();
15460        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15461        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15462        let snapshot = self.buffer.read(cx).read(cx);
15463        selections
15464            .into_iter()
15465            .map(|mut selection| {
15466                selection.start.0 =
15467                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15468                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15469                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15470                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15471            })
15472            .collect()
15473    }
15474
15475    fn report_editor_event(
15476        &self,
15477        event_type: &'static str,
15478        file_extension: Option<String>,
15479        cx: &App,
15480    ) {
15481        if cfg!(any(test, feature = "test-support")) {
15482            return;
15483        }
15484
15485        let Some(project) = &self.project else { return };
15486
15487        // If None, we are in a file without an extension
15488        let file = self
15489            .buffer
15490            .read(cx)
15491            .as_singleton()
15492            .and_then(|b| b.read(cx).file());
15493        let file_extension = file_extension.or(file
15494            .as_ref()
15495            .and_then(|file| Path::new(file.file_name(cx)).extension())
15496            .and_then(|e| e.to_str())
15497            .map(|a| a.to_string()));
15498
15499        let vim_mode = cx
15500            .global::<SettingsStore>()
15501            .raw_user_settings()
15502            .get("vim_mode")
15503            == Some(&serde_json::Value::Bool(true));
15504
15505        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15506        let copilot_enabled = edit_predictions_provider
15507            == language::language_settings::EditPredictionProvider::Copilot;
15508        let copilot_enabled_for_language = self
15509            .buffer
15510            .read(cx)
15511            .settings_at(0, cx)
15512            .show_edit_predictions;
15513
15514        let project = project.read(cx);
15515        telemetry::event!(
15516            event_type,
15517            file_extension,
15518            vim_mode,
15519            copilot_enabled,
15520            copilot_enabled_for_language,
15521            edit_predictions_provider,
15522            is_via_ssh = project.is_via_ssh(),
15523        );
15524    }
15525
15526    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15527    /// with each line being an array of {text, highlight} objects.
15528    fn copy_highlight_json(
15529        &mut self,
15530        _: &CopyHighlightJson,
15531        window: &mut Window,
15532        cx: &mut Context<Self>,
15533    ) {
15534        #[derive(Serialize)]
15535        struct Chunk<'a> {
15536            text: String,
15537            highlight: Option<&'a str>,
15538        }
15539
15540        let snapshot = self.buffer.read(cx).snapshot(cx);
15541        let range = self
15542            .selected_text_range(false, window, cx)
15543            .and_then(|selection| {
15544                if selection.range.is_empty() {
15545                    None
15546                } else {
15547                    Some(selection.range)
15548                }
15549            })
15550            .unwrap_or_else(|| 0..snapshot.len());
15551
15552        let chunks = snapshot.chunks(range, true);
15553        let mut lines = Vec::new();
15554        let mut line: VecDeque<Chunk> = VecDeque::new();
15555
15556        let Some(style) = self.style.as_ref() else {
15557            return;
15558        };
15559
15560        for chunk in chunks {
15561            let highlight = chunk
15562                .syntax_highlight_id
15563                .and_then(|id| id.name(&style.syntax));
15564            let mut chunk_lines = chunk.text.split('\n').peekable();
15565            while let Some(text) = chunk_lines.next() {
15566                let mut merged_with_last_token = false;
15567                if let Some(last_token) = line.back_mut() {
15568                    if last_token.highlight == highlight {
15569                        last_token.text.push_str(text);
15570                        merged_with_last_token = true;
15571                    }
15572                }
15573
15574                if !merged_with_last_token {
15575                    line.push_back(Chunk {
15576                        text: text.into(),
15577                        highlight,
15578                    });
15579                }
15580
15581                if chunk_lines.peek().is_some() {
15582                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15583                        line.pop_front();
15584                    }
15585                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15586                        line.pop_back();
15587                    }
15588
15589                    lines.push(mem::take(&mut line));
15590                }
15591            }
15592        }
15593
15594        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15595            return;
15596        };
15597        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15598    }
15599
15600    pub fn open_context_menu(
15601        &mut self,
15602        _: &OpenContextMenu,
15603        window: &mut Window,
15604        cx: &mut Context<Self>,
15605    ) {
15606        self.request_autoscroll(Autoscroll::newest(), cx);
15607        let position = self.selections.newest_display(cx).start;
15608        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15609    }
15610
15611    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15612        &self.inlay_hint_cache
15613    }
15614
15615    pub fn replay_insert_event(
15616        &mut self,
15617        text: &str,
15618        relative_utf16_range: Option<Range<isize>>,
15619        window: &mut Window,
15620        cx: &mut Context<Self>,
15621    ) {
15622        if !self.input_enabled {
15623            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15624            return;
15625        }
15626        if let Some(relative_utf16_range) = relative_utf16_range {
15627            let selections = self.selections.all::<OffsetUtf16>(cx);
15628            self.change_selections(None, window, cx, |s| {
15629                let new_ranges = selections.into_iter().map(|range| {
15630                    let start = OffsetUtf16(
15631                        range
15632                            .head()
15633                            .0
15634                            .saturating_add_signed(relative_utf16_range.start),
15635                    );
15636                    let end = OffsetUtf16(
15637                        range
15638                            .head()
15639                            .0
15640                            .saturating_add_signed(relative_utf16_range.end),
15641                    );
15642                    start..end
15643                });
15644                s.select_ranges(new_ranges);
15645            });
15646        }
15647
15648        self.handle_input(text, window, cx);
15649    }
15650
15651    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15652        let Some(provider) = self.semantics_provider.as_ref() else {
15653            return false;
15654        };
15655
15656        let mut supports = false;
15657        self.buffer().update(cx, |this, cx| {
15658            this.for_each_buffer(|buffer| {
15659                supports |= provider.supports_inlay_hints(buffer, cx);
15660            });
15661        });
15662
15663        supports
15664    }
15665
15666    pub fn is_focused(&self, window: &Window) -> bool {
15667        self.focus_handle.is_focused(window)
15668    }
15669
15670    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15671        cx.emit(EditorEvent::Focused);
15672
15673        if let Some(descendant) = self
15674            .last_focused_descendant
15675            .take()
15676            .and_then(|descendant| descendant.upgrade())
15677        {
15678            window.focus(&descendant);
15679        } else {
15680            if let Some(blame) = self.blame.as_ref() {
15681                blame.update(cx, GitBlame::focus)
15682            }
15683
15684            self.blink_manager.update(cx, BlinkManager::enable);
15685            self.show_cursor_names(window, cx);
15686            self.buffer.update(cx, |buffer, cx| {
15687                buffer.finalize_last_transaction(cx);
15688                if self.leader_peer_id.is_none() {
15689                    buffer.set_active_selections(
15690                        &self.selections.disjoint_anchors(),
15691                        self.selections.line_mode,
15692                        self.cursor_shape,
15693                        cx,
15694                    );
15695                }
15696            });
15697        }
15698    }
15699
15700    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15701        cx.emit(EditorEvent::FocusedIn)
15702    }
15703
15704    fn handle_focus_out(
15705        &mut self,
15706        event: FocusOutEvent,
15707        _window: &mut Window,
15708        _cx: &mut Context<Self>,
15709    ) {
15710        if event.blurred != self.focus_handle {
15711            self.last_focused_descendant = Some(event.blurred);
15712        }
15713    }
15714
15715    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15716        self.blink_manager.update(cx, BlinkManager::disable);
15717        self.buffer
15718            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15719
15720        if let Some(blame) = self.blame.as_ref() {
15721            blame.update(cx, GitBlame::blur)
15722        }
15723        if !self.hover_state.focused(window, cx) {
15724            hide_hover(self, cx);
15725        }
15726        if !self
15727            .context_menu
15728            .borrow()
15729            .as_ref()
15730            .is_some_and(|context_menu| context_menu.focused(window, cx))
15731        {
15732            self.hide_context_menu(window, cx);
15733        }
15734        self.discard_inline_completion(false, cx);
15735        cx.emit(EditorEvent::Blurred);
15736        cx.notify();
15737    }
15738
15739    pub fn register_action<A: Action>(
15740        &mut self,
15741        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15742    ) -> Subscription {
15743        let id = self.next_editor_action_id.post_inc();
15744        let listener = Arc::new(listener);
15745        self.editor_actions.borrow_mut().insert(
15746            id,
15747            Box::new(move |window, _| {
15748                let listener = listener.clone();
15749                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15750                    let action = action.downcast_ref().unwrap();
15751                    if phase == DispatchPhase::Bubble {
15752                        listener(action, window, cx)
15753                    }
15754                })
15755            }),
15756        );
15757
15758        let editor_actions = self.editor_actions.clone();
15759        Subscription::new(move || {
15760            editor_actions.borrow_mut().remove(&id);
15761        })
15762    }
15763
15764    pub fn file_header_size(&self) -> u32 {
15765        FILE_HEADER_HEIGHT
15766    }
15767
15768    pub fn revert(
15769        &mut self,
15770        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15771        window: &mut Window,
15772        cx: &mut Context<Self>,
15773    ) {
15774        self.buffer().update(cx, |multi_buffer, cx| {
15775            for (buffer_id, changes) in revert_changes {
15776                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15777                    buffer.update(cx, |buffer, cx| {
15778                        buffer.edit(
15779                            changes.into_iter().map(|(range, text)| {
15780                                (range, text.to_string().map(Arc::<str>::from))
15781                            }),
15782                            None,
15783                            cx,
15784                        );
15785                    });
15786                }
15787            }
15788        });
15789        self.change_selections(None, window, cx, |selections| selections.refresh());
15790    }
15791
15792    pub fn to_pixel_point(
15793        &self,
15794        source: multi_buffer::Anchor,
15795        editor_snapshot: &EditorSnapshot,
15796        window: &mut Window,
15797    ) -> Option<gpui::Point<Pixels>> {
15798        let source_point = source.to_display_point(editor_snapshot);
15799        self.display_to_pixel_point(source_point, editor_snapshot, window)
15800    }
15801
15802    pub fn display_to_pixel_point(
15803        &self,
15804        source: DisplayPoint,
15805        editor_snapshot: &EditorSnapshot,
15806        window: &mut Window,
15807    ) -> Option<gpui::Point<Pixels>> {
15808        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15809        let text_layout_details = self.text_layout_details(window);
15810        let scroll_top = text_layout_details
15811            .scroll_anchor
15812            .scroll_position(editor_snapshot)
15813            .y;
15814
15815        if source.row().as_f32() < scroll_top.floor() {
15816            return None;
15817        }
15818        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15819        let source_y = line_height * (source.row().as_f32() - scroll_top);
15820        Some(gpui::Point::new(source_x, source_y))
15821    }
15822
15823    pub fn has_visible_completions_menu(&self) -> bool {
15824        !self.edit_prediction_preview_is_active()
15825            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15826                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15827            })
15828    }
15829
15830    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15831        self.addons
15832            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15833    }
15834
15835    pub fn unregister_addon<T: Addon>(&mut self) {
15836        self.addons.remove(&std::any::TypeId::of::<T>());
15837    }
15838
15839    pub fn addon<T: Addon>(&self) -> Option<&T> {
15840        let type_id = std::any::TypeId::of::<T>();
15841        self.addons
15842            .get(&type_id)
15843            .and_then(|item| item.to_any().downcast_ref::<T>())
15844    }
15845
15846    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15847        let text_layout_details = self.text_layout_details(window);
15848        let style = &text_layout_details.editor_style;
15849        let font_id = window.text_system().resolve_font(&style.text.font());
15850        let font_size = style.text.font_size.to_pixels(window.rem_size());
15851        let line_height = style.text.line_height_in_pixels(window.rem_size());
15852        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15853
15854        gpui::Size::new(em_width, line_height)
15855    }
15856
15857    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15858        self.load_diff_task.clone()
15859    }
15860
15861    fn read_selections_from_db(
15862        &mut self,
15863        item_id: u64,
15864        workspace_id: WorkspaceId,
15865        window: &mut Window,
15866        cx: &mut Context<Editor>,
15867    ) {
15868        if !self.is_singleton(cx)
15869            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15870        {
15871            return;
15872        }
15873        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15874            return;
15875        };
15876        if selections.is_empty() {
15877            return;
15878        }
15879
15880        let snapshot = self.buffer.read(cx).snapshot(cx);
15881        self.change_selections(None, window, cx, |s| {
15882            s.select_ranges(selections.into_iter().map(|(start, end)| {
15883                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15884            }));
15885        });
15886    }
15887}
15888
15889fn insert_extra_newline_brackets(
15890    buffer: &MultiBufferSnapshot,
15891    range: Range<usize>,
15892    language: &language::LanguageScope,
15893) -> bool {
15894    let leading_whitespace_len = buffer
15895        .reversed_chars_at(range.start)
15896        .take_while(|c| c.is_whitespace() && *c != '\n')
15897        .map(|c| c.len_utf8())
15898        .sum::<usize>();
15899    let trailing_whitespace_len = buffer
15900        .chars_at(range.end)
15901        .take_while(|c| c.is_whitespace() && *c != '\n')
15902        .map(|c| c.len_utf8())
15903        .sum::<usize>();
15904    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15905
15906    language.brackets().any(|(pair, enabled)| {
15907        let pair_start = pair.start.trim_end();
15908        let pair_end = pair.end.trim_start();
15909
15910        enabled
15911            && pair.newline
15912            && buffer.contains_str_at(range.end, pair_end)
15913            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15914    })
15915}
15916
15917fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15918    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15919        [(buffer, range, _)] => (*buffer, range.clone()),
15920        _ => return false,
15921    };
15922    let pair = {
15923        let mut result: Option<BracketMatch> = None;
15924
15925        for pair in buffer
15926            .all_bracket_ranges(range.clone())
15927            .filter(move |pair| {
15928                pair.open_range.start <= range.start && pair.close_range.end >= range.end
15929            })
15930        {
15931            let len = pair.close_range.end - pair.open_range.start;
15932
15933            if let Some(existing) = &result {
15934                let existing_len = existing.close_range.end - existing.open_range.start;
15935                if len > existing_len {
15936                    continue;
15937                }
15938            }
15939
15940            result = Some(pair);
15941        }
15942
15943        result
15944    };
15945    let Some(pair) = pair else {
15946        return false;
15947    };
15948    pair.newline_only
15949        && buffer
15950            .chars_for_range(pair.open_range.end..range.start)
15951            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15952            .all(|c| c.is_whitespace() && c != '\n')
15953}
15954
15955fn get_uncommitted_diff_for_buffer(
15956    project: &Entity<Project>,
15957    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15958    buffer: Entity<MultiBuffer>,
15959    cx: &mut App,
15960) -> Task<()> {
15961    let mut tasks = Vec::new();
15962    project.update(cx, |project, cx| {
15963        for buffer in buffers {
15964            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15965        }
15966    });
15967    cx.spawn(|mut cx| async move {
15968        let diffs = futures::future::join_all(tasks).await;
15969        buffer
15970            .update(&mut cx, |buffer, cx| {
15971                for diff in diffs.into_iter().flatten() {
15972                    buffer.add_diff(diff, cx);
15973                }
15974            })
15975            .ok();
15976    })
15977}
15978
15979fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15980    let tab_size = tab_size.get() as usize;
15981    let mut width = offset;
15982
15983    for ch in text.chars() {
15984        width += if ch == '\t' {
15985            tab_size - (width % tab_size)
15986        } else {
15987            1
15988        };
15989    }
15990
15991    width - offset
15992}
15993
15994#[cfg(test)]
15995mod tests {
15996    use super::*;
15997
15998    #[test]
15999    fn test_string_size_with_expanded_tabs() {
16000        let nz = |val| NonZeroU32::new(val).unwrap();
16001        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16002        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16003        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16004        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16005        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16006        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16007        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16008        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16009    }
16010}
16011
16012/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16013struct WordBreakingTokenizer<'a> {
16014    input: &'a str,
16015}
16016
16017impl<'a> WordBreakingTokenizer<'a> {
16018    fn new(input: &'a str) -> Self {
16019        Self { input }
16020    }
16021}
16022
16023fn is_char_ideographic(ch: char) -> bool {
16024    use unicode_script::Script::*;
16025    use unicode_script::UnicodeScript;
16026    matches!(ch.script(), Han | Tangut | Yi)
16027}
16028
16029fn is_grapheme_ideographic(text: &str) -> bool {
16030    text.chars().any(is_char_ideographic)
16031}
16032
16033fn is_grapheme_whitespace(text: &str) -> bool {
16034    text.chars().any(|x| x.is_whitespace())
16035}
16036
16037fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16038    text.chars().next().map_or(false, |ch| {
16039        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16040    })
16041}
16042
16043#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16044struct WordBreakToken<'a> {
16045    token: &'a str,
16046    grapheme_len: usize,
16047    is_whitespace: bool,
16048}
16049
16050impl<'a> Iterator for WordBreakingTokenizer<'a> {
16051    /// Yields a span, the count of graphemes in the token, and whether it was
16052    /// whitespace. Note that it also breaks at word boundaries.
16053    type Item = WordBreakToken<'a>;
16054
16055    fn next(&mut self) -> Option<Self::Item> {
16056        use unicode_segmentation::UnicodeSegmentation;
16057        if self.input.is_empty() {
16058            return None;
16059        }
16060
16061        let mut iter = self.input.graphemes(true).peekable();
16062        let mut offset = 0;
16063        let mut graphemes = 0;
16064        if let Some(first_grapheme) = iter.next() {
16065            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16066            offset += first_grapheme.len();
16067            graphemes += 1;
16068            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16069                if let Some(grapheme) = iter.peek().copied() {
16070                    if should_stay_with_preceding_ideograph(grapheme) {
16071                        offset += grapheme.len();
16072                        graphemes += 1;
16073                    }
16074                }
16075            } else {
16076                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16077                let mut next_word_bound = words.peek().copied();
16078                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16079                    next_word_bound = words.next();
16080                }
16081                while let Some(grapheme) = iter.peek().copied() {
16082                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16083                        break;
16084                    };
16085                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16086                        break;
16087                    };
16088                    offset += grapheme.len();
16089                    graphemes += 1;
16090                    iter.next();
16091                }
16092            }
16093            let token = &self.input[..offset];
16094            self.input = &self.input[offset..];
16095            if is_whitespace {
16096                Some(WordBreakToken {
16097                    token: " ",
16098                    grapheme_len: 1,
16099                    is_whitespace: true,
16100                })
16101            } else {
16102                Some(WordBreakToken {
16103                    token,
16104                    grapheme_len: graphemes,
16105                    is_whitespace: false,
16106                })
16107            }
16108        } else {
16109            None
16110        }
16111    }
16112}
16113
16114#[test]
16115fn test_word_breaking_tokenizer() {
16116    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16117        ("", &[]),
16118        ("  ", &[(" ", 1, true)]),
16119        ("Ʒ", &[("Ʒ", 1, false)]),
16120        ("Ǽ", &[("Ǽ", 1, false)]),
16121        ("", &[("", 1, false)]),
16122        ("⋑⋑", &[("⋑⋑", 2, false)]),
16123        (
16124            "原理,进而",
16125            &[
16126                ("", 1, false),
16127                ("理,", 2, false),
16128                ("", 1, false),
16129                ("", 1, false),
16130            ],
16131        ),
16132        (
16133            "hello world",
16134            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16135        ),
16136        (
16137            "hello, world",
16138            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16139        ),
16140        (
16141            "  hello world",
16142            &[
16143                (" ", 1, true),
16144                ("hello", 5, false),
16145                (" ", 1, true),
16146                ("world", 5, false),
16147            ],
16148        ),
16149        (
16150            "这是什么 \n 钢笔",
16151            &[
16152                ("", 1, false),
16153                ("", 1, false),
16154                ("", 1, false),
16155                ("", 1, false),
16156                (" ", 1, true),
16157                ("", 1, false),
16158                ("", 1, false),
16159            ],
16160        ),
16161        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16162    ];
16163
16164    for (input, result) in tests {
16165        assert_eq!(
16166            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16167            result
16168                .iter()
16169                .copied()
16170                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16171                    token,
16172                    grapheme_len,
16173                    is_whitespace,
16174                })
16175                .collect::<Vec<_>>()
16176        );
16177    }
16178}
16179
16180fn wrap_with_prefix(
16181    line_prefix: String,
16182    unwrapped_text: String,
16183    wrap_column: usize,
16184    tab_size: NonZeroU32,
16185) -> String {
16186    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16187    let mut wrapped_text = String::new();
16188    let mut current_line = line_prefix.clone();
16189
16190    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16191    let mut current_line_len = line_prefix_len;
16192    for WordBreakToken {
16193        token,
16194        grapheme_len,
16195        is_whitespace,
16196    } in tokenizer
16197    {
16198        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16199            wrapped_text.push_str(current_line.trim_end());
16200            wrapped_text.push('\n');
16201            current_line.truncate(line_prefix.len());
16202            current_line_len = line_prefix_len;
16203            if !is_whitespace {
16204                current_line.push_str(token);
16205                current_line_len += grapheme_len;
16206            }
16207        } else if !is_whitespace {
16208            current_line.push_str(token);
16209            current_line_len += grapheme_len;
16210        } else if current_line_len != line_prefix_len {
16211            current_line.push(' ');
16212            current_line_len += 1;
16213        }
16214    }
16215
16216    if !current_line.is_empty() {
16217        wrapped_text.push_str(&current_line);
16218    }
16219    wrapped_text
16220}
16221
16222#[test]
16223fn test_wrap_with_prefix() {
16224    assert_eq!(
16225        wrap_with_prefix(
16226            "# ".to_string(),
16227            "abcdefg".to_string(),
16228            4,
16229            NonZeroU32::new(4).unwrap()
16230        ),
16231        "# abcdefg"
16232    );
16233    assert_eq!(
16234        wrap_with_prefix(
16235            "".to_string(),
16236            "\thello world".to_string(),
16237            8,
16238            NonZeroU32::new(4).unwrap()
16239        ),
16240        "hello\nworld"
16241    );
16242    assert_eq!(
16243        wrap_with_prefix(
16244            "// ".to_string(),
16245            "xx \nyy zz aa bb cc".to_string(),
16246            12,
16247            NonZeroU32::new(4).unwrap()
16248        ),
16249        "// xx yy zz\n// aa bb cc"
16250    );
16251    assert_eq!(
16252        wrap_with_prefix(
16253            String::new(),
16254            "这是什么 \n 钢笔".to_string(),
16255            3,
16256            NonZeroU32::new(4).unwrap()
16257        ),
16258        "这是什\n么 钢\n"
16259    );
16260}
16261
16262pub trait CollaborationHub {
16263    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16264    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16265    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16266}
16267
16268impl CollaborationHub for Entity<Project> {
16269    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16270        self.read(cx).collaborators()
16271    }
16272
16273    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16274        self.read(cx).user_store().read(cx).participant_indices()
16275    }
16276
16277    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16278        let this = self.read(cx);
16279        let user_ids = this.collaborators().values().map(|c| c.user_id);
16280        this.user_store().read_with(cx, |user_store, cx| {
16281            user_store.participant_names(user_ids, cx)
16282        })
16283    }
16284}
16285
16286pub trait SemanticsProvider {
16287    fn hover(
16288        &self,
16289        buffer: &Entity<Buffer>,
16290        position: text::Anchor,
16291        cx: &mut App,
16292    ) -> Option<Task<Vec<project::Hover>>>;
16293
16294    fn inlay_hints(
16295        &self,
16296        buffer_handle: Entity<Buffer>,
16297        range: Range<text::Anchor>,
16298        cx: &mut App,
16299    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16300
16301    fn resolve_inlay_hint(
16302        &self,
16303        hint: InlayHint,
16304        buffer_handle: Entity<Buffer>,
16305        server_id: LanguageServerId,
16306        cx: &mut App,
16307    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16308
16309    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16310
16311    fn document_highlights(
16312        &self,
16313        buffer: &Entity<Buffer>,
16314        position: text::Anchor,
16315        cx: &mut App,
16316    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16317
16318    fn definitions(
16319        &self,
16320        buffer: &Entity<Buffer>,
16321        position: text::Anchor,
16322        kind: GotoDefinitionKind,
16323        cx: &mut App,
16324    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16325
16326    fn range_for_rename(
16327        &self,
16328        buffer: &Entity<Buffer>,
16329        position: text::Anchor,
16330        cx: &mut App,
16331    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16332
16333    fn perform_rename(
16334        &self,
16335        buffer: &Entity<Buffer>,
16336        position: text::Anchor,
16337        new_name: String,
16338        cx: &mut App,
16339    ) -> Option<Task<Result<ProjectTransaction>>>;
16340}
16341
16342pub trait CompletionProvider {
16343    fn completions(
16344        &self,
16345        buffer: &Entity<Buffer>,
16346        buffer_position: text::Anchor,
16347        trigger: CompletionContext,
16348        window: &mut Window,
16349        cx: &mut Context<Editor>,
16350    ) -> Task<Result<Vec<Completion>>>;
16351
16352    fn resolve_completions(
16353        &self,
16354        buffer: Entity<Buffer>,
16355        completion_indices: Vec<usize>,
16356        completions: Rc<RefCell<Box<[Completion]>>>,
16357        cx: &mut Context<Editor>,
16358    ) -> Task<Result<bool>>;
16359
16360    fn apply_additional_edits_for_completion(
16361        &self,
16362        _buffer: Entity<Buffer>,
16363        _completions: Rc<RefCell<Box<[Completion]>>>,
16364        _completion_index: usize,
16365        _push_to_history: bool,
16366        _cx: &mut Context<Editor>,
16367    ) -> Task<Result<Option<language::Transaction>>> {
16368        Task::ready(Ok(None))
16369    }
16370
16371    fn is_completion_trigger(
16372        &self,
16373        buffer: &Entity<Buffer>,
16374        position: language::Anchor,
16375        text: &str,
16376        trigger_in_words: bool,
16377        cx: &mut Context<Editor>,
16378    ) -> bool;
16379
16380    fn sort_completions(&self) -> bool {
16381        true
16382    }
16383}
16384
16385pub trait CodeActionProvider {
16386    fn id(&self) -> Arc<str>;
16387
16388    fn code_actions(
16389        &self,
16390        buffer: &Entity<Buffer>,
16391        range: Range<text::Anchor>,
16392        window: &mut Window,
16393        cx: &mut App,
16394    ) -> Task<Result<Vec<CodeAction>>>;
16395
16396    fn apply_code_action(
16397        &self,
16398        buffer_handle: Entity<Buffer>,
16399        action: CodeAction,
16400        excerpt_id: ExcerptId,
16401        push_to_history: bool,
16402        window: &mut Window,
16403        cx: &mut App,
16404    ) -> Task<Result<ProjectTransaction>>;
16405}
16406
16407impl CodeActionProvider for Entity<Project> {
16408    fn id(&self) -> Arc<str> {
16409        "project".into()
16410    }
16411
16412    fn code_actions(
16413        &self,
16414        buffer: &Entity<Buffer>,
16415        range: Range<text::Anchor>,
16416        _window: &mut Window,
16417        cx: &mut App,
16418    ) -> Task<Result<Vec<CodeAction>>> {
16419        self.update(cx, |project, cx| {
16420            project.code_actions(buffer, range, None, cx)
16421        })
16422    }
16423
16424    fn apply_code_action(
16425        &self,
16426        buffer_handle: Entity<Buffer>,
16427        action: CodeAction,
16428        _excerpt_id: ExcerptId,
16429        push_to_history: bool,
16430        _window: &mut Window,
16431        cx: &mut App,
16432    ) -> Task<Result<ProjectTransaction>> {
16433        self.update(cx, |project, cx| {
16434            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16435        })
16436    }
16437}
16438
16439fn snippet_completions(
16440    project: &Project,
16441    buffer: &Entity<Buffer>,
16442    buffer_position: text::Anchor,
16443    cx: &mut App,
16444) -> Task<Result<Vec<Completion>>> {
16445    let language = buffer.read(cx).language_at(buffer_position);
16446    let language_name = language.as_ref().map(|language| language.lsp_id());
16447    let snippet_store = project.snippets().read(cx);
16448    let snippets = snippet_store.snippets_for(language_name, cx);
16449
16450    if snippets.is_empty() {
16451        return Task::ready(Ok(vec![]));
16452    }
16453    let snapshot = buffer.read(cx).text_snapshot();
16454    let chars: String = snapshot
16455        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16456        .collect();
16457
16458    let scope = language.map(|language| language.default_scope());
16459    let executor = cx.background_executor().clone();
16460
16461    cx.background_spawn(async move {
16462        let classifier = CharClassifier::new(scope).for_completion(true);
16463        let mut last_word = chars
16464            .chars()
16465            .take_while(|c| classifier.is_word(*c))
16466            .collect::<String>();
16467        last_word = last_word.chars().rev().collect();
16468
16469        if last_word.is_empty() {
16470            return Ok(vec![]);
16471        }
16472
16473        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16474        let to_lsp = |point: &text::Anchor| {
16475            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16476            point_to_lsp(end)
16477        };
16478        let lsp_end = to_lsp(&buffer_position);
16479
16480        let candidates = snippets
16481            .iter()
16482            .enumerate()
16483            .flat_map(|(ix, snippet)| {
16484                snippet
16485                    .prefix
16486                    .iter()
16487                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16488            })
16489            .collect::<Vec<StringMatchCandidate>>();
16490
16491        let mut matches = fuzzy::match_strings(
16492            &candidates,
16493            &last_word,
16494            last_word.chars().any(|c| c.is_uppercase()),
16495            100,
16496            &Default::default(),
16497            executor,
16498        )
16499        .await;
16500
16501        // Remove all candidates where the query's start does not match the start of any word in the candidate
16502        if let Some(query_start) = last_word.chars().next() {
16503            matches.retain(|string_match| {
16504                split_words(&string_match.string).any(|word| {
16505                    // Check that the first codepoint of the word as lowercase matches the first
16506                    // codepoint of the query as lowercase
16507                    word.chars()
16508                        .flat_map(|codepoint| codepoint.to_lowercase())
16509                        .zip(query_start.to_lowercase())
16510                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16511                })
16512            });
16513        }
16514
16515        let matched_strings = matches
16516            .into_iter()
16517            .map(|m| m.string)
16518            .collect::<HashSet<_>>();
16519
16520        let result: Vec<Completion> = snippets
16521            .into_iter()
16522            .filter_map(|snippet| {
16523                let matching_prefix = snippet
16524                    .prefix
16525                    .iter()
16526                    .find(|prefix| matched_strings.contains(*prefix))?;
16527                let start = as_offset - last_word.len();
16528                let start = snapshot.anchor_before(start);
16529                let range = start..buffer_position;
16530                let lsp_start = to_lsp(&start);
16531                let lsp_range = lsp::Range {
16532                    start: lsp_start,
16533                    end: lsp_end,
16534                };
16535                Some(Completion {
16536                    old_range: range,
16537                    new_text: snippet.body.clone(),
16538                    resolved: false,
16539                    label: CodeLabel {
16540                        text: matching_prefix.clone(),
16541                        runs: vec![],
16542                        filter_range: 0..matching_prefix.len(),
16543                    },
16544                    server_id: LanguageServerId(usize::MAX),
16545                    documentation: snippet
16546                        .description
16547                        .clone()
16548                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16549                    lsp_completion: lsp::CompletionItem {
16550                        label: snippet.prefix.first().unwrap().clone(),
16551                        kind: Some(CompletionItemKind::SNIPPET),
16552                        label_details: snippet.description.as_ref().map(|description| {
16553                            lsp::CompletionItemLabelDetails {
16554                                detail: Some(description.clone()),
16555                                description: None,
16556                            }
16557                        }),
16558                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16559                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16560                            lsp::InsertReplaceEdit {
16561                                new_text: snippet.body.clone(),
16562                                insert: lsp_range,
16563                                replace: lsp_range,
16564                            },
16565                        )),
16566                        filter_text: Some(snippet.body.clone()),
16567                        sort_text: Some(char::MAX.to_string()),
16568                        ..Default::default()
16569                    },
16570                    confirm: None,
16571                })
16572            })
16573            .collect();
16574
16575        Ok(result)
16576    })
16577}
16578
16579impl CompletionProvider for Entity<Project> {
16580    fn completions(
16581        &self,
16582        buffer: &Entity<Buffer>,
16583        buffer_position: text::Anchor,
16584        options: CompletionContext,
16585        _window: &mut Window,
16586        cx: &mut Context<Editor>,
16587    ) -> Task<Result<Vec<Completion>>> {
16588        self.update(cx, |project, cx| {
16589            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16590            let project_completions = project.completions(buffer, buffer_position, options, cx);
16591            cx.background_spawn(async move {
16592                let mut completions = project_completions.await?;
16593                let snippets_completions = snippets.await?;
16594                completions.extend(snippets_completions);
16595                Ok(completions)
16596            })
16597        })
16598    }
16599
16600    fn resolve_completions(
16601        &self,
16602        buffer: Entity<Buffer>,
16603        completion_indices: Vec<usize>,
16604        completions: Rc<RefCell<Box<[Completion]>>>,
16605        cx: &mut Context<Editor>,
16606    ) -> Task<Result<bool>> {
16607        self.update(cx, |project, cx| {
16608            project.lsp_store().update(cx, |lsp_store, cx| {
16609                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16610            })
16611        })
16612    }
16613
16614    fn apply_additional_edits_for_completion(
16615        &self,
16616        buffer: Entity<Buffer>,
16617        completions: Rc<RefCell<Box<[Completion]>>>,
16618        completion_index: usize,
16619        push_to_history: bool,
16620        cx: &mut Context<Editor>,
16621    ) -> Task<Result<Option<language::Transaction>>> {
16622        self.update(cx, |project, cx| {
16623            project.lsp_store().update(cx, |lsp_store, cx| {
16624                lsp_store.apply_additional_edits_for_completion(
16625                    buffer,
16626                    completions,
16627                    completion_index,
16628                    push_to_history,
16629                    cx,
16630                )
16631            })
16632        })
16633    }
16634
16635    fn is_completion_trigger(
16636        &self,
16637        buffer: &Entity<Buffer>,
16638        position: language::Anchor,
16639        text: &str,
16640        trigger_in_words: bool,
16641        cx: &mut Context<Editor>,
16642    ) -> bool {
16643        let mut chars = text.chars();
16644        let char = if let Some(char) = chars.next() {
16645            char
16646        } else {
16647            return false;
16648        };
16649        if chars.next().is_some() {
16650            return false;
16651        }
16652
16653        let buffer = buffer.read(cx);
16654        let snapshot = buffer.snapshot();
16655        if !snapshot.settings_at(position, cx).show_completions_on_input {
16656            return false;
16657        }
16658        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16659        if trigger_in_words && classifier.is_word(char) {
16660            return true;
16661        }
16662
16663        buffer.completion_triggers().contains(text)
16664    }
16665}
16666
16667impl SemanticsProvider for Entity<Project> {
16668    fn hover(
16669        &self,
16670        buffer: &Entity<Buffer>,
16671        position: text::Anchor,
16672        cx: &mut App,
16673    ) -> Option<Task<Vec<project::Hover>>> {
16674        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16675    }
16676
16677    fn document_highlights(
16678        &self,
16679        buffer: &Entity<Buffer>,
16680        position: text::Anchor,
16681        cx: &mut App,
16682    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16683        Some(self.update(cx, |project, cx| {
16684            project.document_highlights(buffer, position, cx)
16685        }))
16686    }
16687
16688    fn definitions(
16689        &self,
16690        buffer: &Entity<Buffer>,
16691        position: text::Anchor,
16692        kind: GotoDefinitionKind,
16693        cx: &mut App,
16694    ) -> Option<Task<Result<Vec<LocationLink>>>> {
16695        Some(self.update(cx, |project, cx| match kind {
16696            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16697            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16698            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16699            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16700        }))
16701    }
16702
16703    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16704        // TODO: make this work for remote projects
16705        self.update(cx, |this, cx| {
16706            buffer.update(cx, |buffer, cx| {
16707                this.any_language_server_supports_inlay_hints(buffer, cx)
16708            })
16709        })
16710    }
16711
16712    fn inlay_hints(
16713        &self,
16714        buffer_handle: Entity<Buffer>,
16715        range: Range<text::Anchor>,
16716        cx: &mut App,
16717    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16718        Some(self.update(cx, |project, cx| {
16719            project.inlay_hints(buffer_handle, range, cx)
16720        }))
16721    }
16722
16723    fn resolve_inlay_hint(
16724        &self,
16725        hint: InlayHint,
16726        buffer_handle: Entity<Buffer>,
16727        server_id: LanguageServerId,
16728        cx: &mut App,
16729    ) -> Option<Task<anyhow::Result<InlayHint>>> {
16730        Some(self.update(cx, |project, cx| {
16731            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16732        }))
16733    }
16734
16735    fn range_for_rename(
16736        &self,
16737        buffer: &Entity<Buffer>,
16738        position: text::Anchor,
16739        cx: &mut App,
16740    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16741        Some(self.update(cx, |project, cx| {
16742            let buffer = buffer.clone();
16743            let task = project.prepare_rename(buffer.clone(), position, cx);
16744            cx.spawn(|_, mut cx| async move {
16745                Ok(match task.await? {
16746                    PrepareRenameResponse::Success(range) => Some(range),
16747                    PrepareRenameResponse::InvalidPosition => None,
16748                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16749                        // Fallback on using TreeSitter info to determine identifier range
16750                        buffer.update(&mut cx, |buffer, _| {
16751                            let snapshot = buffer.snapshot();
16752                            let (range, kind) = snapshot.surrounding_word(position);
16753                            if kind != Some(CharKind::Word) {
16754                                return None;
16755                            }
16756                            Some(
16757                                snapshot.anchor_before(range.start)
16758                                    ..snapshot.anchor_after(range.end),
16759                            )
16760                        })?
16761                    }
16762                })
16763            })
16764        }))
16765    }
16766
16767    fn perform_rename(
16768        &self,
16769        buffer: &Entity<Buffer>,
16770        position: text::Anchor,
16771        new_name: String,
16772        cx: &mut App,
16773    ) -> Option<Task<Result<ProjectTransaction>>> {
16774        Some(self.update(cx, |project, cx| {
16775            project.perform_rename(buffer.clone(), position, new_name, cx)
16776        }))
16777    }
16778}
16779
16780fn inlay_hint_settings(
16781    location: Anchor,
16782    snapshot: &MultiBufferSnapshot,
16783    cx: &mut Context<Editor>,
16784) -> InlayHintSettings {
16785    let file = snapshot.file_at(location);
16786    let language = snapshot.language_at(location).map(|l| l.name());
16787    language_settings(language, file, cx).inlay_hints
16788}
16789
16790fn consume_contiguous_rows(
16791    contiguous_row_selections: &mut Vec<Selection<Point>>,
16792    selection: &Selection<Point>,
16793    display_map: &DisplaySnapshot,
16794    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16795) -> (MultiBufferRow, MultiBufferRow) {
16796    contiguous_row_selections.push(selection.clone());
16797    let start_row = MultiBufferRow(selection.start.row);
16798    let mut end_row = ending_row(selection, display_map);
16799
16800    while let Some(next_selection) = selections.peek() {
16801        if next_selection.start.row <= end_row.0 {
16802            end_row = ending_row(next_selection, display_map);
16803            contiguous_row_selections.push(selections.next().unwrap().clone());
16804        } else {
16805            break;
16806        }
16807    }
16808    (start_row, end_row)
16809}
16810
16811fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16812    if next_selection.end.column > 0 || next_selection.is_empty() {
16813        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16814    } else {
16815        MultiBufferRow(next_selection.end.row)
16816    }
16817}
16818
16819impl EditorSnapshot {
16820    pub fn remote_selections_in_range<'a>(
16821        &'a self,
16822        range: &'a Range<Anchor>,
16823        collaboration_hub: &dyn CollaborationHub,
16824        cx: &'a App,
16825    ) -> impl 'a + Iterator<Item = RemoteSelection> {
16826        let participant_names = collaboration_hub.user_names(cx);
16827        let participant_indices = collaboration_hub.user_participant_indices(cx);
16828        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16829        let collaborators_by_replica_id = collaborators_by_peer_id
16830            .iter()
16831            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16832            .collect::<HashMap<_, _>>();
16833        self.buffer_snapshot
16834            .selections_in_range(range, false)
16835            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16836                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16837                let participant_index = participant_indices.get(&collaborator.user_id).copied();
16838                let user_name = participant_names.get(&collaborator.user_id).cloned();
16839                Some(RemoteSelection {
16840                    replica_id,
16841                    selection,
16842                    cursor_shape,
16843                    line_mode,
16844                    participant_index,
16845                    peer_id: collaborator.peer_id,
16846                    user_name,
16847                })
16848            })
16849    }
16850
16851    pub fn hunks_for_ranges(
16852        &self,
16853        ranges: impl Iterator<Item = Range<Point>>,
16854    ) -> Vec<MultiBufferDiffHunk> {
16855        let mut hunks = Vec::new();
16856        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16857            HashMap::default();
16858        for query_range in ranges {
16859            let query_rows =
16860                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16861            for hunk in self.buffer_snapshot.diff_hunks_in_range(
16862                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16863            ) {
16864                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16865                // when the caret is just above or just below the deleted hunk.
16866                let allow_adjacent = hunk.status().is_deleted();
16867                let related_to_selection = if allow_adjacent {
16868                    hunk.row_range.overlaps(&query_rows)
16869                        || hunk.row_range.start == query_rows.end
16870                        || hunk.row_range.end == query_rows.start
16871                } else {
16872                    hunk.row_range.overlaps(&query_rows)
16873                };
16874                if related_to_selection {
16875                    if !processed_buffer_rows
16876                        .entry(hunk.buffer_id)
16877                        .or_default()
16878                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16879                    {
16880                        continue;
16881                    }
16882                    hunks.push(hunk);
16883                }
16884            }
16885        }
16886
16887        hunks
16888    }
16889
16890    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16891        self.display_snapshot.buffer_snapshot.language_at(position)
16892    }
16893
16894    pub fn is_focused(&self) -> bool {
16895        self.is_focused
16896    }
16897
16898    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16899        self.placeholder_text.as_ref()
16900    }
16901
16902    pub fn scroll_position(&self) -> gpui::Point<f32> {
16903        self.scroll_anchor.scroll_position(&self.display_snapshot)
16904    }
16905
16906    fn gutter_dimensions(
16907        &self,
16908        font_id: FontId,
16909        font_size: Pixels,
16910        max_line_number_width: Pixels,
16911        cx: &App,
16912    ) -> Option<GutterDimensions> {
16913        if !self.show_gutter {
16914            return None;
16915        }
16916
16917        let descent = cx.text_system().descent(font_id, font_size);
16918        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16919        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16920
16921        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16922            matches!(
16923                ProjectSettings::get_global(cx).git.git_gutter,
16924                Some(GitGutterSetting::TrackedFiles)
16925            )
16926        });
16927        let gutter_settings = EditorSettings::get_global(cx).gutter;
16928        let show_line_numbers = self
16929            .show_line_numbers
16930            .unwrap_or(gutter_settings.line_numbers);
16931        let line_gutter_width = if show_line_numbers {
16932            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16933            let min_width_for_number_on_gutter = em_advance * 4.0;
16934            max_line_number_width.max(min_width_for_number_on_gutter)
16935        } else {
16936            0.0.into()
16937        };
16938
16939        let show_code_actions = self
16940            .show_code_actions
16941            .unwrap_or(gutter_settings.code_actions);
16942
16943        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16944
16945        let git_blame_entries_width =
16946            self.git_blame_gutter_max_author_length
16947                .map(|max_author_length| {
16948                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16949
16950                    /// The number of characters to dedicate to gaps and margins.
16951                    const SPACING_WIDTH: usize = 4;
16952
16953                    let max_char_count = max_author_length
16954                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16955                        + ::git::SHORT_SHA_LENGTH
16956                        + MAX_RELATIVE_TIMESTAMP.len()
16957                        + SPACING_WIDTH;
16958
16959                    em_advance * max_char_count
16960                });
16961
16962        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16963        left_padding += if show_code_actions || show_runnables {
16964            em_width * 3.0
16965        } else if show_git_gutter && show_line_numbers {
16966            em_width * 2.0
16967        } else if show_git_gutter || show_line_numbers {
16968            em_width
16969        } else {
16970            px(0.)
16971        };
16972
16973        let right_padding = if gutter_settings.folds && show_line_numbers {
16974            em_width * 4.0
16975        } else if gutter_settings.folds {
16976            em_width * 3.0
16977        } else if show_line_numbers {
16978            em_width
16979        } else {
16980            px(0.)
16981        };
16982
16983        Some(GutterDimensions {
16984            left_padding,
16985            right_padding,
16986            width: line_gutter_width + left_padding + right_padding,
16987            margin: -descent,
16988            git_blame_entries_width,
16989        })
16990    }
16991
16992    pub fn render_crease_toggle(
16993        &self,
16994        buffer_row: MultiBufferRow,
16995        row_contains_cursor: bool,
16996        editor: Entity<Editor>,
16997        window: &mut Window,
16998        cx: &mut App,
16999    ) -> Option<AnyElement> {
17000        let folded = self.is_line_folded(buffer_row);
17001        let mut is_foldable = false;
17002
17003        if let Some(crease) = self
17004            .crease_snapshot
17005            .query_row(buffer_row, &self.buffer_snapshot)
17006        {
17007            is_foldable = true;
17008            match crease {
17009                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17010                    if let Some(render_toggle) = render_toggle {
17011                        let toggle_callback =
17012                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17013                                if folded {
17014                                    editor.update(cx, |editor, cx| {
17015                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17016                                    });
17017                                } else {
17018                                    editor.update(cx, |editor, cx| {
17019                                        editor.unfold_at(
17020                                            &crate::UnfoldAt { buffer_row },
17021                                            window,
17022                                            cx,
17023                                        )
17024                                    });
17025                                }
17026                            });
17027                        return Some((render_toggle)(
17028                            buffer_row,
17029                            folded,
17030                            toggle_callback,
17031                            window,
17032                            cx,
17033                        ));
17034                    }
17035                }
17036            }
17037        }
17038
17039        is_foldable |= self.starts_indent(buffer_row);
17040
17041        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17042            Some(
17043                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17044                    .toggle_state(folded)
17045                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17046                        if folded {
17047                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17048                        } else {
17049                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17050                        }
17051                    }))
17052                    .into_any_element(),
17053            )
17054        } else {
17055            None
17056        }
17057    }
17058
17059    pub fn render_crease_trailer(
17060        &self,
17061        buffer_row: MultiBufferRow,
17062        window: &mut Window,
17063        cx: &mut App,
17064    ) -> Option<AnyElement> {
17065        let folded = self.is_line_folded(buffer_row);
17066        if let Crease::Inline { render_trailer, .. } = self
17067            .crease_snapshot
17068            .query_row(buffer_row, &self.buffer_snapshot)?
17069        {
17070            let render_trailer = render_trailer.as_ref()?;
17071            Some(render_trailer(buffer_row, folded, window, cx))
17072        } else {
17073            None
17074        }
17075    }
17076}
17077
17078impl Deref for EditorSnapshot {
17079    type Target = DisplaySnapshot;
17080
17081    fn deref(&self) -> &Self::Target {
17082        &self.display_snapshot
17083    }
17084}
17085
17086#[derive(Clone, Debug, PartialEq, Eq)]
17087pub enum EditorEvent {
17088    InputIgnored {
17089        text: Arc<str>,
17090    },
17091    InputHandled {
17092        utf16_range_to_replace: Option<Range<isize>>,
17093        text: Arc<str>,
17094    },
17095    ExcerptsAdded {
17096        buffer: Entity<Buffer>,
17097        predecessor: ExcerptId,
17098        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17099    },
17100    ExcerptsRemoved {
17101        ids: Vec<ExcerptId>,
17102    },
17103    BufferFoldToggled {
17104        ids: Vec<ExcerptId>,
17105        folded: bool,
17106    },
17107    ExcerptsEdited {
17108        ids: Vec<ExcerptId>,
17109    },
17110    ExcerptsExpanded {
17111        ids: Vec<ExcerptId>,
17112    },
17113    BufferEdited,
17114    Edited {
17115        transaction_id: clock::Lamport,
17116    },
17117    Reparsed(BufferId),
17118    Focused,
17119    FocusedIn,
17120    Blurred,
17121    DirtyChanged,
17122    Saved,
17123    TitleChanged,
17124    DiffBaseChanged,
17125    SelectionsChanged {
17126        local: bool,
17127    },
17128    ScrollPositionChanged {
17129        local: bool,
17130        autoscroll: bool,
17131    },
17132    Closed,
17133    TransactionUndone {
17134        transaction_id: clock::Lamport,
17135    },
17136    TransactionBegun {
17137        transaction_id: clock::Lamport,
17138    },
17139    Reloaded,
17140    CursorShapeChanged,
17141}
17142
17143impl EventEmitter<EditorEvent> for Editor {}
17144
17145impl Focusable for Editor {
17146    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17147        self.focus_handle.clone()
17148    }
17149}
17150
17151impl Render for Editor {
17152    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17153        let settings = ThemeSettings::get_global(cx);
17154
17155        let mut text_style = match self.mode {
17156            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17157                color: cx.theme().colors().editor_foreground,
17158                font_family: settings.ui_font.family.clone(),
17159                font_features: settings.ui_font.features.clone(),
17160                font_fallbacks: settings.ui_font.fallbacks.clone(),
17161                font_size: rems(0.875).into(),
17162                font_weight: settings.ui_font.weight,
17163                line_height: relative(settings.buffer_line_height.value()),
17164                ..Default::default()
17165            },
17166            EditorMode::Full => TextStyle {
17167                color: cx.theme().colors().editor_foreground,
17168                font_family: settings.buffer_font.family.clone(),
17169                font_features: settings.buffer_font.features.clone(),
17170                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17171                font_size: settings.buffer_font_size(cx).into(),
17172                font_weight: settings.buffer_font.weight,
17173                line_height: relative(settings.buffer_line_height.value()),
17174                ..Default::default()
17175            },
17176        };
17177        if let Some(text_style_refinement) = &self.text_style_refinement {
17178            text_style.refine(text_style_refinement)
17179        }
17180
17181        let background = match self.mode {
17182            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17183            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17184            EditorMode::Full => cx.theme().colors().editor_background,
17185        };
17186
17187        EditorElement::new(
17188            &cx.entity(),
17189            EditorStyle {
17190                background,
17191                local_player: cx.theme().players().local(),
17192                text: text_style,
17193                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17194                syntax: cx.theme().syntax().clone(),
17195                status: cx.theme().status().clone(),
17196                inlay_hints_style: make_inlay_hints_style(cx),
17197                inline_completion_styles: make_suggestion_styles(cx),
17198                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17199            },
17200        )
17201    }
17202}
17203
17204impl EntityInputHandler for Editor {
17205    fn text_for_range(
17206        &mut self,
17207        range_utf16: Range<usize>,
17208        adjusted_range: &mut Option<Range<usize>>,
17209        _: &mut Window,
17210        cx: &mut Context<Self>,
17211    ) -> Option<String> {
17212        let snapshot = self.buffer.read(cx).read(cx);
17213        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17214        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17215        if (start.0..end.0) != range_utf16 {
17216            adjusted_range.replace(start.0..end.0);
17217        }
17218        Some(snapshot.text_for_range(start..end).collect())
17219    }
17220
17221    fn selected_text_range(
17222        &mut self,
17223        ignore_disabled_input: bool,
17224        _: &mut Window,
17225        cx: &mut Context<Self>,
17226    ) -> Option<UTF16Selection> {
17227        // Prevent the IME menu from appearing when holding down an alphabetic key
17228        // while input is disabled.
17229        if !ignore_disabled_input && !self.input_enabled {
17230            return None;
17231        }
17232
17233        let selection = self.selections.newest::<OffsetUtf16>(cx);
17234        let range = selection.range();
17235
17236        Some(UTF16Selection {
17237            range: range.start.0..range.end.0,
17238            reversed: selection.reversed,
17239        })
17240    }
17241
17242    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17243        let snapshot = self.buffer.read(cx).read(cx);
17244        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17245        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17246    }
17247
17248    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17249        self.clear_highlights::<InputComposition>(cx);
17250        self.ime_transaction.take();
17251    }
17252
17253    fn replace_text_in_range(
17254        &mut self,
17255        range_utf16: Option<Range<usize>>,
17256        text: &str,
17257        window: &mut Window,
17258        cx: &mut Context<Self>,
17259    ) {
17260        if !self.input_enabled {
17261            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17262            return;
17263        }
17264
17265        self.transact(window, cx, |this, window, cx| {
17266            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17267                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17268                Some(this.selection_replacement_ranges(range_utf16, cx))
17269            } else {
17270                this.marked_text_ranges(cx)
17271            };
17272
17273            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17274                let newest_selection_id = this.selections.newest_anchor().id;
17275                this.selections
17276                    .all::<OffsetUtf16>(cx)
17277                    .iter()
17278                    .zip(ranges_to_replace.iter())
17279                    .find_map(|(selection, range)| {
17280                        if selection.id == newest_selection_id {
17281                            Some(
17282                                (range.start.0 as isize - selection.head().0 as isize)
17283                                    ..(range.end.0 as isize - selection.head().0 as isize),
17284                            )
17285                        } else {
17286                            None
17287                        }
17288                    })
17289            });
17290
17291            cx.emit(EditorEvent::InputHandled {
17292                utf16_range_to_replace: range_to_replace,
17293                text: text.into(),
17294            });
17295
17296            if let Some(new_selected_ranges) = new_selected_ranges {
17297                this.change_selections(None, window, cx, |selections| {
17298                    selections.select_ranges(new_selected_ranges)
17299                });
17300                this.backspace(&Default::default(), window, cx);
17301            }
17302
17303            this.handle_input(text, window, cx);
17304        });
17305
17306        if let Some(transaction) = self.ime_transaction {
17307            self.buffer.update(cx, |buffer, cx| {
17308                buffer.group_until_transaction(transaction, cx);
17309            });
17310        }
17311
17312        self.unmark_text(window, cx);
17313    }
17314
17315    fn replace_and_mark_text_in_range(
17316        &mut self,
17317        range_utf16: Option<Range<usize>>,
17318        text: &str,
17319        new_selected_range_utf16: Option<Range<usize>>,
17320        window: &mut Window,
17321        cx: &mut Context<Self>,
17322    ) {
17323        if !self.input_enabled {
17324            return;
17325        }
17326
17327        let transaction = self.transact(window, cx, |this, window, cx| {
17328            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17329                let snapshot = this.buffer.read(cx).read(cx);
17330                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17331                    for marked_range in &mut marked_ranges {
17332                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17333                        marked_range.start.0 += relative_range_utf16.start;
17334                        marked_range.start =
17335                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17336                        marked_range.end =
17337                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17338                    }
17339                }
17340                Some(marked_ranges)
17341            } else if let Some(range_utf16) = range_utf16 {
17342                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17343                Some(this.selection_replacement_ranges(range_utf16, cx))
17344            } else {
17345                None
17346            };
17347
17348            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17349                let newest_selection_id = this.selections.newest_anchor().id;
17350                this.selections
17351                    .all::<OffsetUtf16>(cx)
17352                    .iter()
17353                    .zip(ranges_to_replace.iter())
17354                    .find_map(|(selection, range)| {
17355                        if selection.id == newest_selection_id {
17356                            Some(
17357                                (range.start.0 as isize - selection.head().0 as isize)
17358                                    ..(range.end.0 as isize - selection.head().0 as isize),
17359                            )
17360                        } else {
17361                            None
17362                        }
17363                    })
17364            });
17365
17366            cx.emit(EditorEvent::InputHandled {
17367                utf16_range_to_replace: range_to_replace,
17368                text: text.into(),
17369            });
17370
17371            if let Some(ranges) = ranges_to_replace {
17372                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17373            }
17374
17375            let marked_ranges = {
17376                let snapshot = this.buffer.read(cx).read(cx);
17377                this.selections
17378                    .disjoint_anchors()
17379                    .iter()
17380                    .map(|selection| {
17381                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17382                    })
17383                    .collect::<Vec<_>>()
17384            };
17385
17386            if text.is_empty() {
17387                this.unmark_text(window, cx);
17388            } else {
17389                this.highlight_text::<InputComposition>(
17390                    marked_ranges.clone(),
17391                    HighlightStyle {
17392                        underline: Some(UnderlineStyle {
17393                            thickness: px(1.),
17394                            color: None,
17395                            wavy: false,
17396                        }),
17397                        ..Default::default()
17398                    },
17399                    cx,
17400                );
17401            }
17402
17403            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17404            let use_autoclose = this.use_autoclose;
17405            let use_auto_surround = this.use_auto_surround;
17406            this.set_use_autoclose(false);
17407            this.set_use_auto_surround(false);
17408            this.handle_input(text, window, cx);
17409            this.set_use_autoclose(use_autoclose);
17410            this.set_use_auto_surround(use_auto_surround);
17411
17412            if let Some(new_selected_range) = new_selected_range_utf16 {
17413                let snapshot = this.buffer.read(cx).read(cx);
17414                let new_selected_ranges = marked_ranges
17415                    .into_iter()
17416                    .map(|marked_range| {
17417                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17418                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17419                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17420                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17421                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17422                    })
17423                    .collect::<Vec<_>>();
17424
17425                drop(snapshot);
17426                this.change_selections(None, window, cx, |selections| {
17427                    selections.select_ranges(new_selected_ranges)
17428                });
17429            }
17430        });
17431
17432        self.ime_transaction = self.ime_transaction.or(transaction);
17433        if let Some(transaction) = self.ime_transaction {
17434            self.buffer.update(cx, |buffer, cx| {
17435                buffer.group_until_transaction(transaction, cx);
17436            });
17437        }
17438
17439        if self.text_highlights::<InputComposition>(cx).is_none() {
17440            self.ime_transaction.take();
17441        }
17442    }
17443
17444    fn bounds_for_range(
17445        &mut self,
17446        range_utf16: Range<usize>,
17447        element_bounds: gpui::Bounds<Pixels>,
17448        window: &mut Window,
17449        cx: &mut Context<Self>,
17450    ) -> Option<gpui::Bounds<Pixels>> {
17451        let text_layout_details = self.text_layout_details(window);
17452        let gpui::Size {
17453            width: em_width,
17454            height: line_height,
17455        } = self.character_size(window);
17456
17457        let snapshot = self.snapshot(window, cx);
17458        let scroll_position = snapshot.scroll_position();
17459        let scroll_left = scroll_position.x * em_width;
17460
17461        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17462        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17463            + self.gutter_dimensions.width
17464            + self.gutter_dimensions.margin;
17465        let y = line_height * (start.row().as_f32() - scroll_position.y);
17466
17467        Some(Bounds {
17468            origin: element_bounds.origin + point(x, y),
17469            size: size(em_width, line_height),
17470        })
17471    }
17472
17473    fn character_index_for_point(
17474        &mut self,
17475        point: gpui::Point<Pixels>,
17476        _window: &mut Window,
17477        _cx: &mut Context<Self>,
17478    ) -> Option<usize> {
17479        let position_map = self.last_position_map.as_ref()?;
17480        if !position_map.text_hitbox.contains(&point) {
17481            return None;
17482        }
17483        let display_point = position_map.point_for_position(point).previous_valid;
17484        let anchor = position_map
17485            .snapshot
17486            .display_point_to_anchor(display_point, Bias::Left);
17487        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17488        Some(utf16_offset.0)
17489    }
17490}
17491
17492trait SelectionExt {
17493    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17494    fn spanned_rows(
17495        &self,
17496        include_end_if_at_line_start: bool,
17497        map: &DisplaySnapshot,
17498    ) -> Range<MultiBufferRow>;
17499}
17500
17501impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17502    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17503        let start = self
17504            .start
17505            .to_point(&map.buffer_snapshot)
17506            .to_display_point(map);
17507        let end = self
17508            .end
17509            .to_point(&map.buffer_snapshot)
17510            .to_display_point(map);
17511        if self.reversed {
17512            end..start
17513        } else {
17514            start..end
17515        }
17516    }
17517
17518    fn spanned_rows(
17519        &self,
17520        include_end_if_at_line_start: bool,
17521        map: &DisplaySnapshot,
17522    ) -> Range<MultiBufferRow> {
17523        let start = self.start.to_point(&map.buffer_snapshot);
17524        let mut end = self.end.to_point(&map.buffer_snapshot);
17525        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17526            end.row -= 1;
17527        }
17528
17529        let buffer_start = map.prev_line_boundary(start).0;
17530        let buffer_end = map.next_line_boundary(end).0;
17531        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17532    }
17533}
17534
17535impl<T: InvalidationRegion> InvalidationStack<T> {
17536    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17537    where
17538        S: Clone + ToOffset,
17539    {
17540        while let Some(region) = self.last() {
17541            let all_selections_inside_invalidation_ranges =
17542                if selections.len() == region.ranges().len() {
17543                    selections
17544                        .iter()
17545                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17546                        .all(|(selection, invalidation_range)| {
17547                            let head = selection.head().to_offset(buffer);
17548                            invalidation_range.start <= head && invalidation_range.end >= head
17549                        })
17550                } else {
17551                    false
17552                };
17553
17554            if all_selections_inside_invalidation_ranges {
17555                break;
17556            } else {
17557                self.pop();
17558            }
17559        }
17560    }
17561}
17562
17563impl<T> Default for InvalidationStack<T> {
17564    fn default() -> Self {
17565        Self(Default::default())
17566    }
17567}
17568
17569impl<T> Deref for InvalidationStack<T> {
17570    type Target = Vec<T>;
17571
17572    fn deref(&self) -> &Self::Target {
17573        &self.0
17574    }
17575}
17576
17577impl<T> DerefMut for InvalidationStack<T> {
17578    fn deref_mut(&mut self) -> &mut Self::Target {
17579        &mut self.0
17580    }
17581}
17582
17583impl InvalidationRegion for SnippetState {
17584    fn ranges(&self) -> &[Range<Anchor>] {
17585        &self.ranges[self.active_index]
17586    }
17587}
17588
17589pub fn diagnostic_block_renderer(
17590    diagnostic: Diagnostic,
17591    max_message_rows: Option<u8>,
17592    allow_closing: bool,
17593    _is_valid: bool,
17594) -> RenderBlock {
17595    let (text_without_backticks, code_ranges) =
17596        highlight_diagnostic_message(&diagnostic, max_message_rows);
17597
17598    Arc::new(move |cx: &mut BlockContext| {
17599        let group_id: SharedString = cx.block_id.to_string().into();
17600
17601        let mut text_style = cx.window.text_style().clone();
17602        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17603        let theme_settings = ThemeSettings::get_global(cx);
17604        text_style.font_family = theme_settings.buffer_font.family.clone();
17605        text_style.font_style = theme_settings.buffer_font.style;
17606        text_style.font_features = theme_settings.buffer_font.features.clone();
17607        text_style.font_weight = theme_settings.buffer_font.weight;
17608
17609        let multi_line_diagnostic = diagnostic.message.contains('\n');
17610
17611        let buttons = |diagnostic: &Diagnostic| {
17612            if multi_line_diagnostic {
17613                v_flex()
17614            } else {
17615                h_flex()
17616            }
17617            .when(allow_closing, |div| {
17618                div.children(diagnostic.is_primary.then(|| {
17619                    IconButton::new("close-block", IconName::XCircle)
17620                        .icon_color(Color::Muted)
17621                        .size(ButtonSize::Compact)
17622                        .style(ButtonStyle::Transparent)
17623                        .visible_on_hover(group_id.clone())
17624                        .on_click(move |_click, window, cx| {
17625                            window.dispatch_action(Box::new(Cancel), cx)
17626                        })
17627                        .tooltip(|window, cx| {
17628                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17629                        })
17630                }))
17631            })
17632            .child(
17633                IconButton::new("copy-block", IconName::Copy)
17634                    .icon_color(Color::Muted)
17635                    .size(ButtonSize::Compact)
17636                    .style(ButtonStyle::Transparent)
17637                    .visible_on_hover(group_id.clone())
17638                    .on_click({
17639                        let message = diagnostic.message.clone();
17640                        move |_click, _, cx| {
17641                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17642                        }
17643                    })
17644                    .tooltip(Tooltip::text("Copy diagnostic message")),
17645            )
17646        };
17647
17648        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17649            AvailableSpace::min_size(),
17650            cx.window,
17651            cx.app,
17652        );
17653
17654        h_flex()
17655            .id(cx.block_id)
17656            .group(group_id.clone())
17657            .relative()
17658            .size_full()
17659            .block_mouse_down()
17660            .pl(cx.gutter_dimensions.width)
17661            .w(cx.max_width - cx.gutter_dimensions.full_width())
17662            .child(
17663                div()
17664                    .flex()
17665                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17666                    .flex_shrink(),
17667            )
17668            .child(buttons(&diagnostic))
17669            .child(div().flex().flex_shrink_0().child(
17670                StyledText::new(text_without_backticks.clone()).with_highlights(
17671                    &text_style,
17672                    code_ranges.iter().map(|range| {
17673                        (
17674                            range.clone(),
17675                            HighlightStyle {
17676                                font_weight: Some(FontWeight::BOLD),
17677                                ..Default::default()
17678                            },
17679                        )
17680                    }),
17681                ),
17682            ))
17683            .into_any_element()
17684    })
17685}
17686
17687fn inline_completion_edit_text(
17688    current_snapshot: &BufferSnapshot,
17689    edits: &[(Range<Anchor>, String)],
17690    edit_preview: &EditPreview,
17691    include_deletions: bool,
17692    cx: &App,
17693) -> HighlightedText {
17694    let edits = edits
17695        .iter()
17696        .map(|(anchor, text)| {
17697            (
17698                anchor.start.text_anchor..anchor.end.text_anchor,
17699                text.clone(),
17700            )
17701        })
17702        .collect::<Vec<_>>();
17703
17704    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17705}
17706
17707pub fn highlight_diagnostic_message(
17708    diagnostic: &Diagnostic,
17709    mut max_message_rows: Option<u8>,
17710) -> (SharedString, Vec<Range<usize>>) {
17711    let mut text_without_backticks = String::new();
17712    let mut code_ranges = Vec::new();
17713
17714    if let Some(source) = &diagnostic.source {
17715        text_without_backticks.push_str(source);
17716        code_ranges.push(0..source.len());
17717        text_without_backticks.push_str(": ");
17718    }
17719
17720    let mut prev_offset = 0;
17721    let mut in_code_block = false;
17722    let has_row_limit = max_message_rows.is_some();
17723    let mut newline_indices = diagnostic
17724        .message
17725        .match_indices('\n')
17726        .filter(|_| has_row_limit)
17727        .map(|(ix, _)| ix)
17728        .fuse()
17729        .peekable();
17730
17731    for (quote_ix, _) in diagnostic
17732        .message
17733        .match_indices('`')
17734        .chain([(diagnostic.message.len(), "")])
17735    {
17736        let mut first_newline_ix = None;
17737        let mut last_newline_ix = None;
17738        while let Some(newline_ix) = newline_indices.peek() {
17739            if *newline_ix < quote_ix {
17740                if first_newline_ix.is_none() {
17741                    first_newline_ix = Some(*newline_ix);
17742                }
17743                last_newline_ix = Some(*newline_ix);
17744
17745                if let Some(rows_left) = &mut max_message_rows {
17746                    if *rows_left == 0 {
17747                        break;
17748                    } else {
17749                        *rows_left -= 1;
17750                    }
17751                }
17752                let _ = newline_indices.next();
17753            } else {
17754                break;
17755            }
17756        }
17757        let prev_len = text_without_backticks.len();
17758        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17759        text_without_backticks.push_str(new_text);
17760        if in_code_block {
17761            code_ranges.push(prev_len..text_without_backticks.len());
17762        }
17763        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17764        in_code_block = !in_code_block;
17765        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17766            text_without_backticks.push_str("...");
17767            break;
17768        }
17769    }
17770
17771    (text_without_backticks.into(), code_ranges)
17772}
17773
17774fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17775    match severity {
17776        DiagnosticSeverity::ERROR => colors.error,
17777        DiagnosticSeverity::WARNING => colors.warning,
17778        DiagnosticSeverity::INFORMATION => colors.info,
17779        DiagnosticSeverity::HINT => colors.info,
17780        _ => colors.ignored,
17781    }
17782}
17783
17784pub fn styled_runs_for_code_label<'a>(
17785    label: &'a CodeLabel,
17786    syntax_theme: &'a theme::SyntaxTheme,
17787) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17788    let fade_out = HighlightStyle {
17789        fade_out: Some(0.35),
17790        ..Default::default()
17791    };
17792
17793    let mut prev_end = label.filter_range.end;
17794    label
17795        .runs
17796        .iter()
17797        .enumerate()
17798        .flat_map(move |(ix, (range, highlight_id))| {
17799            let style = if let Some(style) = highlight_id.style(syntax_theme) {
17800                style
17801            } else {
17802                return Default::default();
17803            };
17804            let mut muted_style = style;
17805            muted_style.highlight(fade_out);
17806
17807            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17808            if range.start >= label.filter_range.end {
17809                if range.start > prev_end {
17810                    runs.push((prev_end..range.start, fade_out));
17811                }
17812                runs.push((range.clone(), muted_style));
17813            } else if range.end <= label.filter_range.end {
17814                runs.push((range.clone(), style));
17815            } else {
17816                runs.push((range.start..label.filter_range.end, style));
17817                runs.push((label.filter_range.end..range.end, muted_style));
17818            }
17819            prev_end = cmp::max(prev_end, range.end);
17820
17821            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17822                runs.push((prev_end..label.text.len(), fade_out));
17823            }
17824
17825            runs
17826        })
17827}
17828
17829pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17830    let mut prev_index = 0;
17831    let mut prev_codepoint: Option<char> = None;
17832    text.char_indices()
17833        .chain([(text.len(), '\0')])
17834        .filter_map(move |(index, codepoint)| {
17835            let prev_codepoint = prev_codepoint.replace(codepoint)?;
17836            let is_boundary = index == text.len()
17837                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17838                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17839            if is_boundary {
17840                let chunk = &text[prev_index..index];
17841                prev_index = index;
17842                Some(chunk)
17843            } else {
17844                None
17845            }
17846        })
17847}
17848
17849pub trait RangeToAnchorExt: Sized {
17850    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17851
17852    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17853        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17854        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17855    }
17856}
17857
17858impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17859    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17860        let start_offset = self.start.to_offset(snapshot);
17861        let end_offset = self.end.to_offset(snapshot);
17862        if start_offset == end_offset {
17863            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17864        } else {
17865            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17866        }
17867    }
17868}
17869
17870pub trait RowExt {
17871    fn as_f32(&self) -> f32;
17872
17873    fn next_row(&self) -> Self;
17874
17875    fn previous_row(&self) -> Self;
17876
17877    fn minus(&self, other: Self) -> u32;
17878}
17879
17880impl RowExt for DisplayRow {
17881    fn as_f32(&self) -> f32 {
17882        self.0 as f32
17883    }
17884
17885    fn next_row(&self) -> Self {
17886        Self(self.0 + 1)
17887    }
17888
17889    fn previous_row(&self) -> Self {
17890        Self(self.0.saturating_sub(1))
17891    }
17892
17893    fn minus(&self, other: Self) -> u32 {
17894        self.0 - other.0
17895    }
17896}
17897
17898impl RowExt for MultiBufferRow {
17899    fn as_f32(&self) -> f32 {
17900        self.0 as f32
17901    }
17902
17903    fn next_row(&self) -> Self {
17904        Self(self.0 + 1)
17905    }
17906
17907    fn previous_row(&self) -> Self {
17908        Self(self.0.saturating_sub(1))
17909    }
17910
17911    fn minus(&self, other: Self) -> u32 {
17912        self.0 - other.0
17913    }
17914}
17915
17916trait RowRangeExt {
17917    type Row;
17918
17919    fn len(&self) -> usize;
17920
17921    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17922}
17923
17924impl RowRangeExt for Range<MultiBufferRow> {
17925    type Row = MultiBufferRow;
17926
17927    fn len(&self) -> usize {
17928        (self.end.0 - self.start.0) as usize
17929    }
17930
17931    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17932        (self.start.0..self.end.0).map(MultiBufferRow)
17933    }
17934}
17935
17936impl RowRangeExt for Range<DisplayRow> {
17937    type Row = DisplayRow;
17938
17939    fn len(&self) -> usize {
17940        (self.end.0 - self.start.0) as usize
17941    }
17942
17943    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17944        (self.start.0..self.end.0).map(DisplayRow)
17945    }
17946}
17947
17948/// If select range has more than one line, we
17949/// just point the cursor to range.start.
17950fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17951    if range.start.row == range.end.row {
17952        range
17953    } else {
17954        range.start..range.start
17955    }
17956}
17957pub struct KillRing(ClipboardItem);
17958impl Global for KillRing {}
17959
17960const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17961
17962fn all_edits_insertions_or_deletions(
17963    edits: &Vec<(Range<Anchor>, String)>,
17964    snapshot: &MultiBufferSnapshot,
17965) -> bool {
17966    let mut all_insertions = true;
17967    let mut all_deletions = true;
17968
17969    for (range, new_text) in edits.iter() {
17970        let range_is_empty = range.to_offset(&snapshot).is_empty();
17971        let text_is_empty = new_text.is_empty();
17972
17973        if range_is_empty != text_is_empty {
17974            if range_is_empty {
17975                all_deletions = false;
17976            } else {
17977                all_insertions = false;
17978            }
17979        } else {
17980            return false;
17981        }
17982
17983        if !all_insertions && !all_deletions {
17984            return false;
17985        }
17986    }
17987    all_insertions || all_deletions
17988}