editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkSecondaryStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use ::git::{status::FileStatus, Restore};
   77use code_context_menus::{
   78    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   79    CompletionsMenu, ContextMenuOrigin,
   80};
   81use git::blame::GitBlame;
   82use gpui::{
   83    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   84    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   85    ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
   86    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   87    HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
   88    ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
   89    TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   90    WeakEntity, WeakFocusHandle, Window,
   91};
   92use highlight_matching_bracket::refresh_matching_bracket_highlights;
   93use hover_popover::{hide_hover, HoverState};
   94use indent_guides::ActiveIndentGuidesState;
   95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   96pub use inline_completion::Direction;
   97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   98pub use items::MAX_TAB_TITLE_LEN;
   99use itertools::Itertools;
  100use language::{
  101    language_settings::{
  102        self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
  103    },
  104    point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
  105    Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, DiskState,
  106    EditPredictionsMode, EditPreview, HighlightedText, IndentKind, IndentSize, Language,
  107    OffsetRangeExt, Point, Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  108};
  109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  110use linked_editing_ranges::refresh_linked_ranges;
  111use mouse_context_menu::MouseContextMenu;
  112use persistence::DB;
  113pub use proposed_changes_editor::{
  114    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  115};
  116use smallvec::smallvec;
  117use std::iter::Peekable;
  118use task::{ResolvedTask, TaskTemplate, TaskVariables};
  119
  120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  121pub use lsp::CompletionContext;
  122use lsp::{
  123    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  124    LanguageServerId, LanguageServerName,
  125};
  126
  127use language::BufferSnapshot;
  128use movement::TextLayoutDetails;
  129pub use multi_buffer::{
  130    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  131    ToOffset, ToPoint,
  132};
  133use multi_buffer::{
  134    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  135    ToOffsetUtf16,
  136};
  137use project::{
  138    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  139    project_settings::{GitGutterSetting, ProjectSettings},
  140    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  141    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  142};
  143use rand::prelude::*;
  144use rpc::{proto::*, ErrorExt};
  145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  146use selections_collection::{
  147    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  148};
  149use serde::{Deserialize, Serialize};
  150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  151use smallvec::SmallVec;
  152use snippet::Snippet;
  153use std::{
  154    any::TypeId,
  155    borrow::Cow,
  156    cell::RefCell,
  157    cmp::{self, Ordering, Reverse},
  158    mem,
  159    num::NonZeroU32,
  160    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  161    path::{Path, PathBuf},
  162    rc::Rc,
  163    sync::Arc,
  164    time::{Duration, Instant},
  165};
  166pub use sum_tree::Bias;
  167use sum_tree::TreeMap;
  168use text::{BufferId, OffsetUtf16, Rope};
  169use theme::{
  170    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  171    ThemeColors, ThemeSettings,
  172};
  173use ui::{
  174    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  175    Tooltip,
  176};
  177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  178use workspace::{
  179    item::{ItemHandle, PreviewTabsSettings},
  180    ItemId, RestoreOnStartupBehavior,
  181};
  182use workspace::{
  183    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  184    WorkspaceSettings,
  185};
  186use workspace::{
  187    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  188};
  189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  190
  191use crate::hover_links::{find_url, find_url_from_range};
  192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  193
  194pub const FILE_HEADER_HEIGHT: u32 = 2;
  195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  199const MAX_LINE_LEN: usize = 1024;
  200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  203#[doc(hidden)]
  204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  205
  206pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
  207pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  208
  209pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  210pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  211
  212const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  213    alt: true,
  214    shift: true,
  215    control: false,
  216    platform: false,
  217    function: false,
  218};
  219
  220#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  221pub enum InlayId {
  222    InlineCompletion(usize),
  223    Hint(usize),
  224}
  225
  226impl InlayId {
  227    fn id(&self) -> usize {
  228        match self {
  229            Self::InlineCompletion(id) => *id,
  230            Self::Hint(id) => *id,
  231        }
  232    }
  233}
  234
  235enum DocumentHighlightRead {}
  236enum DocumentHighlightWrite {}
  237enum InputComposition {}
  238enum SelectedTextHighlight {}
  239
  240#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  241pub enum Navigated {
  242    Yes,
  243    No,
  244}
  245
  246impl Navigated {
  247    pub fn from_bool(yes: bool) -> Navigated {
  248        if yes {
  249            Navigated::Yes
  250        } else {
  251            Navigated::No
  252        }
  253    }
  254}
  255
  256pub fn init_settings(cx: &mut App) {
  257    EditorSettings::register(cx);
  258}
  259
  260pub fn init(cx: &mut App) {
  261    init_settings(cx);
  262
  263    workspace::register_project_item::<Editor>(cx);
  264    workspace::FollowableViewRegistry::register::<Editor>(cx);
  265    workspace::register_serializable_item::<Editor>(cx);
  266
  267    cx.observe_new(
  268        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  269            workspace.register_action(Editor::new_file);
  270            workspace.register_action(Editor::new_file_vertical);
  271            workspace.register_action(Editor::new_file_horizontal);
  272            workspace.register_action(Editor::cancel_language_server_work);
  273        },
  274    )
  275    .detach();
  276
  277    cx.on_action(move |_: &workspace::NewFile, cx| {
  278        let app_state = workspace::AppState::global(cx);
  279        if let Some(app_state) = app_state.upgrade() {
  280            workspace::open_new(
  281                Default::default(),
  282                app_state,
  283                cx,
  284                |workspace, window, cx| {
  285                    Editor::new_file(workspace, &Default::default(), window, cx)
  286                },
  287            )
  288            .detach();
  289        }
  290    });
  291    cx.on_action(move |_: &workspace::NewWindow, cx| {
  292        let app_state = workspace::AppState::global(cx);
  293        if let Some(app_state) = app_state.upgrade() {
  294            workspace::open_new(
  295                Default::default(),
  296                app_state,
  297                cx,
  298                |workspace, window, cx| {
  299                    cx.activate(true);
  300                    Editor::new_file(workspace, &Default::default(), window, cx)
  301                },
  302            )
  303            .detach();
  304        }
  305    });
  306}
  307
  308pub struct SearchWithinRange;
  309
  310trait InvalidationRegion {
  311    fn ranges(&self) -> &[Range<Anchor>];
  312}
  313
  314#[derive(Clone, Debug, PartialEq)]
  315pub enum SelectPhase {
  316    Begin {
  317        position: DisplayPoint,
  318        add: bool,
  319        click_count: usize,
  320    },
  321    BeginColumnar {
  322        position: DisplayPoint,
  323        reset: bool,
  324        goal_column: u32,
  325    },
  326    Extend {
  327        position: DisplayPoint,
  328        click_count: usize,
  329    },
  330    Update {
  331        position: DisplayPoint,
  332        goal_column: u32,
  333        scroll_delta: gpui::Point<f32>,
  334    },
  335    End,
  336}
  337
  338#[derive(Clone, Debug)]
  339pub enum SelectMode {
  340    Character,
  341    Word(Range<Anchor>),
  342    Line(Range<Anchor>),
  343    All,
  344}
  345
  346#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  347pub enum EditorMode {
  348    SingleLine { auto_width: bool },
  349    AutoHeight { max_lines: usize },
  350    Full,
  351}
  352
  353#[derive(Copy, Clone, Debug)]
  354pub enum SoftWrap {
  355    /// Prefer not to wrap at all.
  356    ///
  357    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  358    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  359    GitDiff,
  360    /// Prefer a single line generally, unless an overly long line is encountered.
  361    None,
  362    /// Soft wrap lines that exceed the editor width.
  363    EditorWidth,
  364    /// Soft wrap lines at the preferred line length.
  365    Column(u32),
  366    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  367    Bounded(u32),
  368}
  369
  370#[derive(Clone)]
  371pub struct EditorStyle {
  372    pub background: Hsla,
  373    pub local_player: PlayerColor,
  374    pub text: TextStyle,
  375    pub scrollbar_width: Pixels,
  376    pub syntax: Arc<SyntaxTheme>,
  377    pub status: StatusColors,
  378    pub inlay_hints_style: HighlightStyle,
  379    pub inline_completion_styles: InlineCompletionStyles,
  380    pub unnecessary_code_fade: f32,
  381}
  382
  383impl Default for EditorStyle {
  384    fn default() -> Self {
  385        Self {
  386            background: Hsla::default(),
  387            local_player: PlayerColor::default(),
  388            text: TextStyle::default(),
  389            scrollbar_width: Pixels::default(),
  390            syntax: Default::default(),
  391            // HACK: Status colors don't have a real default.
  392            // We should look into removing the status colors from the editor
  393            // style and retrieve them directly from the theme.
  394            status: StatusColors::dark(),
  395            inlay_hints_style: HighlightStyle::default(),
  396            inline_completion_styles: InlineCompletionStyles {
  397                insertion: HighlightStyle::default(),
  398                whitespace: HighlightStyle::default(),
  399            },
  400            unnecessary_code_fade: Default::default(),
  401        }
  402    }
  403}
  404
  405pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  406    let show_background = language_settings::language_settings(None, None, cx)
  407        .inlay_hints
  408        .show_background;
  409
  410    HighlightStyle {
  411        color: Some(cx.theme().status().hint),
  412        background_color: show_background.then(|| cx.theme().status().hint_background),
  413        ..HighlightStyle::default()
  414    }
  415}
  416
  417pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  418    InlineCompletionStyles {
  419        insertion: HighlightStyle {
  420            color: Some(cx.theme().status().predictive),
  421            ..HighlightStyle::default()
  422        },
  423        whitespace: HighlightStyle {
  424            background_color: Some(cx.theme().status().created_background),
  425            ..HighlightStyle::default()
  426        },
  427    }
  428}
  429
  430type CompletionId = usize;
  431
  432pub(crate) enum EditDisplayMode {
  433    TabAccept,
  434    DiffPopover,
  435    Inline,
  436}
  437
  438enum InlineCompletion {
  439    Edit {
  440        edits: Vec<(Range<Anchor>, String)>,
  441        edit_preview: Option<EditPreview>,
  442        display_mode: EditDisplayMode,
  443        snapshot: BufferSnapshot,
  444    },
  445    Move {
  446        target: Anchor,
  447        snapshot: BufferSnapshot,
  448    },
  449}
  450
  451struct InlineCompletionState {
  452    inlay_ids: Vec<InlayId>,
  453    completion: InlineCompletion,
  454    completion_id: Option<SharedString>,
  455    invalidation_range: Range<Anchor>,
  456}
  457
  458enum EditPredictionSettings {
  459    Disabled,
  460    Enabled {
  461        show_in_menu: bool,
  462        preview_requires_modifier: bool,
  463    },
  464}
  465
  466enum InlineCompletionHighlight {}
  467
  468#[derive(Debug, Clone)]
  469struct InlineDiagnostic {
  470    message: SharedString,
  471    group_id: usize,
  472    is_primary: bool,
  473    start: Point,
  474    severity: DiagnosticSeverity,
  475}
  476
  477pub enum MenuInlineCompletionsPolicy {
  478    Never,
  479    ByProvider,
  480}
  481
  482pub enum EditPredictionPreview {
  483    /// Modifier is not pressed
  484    Inactive,
  485    /// Modifier pressed
  486    Active {
  487        previous_scroll_position: Option<ScrollAnchor>,
  488    },
  489}
  490
  491#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  492struct EditorActionId(usize);
  493
  494impl EditorActionId {
  495    pub fn post_inc(&mut self) -> Self {
  496        let answer = self.0;
  497
  498        *self = Self(answer + 1);
  499
  500        Self(answer)
  501    }
  502}
  503
  504// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  505// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  506
  507type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  508type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  509
  510#[derive(Default)]
  511struct ScrollbarMarkerState {
  512    scrollbar_size: Size<Pixels>,
  513    dirty: bool,
  514    markers: Arc<[PaintQuad]>,
  515    pending_refresh: Option<Task<Result<()>>>,
  516}
  517
  518impl ScrollbarMarkerState {
  519    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  520        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  521    }
  522}
  523
  524#[derive(Clone, Debug)]
  525struct RunnableTasks {
  526    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  527    offset: multi_buffer::Anchor,
  528    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  529    column: u32,
  530    // Values of all named captures, including those starting with '_'
  531    extra_variables: HashMap<String, String>,
  532    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  533    context_range: Range<BufferOffset>,
  534}
  535
  536impl RunnableTasks {
  537    fn resolve<'a>(
  538        &'a self,
  539        cx: &'a task::TaskContext,
  540    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  541        self.templates.iter().filter_map(|(kind, template)| {
  542            template
  543                .resolve_task(&kind.to_id_base(), cx)
  544                .map(|task| (kind.clone(), task))
  545        })
  546    }
  547}
  548
  549#[derive(Clone)]
  550struct ResolvedTasks {
  551    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  552    position: Anchor,
  553}
  554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  555struct BufferOffset(usize);
  556
  557// Addons allow storing per-editor state in other crates (e.g. Vim)
  558pub trait Addon: 'static {
  559    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  560
  561    fn render_buffer_header_controls(
  562        &self,
  563        _: &ExcerptInfo,
  564        _: &Window,
  565        _: &App,
  566    ) -> Option<AnyElement> {
  567        None
  568    }
  569
  570    fn to_any(&self) -> &dyn std::any::Any;
  571}
  572
  573#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  574pub enum IsVimMode {
  575    Yes,
  576    No,
  577}
  578
  579/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  580///
  581/// See the [module level documentation](self) for more information.
  582pub struct Editor {
  583    focus_handle: FocusHandle,
  584    last_focused_descendant: Option<WeakFocusHandle>,
  585    /// The text buffer being edited
  586    buffer: Entity<MultiBuffer>,
  587    /// Map of how text in the buffer should be displayed.
  588    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  589    pub display_map: Entity<DisplayMap>,
  590    pub selections: SelectionsCollection,
  591    pub scroll_manager: ScrollManager,
  592    /// When inline assist editors are linked, they all render cursors because
  593    /// typing enters text into each of them, even the ones that aren't focused.
  594    pub(crate) show_cursor_when_unfocused: bool,
  595    columnar_selection_tail: Option<Anchor>,
  596    add_selections_state: Option<AddSelectionsState>,
  597    select_next_state: Option<SelectNextState>,
  598    select_prev_state: Option<SelectNextState>,
  599    selection_history: SelectionHistory,
  600    autoclose_regions: Vec<AutocloseRegion>,
  601    snippet_stack: InvalidationStack<SnippetState>,
  602    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  603    ime_transaction: Option<TransactionId>,
  604    active_diagnostics: Option<ActiveDiagnosticGroup>,
  605    show_inline_diagnostics: bool,
  606    inline_diagnostics_update: Task<()>,
  607    inline_diagnostics_enabled: bool,
  608    inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
  609    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  610
  611    // TODO: make this a access method
  612    pub project: Option<Entity<Project>>,
  613    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  614    completion_provider: Option<Box<dyn CompletionProvider>>,
  615    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  616    blink_manager: Entity<BlinkManager>,
  617    show_cursor_names: bool,
  618    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  619    pub show_local_selections: bool,
  620    mode: EditorMode,
  621    show_breadcrumbs: bool,
  622    show_gutter: bool,
  623    show_scrollbars: bool,
  624    show_line_numbers: Option<bool>,
  625    use_relative_line_numbers: Option<bool>,
  626    show_git_diff_gutter: Option<bool>,
  627    show_code_actions: Option<bool>,
  628    show_runnables: Option<bool>,
  629    show_wrap_guides: Option<bool>,
  630    show_indent_guides: Option<bool>,
  631    placeholder_text: Option<Arc<str>>,
  632    highlight_order: usize,
  633    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  634    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  635    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  636    scrollbar_marker_state: ScrollbarMarkerState,
  637    active_indent_guides_state: ActiveIndentGuidesState,
  638    nav_history: Option<ItemNavHistory>,
  639    context_menu: RefCell<Option<CodeContextMenu>>,
  640    mouse_context_menu: Option<MouseContextMenu>,
  641    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  642    signature_help_state: SignatureHelpState,
  643    auto_signature_help: Option<bool>,
  644    find_all_references_task_sources: Vec<Anchor>,
  645    next_completion_id: CompletionId,
  646    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  647    code_actions_task: Option<Task<Result<()>>>,
  648    selection_highlight_task: Option<Task<()>>,
  649    document_highlights_task: Option<Task<()>>,
  650    linked_editing_range_task: Option<Task<Option<()>>>,
  651    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  652    pending_rename: Option<RenameState>,
  653    searchable: bool,
  654    cursor_shape: CursorShape,
  655    current_line_highlight: Option<CurrentLineHighlight>,
  656    collapse_matches: bool,
  657    autoindent_mode: Option<AutoindentMode>,
  658    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  659    input_enabled: bool,
  660    use_modal_editing: bool,
  661    read_only: bool,
  662    leader_peer_id: Option<PeerId>,
  663    remote_id: Option<ViewId>,
  664    hover_state: HoverState,
  665    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  666    gutter_hovered: bool,
  667    hovered_link_state: Option<HoveredLinkState>,
  668    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  669    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  670    active_inline_completion: Option<InlineCompletionState>,
  671    /// Used to prevent flickering as the user types while the menu is open
  672    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  673    edit_prediction_settings: EditPredictionSettings,
  674    inline_completions_hidden_for_vim_mode: bool,
  675    show_inline_completions_override: Option<bool>,
  676    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  677    edit_prediction_preview: EditPredictionPreview,
  678    edit_prediction_indent_conflict: bool,
  679    edit_prediction_requires_modifier_in_indent_conflict: bool,
  680    inlay_hint_cache: InlayHintCache,
  681    next_inlay_id: usize,
  682    _subscriptions: Vec<Subscription>,
  683    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  684    gutter_dimensions: GutterDimensions,
  685    style: Option<EditorStyle>,
  686    text_style_refinement: Option<TextStyleRefinement>,
  687    next_editor_action_id: EditorActionId,
  688    editor_actions:
  689        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  690    use_autoclose: bool,
  691    use_auto_surround: bool,
  692    auto_replace_emoji_shortcode: bool,
  693    show_git_blame_gutter: bool,
  694    show_git_blame_inline: bool,
  695    show_git_blame_inline_delay_task: Option<Task<()>>,
  696    git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
  697    git_blame_inline_enabled: bool,
  698    serialize_dirty_buffers: bool,
  699    show_selection_menu: Option<bool>,
  700    blame: Option<Entity<GitBlame>>,
  701    blame_subscription: Option<Subscription>,
  702    custom_context_menu: Option<
  703        Box<
  704            dyn 'static
  705                + Fn(
  706                    &mut Self,
  707                    DisplayPoint,
  708                    &mut Window,
  709                    &mut Context<Self>,
  710                ) -> Option<Entity<ui::ContextMenu>>,
  711        >,
  712    >,
  713    last_bounds: Option<Bounds<Pixels>>,
  714    last_position_map: Option<Rc<PositionMap>>,
  715    expect_bounds_change: Option<Bounds<Pixels>>,
  716    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  717    tasks_update_task: Option<Task<()>>,
  718    in_project_search: bool,
  719    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  720    breadcrumb_header: Option<String>,
  721    focused_block: Option<FocusedBlock>,
  722    next_scroll_position: NextScrollCursorCenterTopBottom,
  723    addons: HashMap<TypeId, Box<dyn Addon>>,
  724    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  725    load_diff_task: Option<Shared<Task<()>>>,
  726    selection_mark_mode: bool,
  727    toggle_fold_multiple_buffers: Task<()>,
  728    _scroll_cursor_center_top_bottom_task: Task<()>,
  729    serialize_selections: Task<()>,
  730}
  731
  732#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  733enum NextScrollCursorCenterTopBottom {
  734    #[default]
  735    Center,
  736    Top,
  737    Bottom,
  738}
  739
  740impl NextScrollCursorCenterTopBottom {
  741    fn next(&self) -> Self {
  742        match self {
  743            Self::Center => Self::Top,
  744            Self::Top => Self::Bottom,
  745            Self::Bottom => Self::Center,
  746        }
  747    }
  748}
  749
  750#[derive(Clone)]
  751pub struct EditorSnapshot {
  752    pub mode: EditorMode,
  753    show_gutter: bool,
  754    show_line_numbers: Option<bool>,
  755    show_git_diff_gutter: Option<bool>,
  756    show_code_actions: Option<bool>,
  757    show_runnables: Option<bool>,
  758    git_blame_gutter_max_author_length: Option<usize>,
  759    pub display_snapshot: DisplaySnapshot,
  760    pub placeholder_text: Option<Arc<str>>,
  761    is_focused: bool,
  762    scroll_anchor: ScrollAnchor,
  763    ongoing_scroll: OngoingScroll,
  764    current_line_highlight: CurrentLineHighlight,
  765    gutter_hovered: bool,
  766}
  767
  768const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  769
  770#[derive(Default, Debug, Clone, Copy)]
  771pub struct GutterDimensions {
  772    pub left_padding: Pixels,
  773    pub right_padding: Pixels,
  774    pub width: Pixels,
  775    pub margin: Pixels,
  776    pub git_blame_entries_width: Option<Pixels>,
  777}
  778
  779impl GutterDimensions {
  780    /// The full width of the space taken up by the gutter.
  781    pub fn full_width(&self) -> Pixels {
  782        self.margin + self.width
  783    }
  784
  785    /// The width of the space reserved for the fold indicators,
  786    /// use alongside 'justify_end' and `gutter_width` to
  787    /// right align content with the line numbers
  788    pub fn fold_area_width(&self) -> Pixels {
  789        self.margin + self.right_padding
  790    }
  791}
  792
  793#[derive(Debug)]
  794pub struct RemoteSelection {
  795    pub replica_id: ReplicaId,
  796    pub selection: Selection<Anchor>,
  797    pub cursor_shape: CursorShape,
  798    pub peer_id: PeerId,
  799    pub line_mode: bool,
  800    pub participant_index: Option<ParticipantIndex>,
  801    pub user_name: Option<SharedString>,
  802}
  803
  804#[derive(Clone, Debug)]
  805struct SelectionHistoryEntry {
  806    selections: Arc<[Selection<Anchor>]>,
  807    select_next_state: Option<SelectNextState>,
  808    select_prev_state: Option<SelectNextState>,
  809    add_selections_state: Option<AddSelectionsState>,
  810}
  811
  812enum SelectionHistoryMode {
  813    Normal,
  814    Undoing,
  815    Redoing,
  816}
  817
  818#[derive(Clone, PartialEq, Eq, Hash)]
  819struct HoveredCursor {
  820    replica_id: u16,
  821    selection_id: usize,
  822}
  823
  824impl Default for SelectionHistoryMode {
  825    fn default() -> Self {
  826        Self::Normal
  827    }
  828}
  829
  830#[derive(Default)]
  831struct SelectionHistory {
  832    #[allow(clippy::type_complexity)]
  833    selections_by_transaction:
  834        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  835    mode: SelectionHistoryMode,
  836    undo_stack: VecDeque<SelectionHistoryEntry>,
  837    redo_stack: VecDeque<SelectionHistoryEntry>,
  838}
  839
  840impl SelectionHistory {
  841    fn insert_transaction(
  842        &mut self,
  843        transaction_id: TransactionId,
  844        selections: Arc<[Selection<Anchor>]>,
  845    ) {
  846        self.selections_by_transaction
  847            .insert(transaction_id, (selections, None));
  848    }
  849
  850    #[allow(clippy::type_complexity)]
  851    fn transaction(
  852        &self,
  853        transaction_id: TransactionId,
  854    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  855        self.selections_by_transaction.get(&transaction_id)
  856    }
  857
  858    #[allow(clippy::type_complexity)]
  859    fn transaction_mut(
  860        &mut self,
  861        transaction_id: TransactionId,
  862    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  863        self.selections_by_transaction.get_mut(&transaction_id)
  864    }
  865
  866    fn push(&mut self, entry: SelectionHistoryEntry) {
  867        if !entry.selections.is_empty() {
  868            match self.mode {
  869                SelectionHistoryMode::Normal => {
  870                    self.push_undo(entry);
  871                    self.redo_stack.clear();
  872                }
  873                SelectionHistoryMode::Undoing => self.push_redo(entry),
  874                SelectionHistoryMode::Redoing => self.push_undo(entry),
  875            }
  876        }
  877    }
  878
  879    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  880        if self
  881            .undo_stack
  882            .back()
  883            .map_or(true, |e| e.selections != entry.selections)
  884        {
  885            self.undo_stack.push_back(entry);
  886            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  887                self.undo_stack.pop_front();
  888            }
  889        }
  890    }
  891
  892    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  893        if self
  894            .redo_stack
  895            .back()
  896            .map_or(true, |e| e.selections != entry.selections)
  897        {
  898            self.redo_stack.push_back(entry);
  899            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  900                self.redo_stack.pop_front();
  901            }
  902        }
  903    }
  904}
  905
  906struct RowHighlight {
  907    index: usize,
  908    range: Range<Anchor>,
  909    color: Hsla,
  910    should_autoscroll: bool,
  911}
  912
  913#[derive(Clone, Debug)]
  914struct AddSelectionsState {
  915    above: bool,
  916    stack: Vec<usize>,
  917}
  918
  919#[derive(Clone)]
  920struct SelectNextState {
  921    query: AhoCorasick,
  922    wordwise: bool,
  923    done: bool,
  924}
  925
  926impl std::fmt::Debug for SelectNextState {
  927    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  928        f.debug_struct(std::any::type_name::<Self>())
  929            .field("wordwise", &self.wordwise)
  930            .field("done", &self.done)
  931            .finish()
  932    }
  933}
  934
  935#[derive(Debug)]
  936struct AutocloseRegion {
  937    selection_id: usize,
  938    range: Range<Anchor>,
  939    pair: BracketPair,
  940}
  941
  942#[derive(Debug)]
  943struct SnippetState {
  944    ranges: Vec<Vec<Range<Anchor>>>,
  945    active_index: usize,
  946    choices: Vec<Option<Vec<String>>>,
  947}
  948
  949#[doc(hidden)]
  950pub struct RenameState {
  951    pub range: Range<Anchor>,
  952    pub old_name: Arc<str>,
  953    pub editor: Entity<Editor>,
  954    block_id: CustomBlockId,
  955}
  956
  957struct InvalidationStack<T>(Vec<T>);
  958
  959struct RegisteredInlineCompletionProvider {
  960    provider: Arc<dyn InlineCompletionProviderHandle>,
  961    _subscription: Subscription,
  962}
  963
  964#[derive(Debug)]
  965struct ActiveDiagnosticGroup {
  966    primary_range: Range<Anchor>,
  967    primary_message: String,
  968    group_id: usize,
  969    blocks: HashMap<CustomBlockId, Diagnostic>,
  970    is_valid: bool,
  971}
  972
  973#[derive(Serialize, Deserialize, Clone, Debug)]
  974pub struct ClipboardSelection {
  975    /// The number of bytes in this selection.
  976    pub len: usize,
  977    /// Whether this was a full-line selection.
  978    pub is_entire_line: bool,
  979    /// The column where this selection originally started.
  980    pub start_column: u32,
  981}
  982
  983#[derive(Debug)]
  984pub(crate) struct NavigationData {
  985    cursor_anchor: Anchor,
  986    cursor_position: Point,
  987    scroll_anchor: ScrollAnchor,
  988    scroll_top_row: u32,
  989}
  990
  991#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  992pub enum GotoDefinitionKind {
  993    Symbol,
  994    Declaration,
  995    Type,
  996    Implementation,
  997}
  998
  999#[derive(Debug, Clone)]
 1000enum InlayHintRefreshReason {
 1001    Toggle(bool),
 1002    SettingsChange(InlayHintSettings),
 1003    NewLinesShown,
 1004    BufferEdited(HashSet<Arc<Language>>),
 1005    RefreshRequested,
 1006    ExcerptsRemoved(Vec<ExcerptId>),
 1007}
 1008
 1009impl InlayHintRefreshReason {
 1010    fn description(&self) -> &'static str {
 1011        match self {
 1012            Self::Toggle(_) => "toggle",
 1013            Self::SettingsChange(_) => "settings change",
 1014            Self::NewLinesShown => "new lines shown",
 1015            Self::BufferEdited(_) => "buffer edited",
 1016            Self::RefreshRequested => "refresh requested",
 1017            Self::ExcerptsRemoved(_) => "excerpts removed",
 1018        }
 1019    }
 1020}
 1021
 1022pub enum FormatTarget {
 1023    Buffers,
 1024    Ranges(Vec<Range<MultiBufferPoint>>),
 1025}
 1026
 1027pub(crate) struct FocusedBlock {
 1028    id: BlockId,
 1029    focus_handle: WeakFocusHandle,
 1030}
 1031
 1032#[derive(Clone)]
 1033enum JumpData {
 1034    MultiBufferRow {
 1035        row: MultiBufferRow,
 1036        line_offset_from_top: u32,
 1037    },
 1038    MultiBufferPoint {
 1039        excerpt_id: ExcerptId,
 1040        position: Point,
 1041        anchor: text::Anchor,
 1042        line_offset_from_top: u32,
 1043    },
 1044}
 1045
 1046pub enum MultibufferSelectionMode {
 1047    First,
 1048    All,
 1049}
 1050
 1051impl Editor {
 1052    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1053        let buffer = cx.new(|cx| Buffer::local("", cx));
 1054        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1055        Self::new(
 1056            EditorMode::SingleLine { auto_width: false },
 1057            buffer,
 1058            None,
 1059            false,
 1060            window,
 1061            cx,
 1062        )
 1063    }
 1064
 1065    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1066        let buffer = cx.new(|cx| Buffer::local("", cx));
 1067        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1068        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1069    }
 1070
 1071    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1072        let buffer = cx.new(|cx| Buffer::local("", cx));
 1073        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1074        Self::new(
 1075            EditorMode::SingleLine { auto_width: true },
 1076            buffer,
 1077            None,
 1078            false,
 1079            window,
 1080            cx,
 1081        )
 1082    }
 1083
 1084    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1085        let buffer = cx.new(|cx| Buffer::local("", cx));
 1086        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1087        Self::new(
 1088            EditorMode::AutoHeight { max_lines },
 1089            buffer,
 1090            None,
 1091            false,
 1092            window,
 1093            cx,
 1094        )
 1095    }
 1096
 1097    pub fn for_buffer(
 1098        buffer: Entity<Buffer>,
 1099        project: Option<Entity<Project>>,
 1100        window: &mut Window,
 1101        cx: &mut Context<Self>,
 1102    ) -> Self {
 1103        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1104        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1105    }
 1106
 1107    pub fn for_multibuffer(
 1108        buffer: Entity<MultiBuffer>,
 1109        project: Option<Entity<Project>>,
 1110        show_excerpt_controls: bool,
 1111        window: &mut Window,
 1112        cx: &mut Context<Self>,
 1113    ) -> Self {
 1114        Self::new(
 1115            EditorMode::Full,
 1116            buffer,
 1117            project,
 1118            show_excerpt_controls,
 1119            window,
 1120            cx,
 1121        )
 1122    }
 1123
 1124    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1125        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1126        let mut clone = Self::new(
 1127            self.mode,
 1128            self.buffer.clone(),
 1129            self.project.clone(),
 1130            show_excerpt_controls,
 1131            window,
 1132            cx,
 1133        );
 1134        self.display_map.update(cx, |display_map, cx| {
 1135            let snapshot = display_map.snapshot(cx);
 1136            clone.display_map.update(cx, |display_map, cx| {
 1137                display_map.set_state(&snapshot, cx);
 1138            });
 1139        });
 1140        clone.selections.clone_state(&self.selections);
 1141        clone.scroll_manager.clone_state(&self.scroll_manager);
 1142        clone.searchable = self.searchable;
 1143        clone
 1144    }
 1145
 1146    pub fn new(
 1147        mode: EditorMode,
 1148        buffer: Entity<MultiBuffer>,
 1149        project: Option<Entity<Project>>,
 1150        show_excerpt_controls: bool,
 1151        window: &mut Window,
 1152        cx: &mut Context<Self>,
 1153    ) -> Self {
 1154        let style = window.text_style();
 1155        let font_size = style.font_size.to_pixels(window.rem_size());
 1156        let editor = cx.entity().downgrade();
 1157        let fold_placeholder = FoldPlaceholder {
 1158            constrain_width: true,
 1159            render: Arc::new(move |fold_id, fold_range, cx| {
 1160                let editor = editor.clone();
 1161                div()
 1162                    .id(fold_id)
 1163                    .bg(cx.theme().colors().ghost_element_background)
 1164                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1165                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1166                    .rounded_sm()
 1167                    .size_full()
 1168                    .cursor_pointer()
 1169                    .child("")
 1170                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1171                    .on_click(move |_, _window, cx| {
 1172                        editor
 1173                            .update(cx, |editor, cx| {
 1174                                editor.unfold_ranges(
 1175                                    &[fold_range.start..fold_range.end],
 1176                                    true,
 1177                                    false,
 1178                                    cx,
 1179                                );
 1180                                cx.stop_propagation();
 1181                            })
 1182                            .ok();
 1183                    })
 1184                    .into_any()
 1185            }),
 1186            merge_adjacent: true,
 1187            ..Default::default()
 1188        };
 1189        let display_map = cx.new(|cx| {
 1190            DisplayMap::new(
 1191                buffer.clone(),
 1192                style.font(),
 1193                font_size,
 1194                None,
 1195                show_excerpt_controls,
 1196                FILE_HEADER_HEIGHT,
 1197                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1198                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1199                fold_placeholder,
 1200                cx,
 1201            )
 1202        });
 1203
 1204        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1205
 1206        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1207
 1208        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1209            .then(|| language_settings::SoftWrap::None);
 1210
 1211        let mut project_subscriptions = Vec::new();
 1212        if mode == EditorMode::Full {
 1213            if let Some(project) = project.as_ref() {
 1214                if buffer.read(cx).is_singleton() {
 1215                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1216                        cx.emit(EditorEvent::TitleChanged);
 1217                    }));
 1218                }
 1219                project_subscriptions.push(cx.subscribe_in(
 1220                    project,
 1221                    window,
 1222                    |editor, _, event, window, cx| {
 1223                        if let project::Event::RefreshInlayHints = event {
 1224                            editor
 1225                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1226                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1227                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1228                                let focus_handle = editor.focus_handle(cx);
 1229                                if focus_handle.is_focused(window) {
 1230                                    let snapshot = buffer.read(cx).snapshot();
 1231                                    for (range, snippet) in snippet_edits {
 1232                                        let editor_range =
 1233                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1234                                        editor
 1235                                            .insert_snippet(
 1236                                                &[editor_range],
 1237                                                snippet.clone(),
 1238                                                window,
 1239                                                cx,
 1240                                            )
 1241                                            .ok();
 1242                                    }
 1243                                }
 1244                            }
 1245                        }
 1246                    },
 1247                ));
 1248                if let Some(task_inventory) = project
 1249                    .read(cx)
 1250                    .task_store()
 1251                    .read(cx)
 1252                    .task_inventory()
 1253                    .cloned()
 1254                {
 1255                    project_subscriptions.push(cx.observe_in(
 1256                        &task_inventory,
 1257                        window,
 1258                        |editor, _, window, cx| {
 1259                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1260                        },
 1261                    ));
 1262                }
 1263            }
 1264        }
 1265
 1266        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1267
 1268        let inlay_hint_settings =
 1269            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1270        let focus_handle = cx.focus_handle();
 1271        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1272            .detach();
 1273        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1274            .detach();
 1275        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1276            .detach();
 1277        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1278            .detach();
 1279
 1280        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1281            Some(false)
 1282        } else {
 1283            None
 1284        };
 1285
 1286        let mut code_action_providers = Vec::new();
 1287        let mut load_uncommitted_diff = None;
 1288        if let Some(project) = project.clone() {
 1289            load_uncommitted_diff = Some(
 1290                get_uncommitted_diff_for_buffer(
 1291                    &project,
 1292                    buffer.read(cx).all_buffers(),
 1293                    buffer.clone(),
 1294                    cx,
 1295                )
 1296                .shared(),
 1297            );
 1298            code_action_providers.push(Rc::new(project) as Rc<_>);
 1299        }
 1300
 1301        let mut this = Self {
 1302            focus_handle,
 1303            show_cursor_when_unfocused: false,
 1304            last_focused_descendant: None,
 1305            buffer: buffer.clone(),
 1306            display_map: display_map.clone(),
 1307            selections,
 1308            scroll_manager: ScrollManager::new(cx),
 1309            columnar_selection_tail: None,
 1310            add_selections_state: None,
 1311            select_next_state: None,
 1312            select_prev_state: None,
 1313            selection_history: Default::default(),
 1314            autoclose_regions: Default::default(),
 1315            snippet_stack: Default::default(),
 1316            select_larger_syntax_node_stack: Vec::new(),
 1317            ime_transaction: Default::default(),
 1318            active_diagnostics: None,
 1319            show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
 1320            inline_diagnostics_update: Task::ready(()),
 1321            inline_diagnostics: Vec::new(),
 1322            soft_wrap_mode_override,
 1323            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1324            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1325            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1326            project,
 1327            blink_manager: blink_manager.clone(),
 1328            show_local_selections: true,
 1329            show_scrollbars: true,
 1330            mode,
 1331            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1332            show_gutter: mode == EditorMode::Full,
 1333            show_line_numbers: None,
 1334            use_relative_line_numbers: None,
 1335            show_git_diff_gutter: None,
 1336            show_code_actions: None,
 1337            show_runnables: None,
 1338            show_wrap_guides: None,
 1339            show_indent_guides,
 1340            placeholder_text: None,
 1341            highlight_order: 0,
 1342            highlighted_rows: HashMap::default(),
 1343            background_highlights: Default::default(),
 1344            gutter_highlights: TreeMap::default(),
 1345            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1346            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1347            nav_history: None,
 1348            context_menu: RefCell::new(None),
 1349            mouse_context_menu: None,
 1350            completion_tasks: Default::default(),
 1351            signature_help_state: SignatureHelpState::default(),
 1352            auto_signature_help: None,
 1353            find_all_references_task_sources: Vec::new(),
 1354            next_completion_id: 0,
 1355            next_inlay_id: 0,
 1356            code_action_providers,
 1357            available_code_actions: Default::default(),
 1358            code_actions_task: Default::default(),
 1359            selection_highlight_task: Default::default(),
 1360            document_highlights_task: Default::default(),
 1361            linked_editing_range_task: Default::default(),
 1362            pending_rename: Default::default(),
 1363            searchable: true,
 1364            cursor_shape: EditorSettings::get_global(cx)
 1365                .cursor_shape
 1366                .unwrap_or_default(),
 1367            current_line_highlight: None,
 1368            autoindent_mode: Some(AutoindentMode::EachLine),
 1369            collapse_matches: false,
 1370            workspace: None,
 1371            input_enabled: true,
 1372            use_modal_editing: mode == EditorMode::Full,
 1373            read_only: false,
 1374            use_autoclose: true,
 1375            use_auto_surround: true,
 1376            auto_replace_emoji_shortcode: false,
 1377            leader_peer_id: None,
 1378            remote_id: None,
 1379            hover_state: Default::default(),
 1380            pending_mouse_down: None,
 1381            hovered_link_state: Default::default(),
 1382            edit_prediction_provider: None,
 1383            active_inline_completion: None,
 1384            stale_inline_completion_in_menu: None,
 1385            edit_prediction_preview: EditPredictionPreview::Inactive,
 1386            inline_diagnostics_enabled: mode == EditorMode::Full,
 1387            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1388
 1389            gutter_hovered: false,
 1390            pixel_position_of_newest_cursor: None,
 1391            last_bounds: None,
 1392            last_position_map: None,
 1393            expect_bounds_change: None,
 1394            gutter_dimensions: GutterDimensions::default(),
 1395            style: None,
 1396            show_cursor_names: false,
 1397            hovered_cursors: Default::default(),
 1398            next_editor_action_id: EditorActionId::default(),
 1399            editor_actions: Rc::default(),
 1400            inline_completions_hidden_for_vim_mode: false,
 1401            show_inline_completions_override: None,
 1402            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1403            edit_prediction_settings: EditPredictionSettings::Disabled,
 1404            edit_prediction_indent_conflict: false,
 1405            edit_prediction_requires_modifier_in_indent_conflict: true,
 1406            custom_context_menu: None,
 1407            show_git_blame_gutter: false,
 1408            show_git_blame_inline: false,
 1409            show_selection_menu: None,
 1410            show_git_blame_inline_delay_task: None,
 1411            git_blame_inline_tooltip: None,
 1412            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1413            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1414                .session
 1415                .restore_unsaved_buffers,
 1416            blame: None,
 1417            blame_subscription: None,
 1418            tasks: Default::default(),
 1419            _subscriptions: vec![
 1420                cx.observe(&buffer, Self::on_buffer_changed),
 1421                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1422                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1423                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1424                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1425                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1426                cx.observe_window_activation(window, |editor, window, cx| {
 1427                    let active = window.is_window_active();
 1428                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1429                        if active {
 1430                            blink_manager.enable(cx);
 1431                        } else {
 1432                            blink_manager.disable(cx);
 1433                        }
 1434                    });
 1435                }),
 1436            ],
 1437            tasks_update_task: None,
 1438            linked_edit_ranges: Default::default(),
 1439            in_project_search: false,
 1440            previous_search_ranges: None,
 1441            breadcrumb_header: None,
 1442            focused_block: None,
 1443            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1444            addons: HashMap::default(),
 1445            registered_buffers: HashMap::default(),
 1446            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1447            selection_mark_mode: false,
 1448            toggle_fold_multiple_buffers: Task::ready(()),
 1449            serialize_selections: Task::ready(()),
 1450            text_style_refinement: None,
 1451            load_diff_task: load_uncommitted_diff,
 1452        };
 1453        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1454        this._subscriptions.extend(project_subscriptions);
 1455
 1456        this.end_selection(window, cx);
 1457        this.scroll_manager.show_scrollbar(window, cx);
 1458
 1459        if mode == EditorMode::Full {
 1460            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1461            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1462
 1463            if this.git_blame_inline_enabled {
 1464                this.git_blame_inline_enabled = true;
 1465                this.start_git_blame_inline(false, window, cx);
 1466            }
 1467
 1468            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1469                if let Some(project) = this.project.as_ref() {
 1470                    let handle = project.update(cx, |project, cx| {
 1471                        project.register_buffer_with_language_servers(&buffer, cx)
 1472                    });
 1473                    this.registered_buffers
 1474                        .insert(buffer.read(cx).remote_id(), handle);
 1475                }
 1476            }
 1477        }
 1478
 1479        this.report_editor_event("Editor Opened", None, cx);
 1480        this
 1481    }
 1482
 1483    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1484        self.mouse_context_menu
 1485            .as_ref()
 1486            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1487    }
 1488
 1489    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1490        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1491    }
 1492
 1493    fn key_context_internal(
 1494        &self,
 1495        has_active_edit_prediction: bool,
 1496        window: &Window,
 1497        cx: &App,
 1498    ) -> KeyContext {
 1499        let mut key_context = KeyContext::new_with_defaults();
 1500        key_context.add("Editor");
 1501        let mode = match self.mode {
 1502            EditorMode::SingleLine { .. } => "single_line",
 1503            EditorMode::AutoHeight { .. } => "auto_height",
 1504            EditorMode::Full => "full",
 1505        };
 1506
 1507        if EditorSettings::jupyter_enabled(cx) {
 1508            key_context.add("jupyter");
 1509        }
 1510
 1511        key_context.set("mode", mode);
 1512        if self.pending_rename.is_some() {
 1513            key_context.add("renaming");
 1514        }
 1515
 1516        match self.context_menu.borrow().as_ref() {
 1517            Some(CodeContextMenu::Completions(_)) => {
 1518                key_context.add("menu");
 1519                key_context.add("showing_completions");
 1520            }
 1521            Some(CodeContextMenu::CodeActions(_)) => {
 1522                key_context.add("menu");
 1523                key_context.add("showing_code_actions")
 1524            }
 1525            None => {}
 1526        }
 1527
 1528        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1529        if !self.focus_handle(cx).contains_focused(window, cx)
 1530            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1531        {
 1532            for addon in self.addons.values() {
 1533                addon.extend_key_context(&mut key_context, cx)
 1534            }
 1535        }
 1536
 1537        if let Some(extension) = self
 1538            .buffer
 1539            .read(cx)
 1540            .as_singleton()
 1541            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1542        {
 1543            key_context.set("extension", extension.to_string());
 1544        }
 1545
 1546        if has_active_edit_prediction {
 1547            if self.edit_prediction_in_conflict() {
 1548                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1549            } else {
 1550                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1551                key_context.add("copilot_suggestion");
 1552            }
 1553        }
 1554
 1555        if self.selection_mark_mode {
 1556            key_context.add("selection_mode");
 1557        }
 1558
 1559        key_context
 1560    }
 1561
 1562    pub fn edit_prediction_in_conflict(&self) -> bool {
 1563        if !self.show_edit_predictions_in_menu() {
 1564            return false;
 1565        }
 1566
 1567        let showing_completions = self
 1568            .context_menu
 1569            .borrow()
 1570            .as_ref()
 1571            .map_or(false, |context| {
 1572                matches!(context, CodeContextMenu::Completions(_))
 1573            });
 1574
 1575        showing_completions
 1576            || self.edit_prediction_requires_modifier()
 1577            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1578            // bindings to insert tab characters.
 1579            || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
 1580    }
 1581
 1582    pub fn accept_edit_prediction_keybind(
 1583        &self,
 1584        window: &Window,
 1585        cx: &App,
 1586    ) -> AcceptEditPredictionBinding {
 1587        let key_context = self.key_context_internal(true, window, cx);
 1588        let in_conflict = self.edit_prediction_in_conflict();
 1589
 1590        AcceptEditPredictionBinding(
 1591            window
 1592                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1593                .into_iter()
 1594                .filter(|binding| {
 1595                    !in_conflict
 1596                        || binding
 1597                            .keystrokes()
 1598                            .first()
 1599                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1600                })
 1601                .rev()
 1602                .min_by_key(|binding| {
 1603                    binding
 1604                        .keystrokes()
 1605                        .first()
 1606                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1607                }),
 1608        )
 1609    }
 1610
 1611    pub fn new_file(
 1612        workspace: &mut Workspace,
 1613        _: &workspace::NewFile,
 1614        window: &mut Window,
 1615        cx: &mut Context<Workspace>,
 1616    ) {
 1617        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1618            "Failed to create buffer",
 1619            window,
 1620            cx,
 1621            |e, _, _| match e.error_code() {
 1622                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1623                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1624                e.error_tag("required").unwrap_or("the latest version")
 1625            )),
 1626                _ => None,
 1627            },
 1628        );
 1629    }
 1630
 1631    pub fn new_in_workspace(
 1632        workspace: &mut Workspace,
 1633        window: &mut Window,
 1634        cx: &mut Context<Workspace>,
 1635    ) -> Task<Result<Entity<Editor>>> {
 1636        let project = workspace.project().clone();
 1637        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1638
 1639        cx.spawn_in(window, |workspace, mut cx| async move {
 1640            let buffer = create.await?;
 1641            workspace.update_in(&mut cx, |workspace, window, cx| {
 1642                let editor =
 1643                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1644                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1645                editor
 1646            })
 1647        })
 1648    }
 1649
 1650    fn new_file_vertical(
 1651        workspace: &mut Workspace,
 1652        _: &workspace::NewFileSplitVertical,
 1653        window: &mut Window,
 1654        cx: &mut Context<Workspace>,
 1655    ) {
 1656        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1657    }
 1658
 1659    fn new_file_horizontal(
 1660        workspace: &mut Workspace,
 1661        _: &workspace::NewFileSplitHorizontal,
 1662        window: &mut Window,
 1663        cx: &mut Context<Workspace>,
 1664    ) {
 1665        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1666    }
 1667
 1668    fn new_file_in_direction(
 1669        workspace: &mut Workspace,
 1670        direction: SplitDirection,
 1671        window: &mut Window,
 1672        cx: &mut Context<Workspace>,
 1673    ) {
 1674        let project = workspace.project().clone();
 1675        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1676
 1677        cx.spawn_in(window, |workspace, mut cx| async move {
 1678            let buffer = create.await?;
 1679            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1680                workspace.split_item(
 1681                    direction,
 1682                    Box::new(
 1683                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1684                    ),
 1685                    window,
 1686                    cx,
 1687                )
 1688            })?;
 1689            anyhow::Ok(())
 1690        })
 1691        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1692            match e.error_code() {
 1693                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1694                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1695                e.error_tag("required").unwrap_or("the latest version")
 1696            )),
 1697                _ => None,
 1698            }
 1699        });
 1700    }
 1701
 1702    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1703        self.leader_peer_id
 1704    }
 1705
 1706    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1707        &self.buffer
 1708    }
 1709
 1710    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1711        self.workspace.as_ref()?.0.upgrade()
 1712    }
 1713
 1714    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1715        self.buffer().read(cx).title(cx)
 1716    }
 1717
 1718    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1719        let git_blame_gutter_max_author_length = self
 1720            .render_git_blame_gutter(cx)
 1721            .then(|| {
 1722                if let Some(blame) = self.blame.as_ref() {
 1723                    let max_author_length =
 1724                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1725                    Some(max_author_length)
 1726                } else {
 1727                    None
 1728                }
 1729            })
 1730            .flatten();
 1731
 1732        EditorSnapshot {
 1733            mode: self.mode,
 1734            show_gutter: self.show_gutter,
 1735            show_line_numbers: self.show_line_numbers,
 1736            show_git_diff_gutter: self.show_git_diff_gutter,
 1737            show_code_actions: self.show_code_actions,
 1738            show_runnables: self.show_runnables,
 1739            git_blame_gutter_max_author_length,
 1740            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1741            scroll_anchor: self.scroll_manager.anchor(),
 1742            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1743            placeholder_text: self.placeholder_text.clone(),
 1744            is_focused: self.focus_handle.is_focused(window),
 1745            current_line_highlight: self
 1746                .current_line_highlight
 1747                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1748            gutter_hovered: self.gutter_hovered,
 1749        }
 1750    }
 1751
 1752    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1753        self.buffer.read(cx).language_at(point, cx)
 1754    }
 1755
 1756    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1757        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1758    }
 1759
 1760    pub fn active_excerpt(
 1761        &self,
 1762        cx: &App,
 1763    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1764        self.buffer
 1765            .read(cx)
 1766            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1767    }
 1768
 1769    pub fn mode(&self) -> EditorMode {
 1770        self.mode
 1771    }
 1772
 1773    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1774        self.collaboration_hub.as_deref()
 1775    }
 1776
 1777    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1778        self.collaboration_hub = Some(hub);
 1779    }
 1780
 1781    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1782        self.in_project_search = in_project_search;
 1783    }
 1784
 1785    pub fn set_custom_context_menu(
 1786        &mut self,
 1787        f: impl 'static
 1788            + Fn(
 1789                &mut Self,
 1790                DisplayPoint,
 1791                &mut Window,
 1792                &mut Context<Self>,
 1793            ) -> Option<Entity<ui::ContextMenu>>,
 1794    ) {
 1795        self.custom_context_menu = Some(Box::new(f))
 1796    }
 1797
 1798    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1799        self.completion_provider = provider;
 1800    }
 1801
 1802    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1803        self.semantics_provider.clone()
 1804    }
 1805
 1806    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1807        self.semantics_provider = provider;
 1808    }
 1809
 1810    pub fn set_edit_prediction_provider<T>(
 1811        &mut self,
 1812        provider: Option<Entity<T>>,
 1813        window: &mut Window,
 1814        cx: &mut Context<Self>,
 1815    ) where
 1816        T: EditPredictionProvider,
 1817    {
 1818        self.edit_prediction_provider =
 1819            provider.map(|provider| RegisteredInlineCompletionProvider {
 1820                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1821                    if this.focus_handle.is_focused(window) {
 1822                        this.update_visible_inline_completion(window, cx);
 1823                    }
 1824                }),
 1825                provider: Arc::new(provider),
 1826            });
 1827        self.refresh_inline_completion(false, false, window, cx);
 1828    }
 1829
 1830    pub fn placeholder_text(&self) -> Option<&str> {
 1831        self.placeholder_text.as_deref()
 1832    }
 1833
 1834    pub fn set_placeholder_text(
 1835        &mut self,
 1836        placeholder_text: impl Into<Arc<str>>,
 1837        cx: &mut Context<Self>,
 1838    ) {
 1839        let placeholder_text = Some(placeholder_text.into());
 1840        if self.placeholder_text != placeholder_text {
 1841            self.placeholder_text = placeholder_text;
 1842            cx.notify();
 1843        }
 1844    }
 1845
 1846    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1847        self.cursor_shape = cursor_shape;
 1848
 1849        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1850        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1851
 1852        cx.notify();
 1853    }
 1854
 1855    pub fn set_current_line_highlight(
 1856        &mut self,
 1857        current_line_highlight: Option<CurrentLineHighlight>,
 1858    ) {
 1859        self.current_line_highlight = current_line_highlight;
 1860    }
 1861
 1862    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1863        self.collapse_matches = collapse_matches;
 1864    }
 1865
 1866    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1867        let buffers = self.buffer.read(cx).all_buffers();
 1868        let Some(project) = self.project.as_ref() else {
 1869            return;
 1870        };
 1871        project.update(cx, |project, cx| {
 1872            for buffer in buffers {
 1873                self.registered_buffers
 1874                    .entry(buffer.read(cx).remote_id())
 1875                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1876            }
 1877        })
 1878    }
 1879
 1880    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1881        if self.collapse_matches {
 1882            return range.start..range.start;
 1883        }
 1884        range.clone()
 1885    }
 1886
 1887    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1888        if self.display_map.read(cx).clip_at_line_ends != clip {
 1889            self.display_map
 1890                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1891        }
 1892    }
 1893
 1894    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1895        self.input_enabled = input_enabled;
 1896    }
 1897
 1898    pub fn set_inline_completions_hidden_for_vim_mode(
 1899        &mut self,
 1900        hidden: bool,
 1901        window: &mut Window,
 1902        cx: &mut Context<Self>,
 1903    ) {
 1904        if hidden != self.inline_completions_hidden_for_vim_mode {
 1905            self.inline_completions_hidden_for_vim_mode = hidden;
 1906            if hidden {
 1907                self.update_visible_inline_completion(window, cx);
 1908            } else {
 1909                self.refresh_inline_completion(true, false, window, cx);
 1910            }
 1911        }
 1912    }
 1913
 1914    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1915        self.menu_inline_completions_policy = value;
 1916    }
 1917
 1918    pub fn set_autoindent(&mut self, autoindent: bool) {
 1919        if autoindent {
 1920            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1921        } else {
 1922            self.autoindent_mode = None;
 1923        }
 1924    }
 1925
 1926    pub fn read_only(&self, cx: &App) -> bool {
 1927        self.read_only || self.buffer.read(cx).read_only()
 1928    }
 1929
 1930    pub fn set_read_only(&mut self, read_only: bool) {
 1931        self.read_only = read_only;
 1932    }
 1933
 1934    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1935        self.use_autoclose = autoclose;
 1936    }
 1937
 1938    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1939        self.use_auto_surround = auto_surround;
 1940    }
 1941
 1942    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1943        self.auto_replace_emoji_shortcode = auto_replace;
 1944    }
 1945
 1946    pub fn toggle_inline_completions(
 1947        &mut self,
 1948        _: &ToggleEditPrediction,
 1949        window: &mut Window,
 1950        cx: &mut Context<Self>,
 1951    ) {
 1952        if self.show_inline_completions_override.is_some() {
 1953            self.set_show_edit_predictions(None, window, cx);
 1954        } else {
 1955            let show_edit_predictions = !self.edit_predictions_enabled();
 1956            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1957        }
 1958    }
 1959
 1960    pub fn set_show_edit_predictions(
 1961        &mut self,
 1962        show_edit_predictions: Option<bool>,
 1963        window: &mut Window,
 1964        cx: &mut Context<Self>,
 1965    ) {
 1966        self.show_inline_completions_override = show_edit_predictions;
 1967
 1968        if let Some(false) = show_edit_predictions {
 1969            self.discard_inline_completion(false, cx);
 1970        } else {
 1971            self.refresh_inline_completion(false, true, window, cx);
 1972        }
 1973    }
 1974
 1975    fn inline_completions_disabled_in_scope(
 1976        &self,
 1977        buffer: &Entity<Buffer>,
 1978        buffer_position: language::Anchor,
 1979        cx: &App,
 1980    ) -> bool {
 1981        let snapshot = buffer.read(cx).snapshot();
 1982        let settings = snapshot.settings_at(buffer_position, cx);
 1983
 1984        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1985            return false;
 1986        };
 1987
 1988        scope.override_name().map_or(false, |scope_name| {
 1989            settings
 1990                .edit_predictions_disabled_in
 1991                .iter()
 1992                .any(|s| s == scope_name)
 1993        })
 1994    }
 1995
 1996    pub fn set_use_modal_editing(&mut self, to: bool) {
 1997        self.use_modal_editing = to;
 1998    }
 1999
 2000    pub fn use_modal_editing(&self) -> bool {
 2001        self.use_modal_editing
 2002    }
 2003
 2004    fn selections_did_change(
 2005        &mut self,
 2006        local: bool,
 2007        old_cursor_position: &Anchor,
 2008        show_completions: bool,
 2009        window: &mut Window,
 2010        cx: &mut Context<Self>,
 2011    ) {
 2012        window.invalidate_character_coordinates();
 2013
 2014        // Copy selections to primary selection buffer
 2015        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2016        if local {
 2017            let selections = self.selections.all::<usize>(cx);
 2018            let buffer_handle = self.buffer.read(cx).read(cx);
 2019
 2020            let mut text = String::new();
 2021            for (index, selection) in selections.iter().enumerate() {
 2022                let text_for_selection = buffer_handle
 2023                    .text_for_range(selection.start..selection.end)
 2024                    .collect::<String>();
 2025
 2026                text.push_str(&text_for_selection);
 2027                if index != selections.len() - 1 {
 2028                    text.push('\n');
 2029                }
 2030            }
 2031
 2032            if !text.is_empty() {
 2033                cx.write_to_primary(ClipboardItem::new_string(text));
 2034            }
 2035        }
 2036
 2037        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2038            self.buffer.update(cx, |buffer, cx| {
 2039                buffer.set_active_selections(
 2040                    &self.selections.disjoint_anchors(),
 2041                    self.selections.line_mode,
 2042                    self.cursor_shape,
 2043                    cx,
 2044                )
 2045            });
 2046        }
 2047        let display_map = self
 2048            .display_map
 2049            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2050        let buffer = &display_map.buffer_snapshot;
 2051        self.add_selections_state = None;
 2052        self.select_next_state = None;
 2053        self.select_prev_state = None;
 2054        self.select_larger_syntax_node_stack.clear();
 2055        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2056        self.snippet_stack
 2057            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2058        self.take_rename(false, window, cx);
 2059
 2060        let new_cursor_position = self.selections.newest_anchor().head();
 2061
 2062        self.push_to_nav_history(
 2063            *old_cursor_position,
 2064            Some(new_cursor_position.to_point(buffer)),
 2065            cx,
 2066        );
 2067
 2068        if local {
 2069            let new_cursor_position = self.selections.newest_anchor().head();
 2070            let mut context_menu = self.context_menu.borrow_mut();
 2071            let completion_menu = match context_menu.as_ref() {
 2072                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2073                _ => {
 2074                    *context_menu = None;
 2075                    None
 2076                }
 2077            };
 2078            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2079                if !self.registered_buffers.contains_key(&buffer_id) {
 2080                    if let Some(project) = self.project.as_ref() {
 2081                        project.update(cx, |project, cx| {
 2082                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2083                                return;
 2084                            };
 2085                            self.registered_buffers.insert(
 2086                                buffer_id,
 2087                                project.register_buffer_with_language_servers(&buffer, cx),
 2088                            );
 2089                        })
 2090                    }
 2091                }
 2092            }
 2093
 2094            if let Some(completion_menu) = completion_menu {
 2095                let cursor_position = new_cursor_position.to_offset(buffer);
 2096                let (word_range, kind) =
 2097                    buffer.surrounding_word(completion_menu.initial_position, true);
 2098                if kind == Some(CharKind::Word)
 2099                    && word_range.to_inclusive().contains(&cursor_position)
 2100                {
 2101                    let mut completion_menu = completion_menu.clone();
 2102                    drop(context_menu);
 2103
 2104                    let query = Self::completion_query(buffer, cursor_position);
 2105                    cx.spawn(move |this, mut cx| async move {
 2106                        completion_menu
 2107                            .filter(query.as_deref(), cx.background_executor().clone())
 2108                            .await;
 2109
 2110                        this.update(&mut cx, |this, cx| {
 2111                            let mut context_menu = this.context_menu.borrow_mut();
 2112                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2113                            else {
 2114                                return;
 2115                            };
 2116
 2117                            if menu.id > completion_menu.id {
 2118                                return;
 2119                            }
 2120
 2121                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2122                            drop(context_menu);
 2123                            cx.notify();
 2124                        })
 2125                    })
 2126                    .detach();
 2127
 2128                    if show_completions {
 2129                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2130                    }
 2131                } else {
 2132                    drop(context_menu);
 2133                    self.hide_context_menu(window, cx);
 2134                }
 2135            } else {
 2136                drop(context_menu);
 2137            }
 2138
 2139            hide_hover(self, cx);
 2140
 2141            if old_cursor_position.to_display_point(&display_map).row()
 2142                != new_cursor_position.to_display_point(&display_map).row()
 2143            {
 2144                self.available_code_actions.take();
 2145            }
 2146            self.refresh_code_actions(window, cx);
 2147            self.refresh_document_highlights(cx);
 2148            self.refresh_selected_text_highlights(window, cx);
 2149            refresh_matching_bracket_highlights(self, window, cx);
 2150            self.update_visible_inline_completion(window, cx);
 2151            self.edit_prediction_requires_modifier_in_indent_conflict = true;
 2152            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2153            if self.git_blame_inline_enabled {
 2154                self.start_inline_blame_timer(window, cx);
 2155            }
 2156        }
 2157
 2158        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2159        cx.emit(EditorEvent::SelectionsChanged { local });
 2160
 2161        let selections = &self.selections.disjoint;
 2162        if selections.len() == 1 {
 2163            cx.emit(SearchEvent::ActiveMatchChanged)
 2164        }
 2165        if local
 2166            && self.is_singleton(cx)
 2167            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2168        {
 2169            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2170                let background_executor = cx.background_executor().clone();
 2171                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2172                let snapshot = self.buffer().read(cx).snapshot(cx);
 2173                let selections = selections.clone();
 2174                self.serialize_selections = cx.background_spawn(async move {
 2175                    background_executor.timer(Duration::from_millis(100)).await;
 2176                    let selections = selections
 2177                        .iter()
 2178                        .map(|selection| {
 2179                            (
 2180                                selection.start.to_offset(&snapshot),
 2181                                selection.end.to_offset(&snapshot),
 2182                            )
 2183                        })
 2184                        .collect();
 2185                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2186                        .await
 2187                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2188                        .log_err();
 2189                });
 2190            }
 2191        }
 2192
 2193        cx.notify();
 2194    }
 2195
 2196    pub fn change_selections<R>(
 2197        &mut self,
 2198        autoscroll: Option<Autoscroll>,
 2199        window: &mut Window,
 2200        cx: &mut Context<Self>,
 2201        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2202    ) -> R {
 2203        self.change_selections_inner(autoscroll, true, window, cx, change)
 2204    }
 2205
 2206    fn change_selections_inner<R>(
 2207        &mut self,
 2208        autoscroll: Option<Autoscroll>,
 2209        request_completions: bool,
 2210        window: &mut Window,
 2211        cx: &mut Context<Self>,
 2212        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2213    ) -> R {
 2214        let old_cursor_position = self.selections.newest_anchor().head();
 2215        self.push_to_selection_history();
 2216
 2217        let (changed, result) = self.selections.change_with(cx, change);
 2218
 2219        if changed {
 2220            if let Some(autoscroll) = autoscroll {
 2221                self.request_autoscroll(autoscroll, cx);
 2222            }
 2223            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2224
 2225            if self.should_open_signature_help_automatically(
 2226                &old_cursor_position,
 2227                self.signature_help_state.backspace_pressed(),
 2228                cx,
 2229            ) {
 2230                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2231            }
 2232            self.signature_help_state.set_backspace_pressed(false);
 2233        }
 2234
 2235        result
 2236    }
 2237
 2238    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2239    where
 2240        I: IntoIterator<Item = (Range<S>, T)>,
 2241        S: ToOffset,
 2242        T: Into<Arc<str>>,
 2243    {
 2244        if self.read_only(cx) {
 2245            return;
 2246        }
 2247
 2248        self.buffer
 2249            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2250    }
 2251
 2252    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2253    where
 2254        I: IntoIterator<Item = (Range<S>, T)>,
 2255        S: ToOffset,
 2256        T: Into<Arc<str>>,
 2257    {
 2258        if self.read_only(cx) {
 2259            return;
 2260        }
 2261
 2262        self.buffer.update(cx, |buffer, cx| {
 2263            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2264        });
 2265    }
 2266
 2267    pub fn edit_with_block_indent<I, S, T>(
 2268        &mut self,
 2269        edits: I,
 2270        original_start_columns: Vec<u32>,
 2271        cx: &mut Context<Self>,
 2272    ) where
 2273        I: IntoIterator<Item = (Range<S>, T)>,
 2274        S: ToOffset,
 2275        T: Into<Arc<str>>,
 2276    {
 2277        if self.read_only(cx) {
 2278            return;
 2279        }
 2280
 2281        self.buffer.update(cx, |buffer, cx| {
 2282            buffer.edit(
 2283                edits,
 2284                Some(AutoindentMode::Block {
 2285                    original_start_columns,
 2286                }),
 2287                cx,
 2288            )
 2289        });
 2290    }
 2291
 2292    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2293        self.hide_context_menu(window, cx);
 2294
 2295        match phase {
 2296            SelectPhase::Begin {
 2297                position,
 2298                add,
 2299                click_count,
 2300            } => self.begin_selection(position, add, click_count, window, cx),
 2301            SelectPhase::BeginColumnar {
 2302                position,
 2303                goal_column,
 2304                reset,
 2305            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2306            SelectPhase::Extend {
 2307                position,
 2308                click_count,
 2309            } => self.extend_selection(position, click_count, window, cx),
 2310            SelectPhase::Update {
 2311                position,
 2312                goal_column,
 2313                scroll_delta,
 2314            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2315            SelectPhase::End => self.end_selection(window, cx),
 2316        }
 2317    }
 2318
 2319    fn extend_selection(
 2320        &mut self,
 2321        position: DisplayPoint,
 2322        click_count: usize,
 2323        window: &mut Window,
 2324        cx: &mut Context<Self>,
 2325    ) {
 2326        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2327        let tail = self.selections.newest::<usize>(cx).tail();
 2328        self.begin_selection(position, false, click_count, window, cx);
 2329
 2330        let position = position.to_offset(&display_map, Bias::Left);
 2331        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2332
 2333        let mut pending_selection = self
 2334            .selections
 2335            .pending_anchor()
 2336            .expect("extend_selection not called with pending selection");
 2337        if position >= tail {
 2338            pending_selection.start = tail_anchor;
 2339        } else {
 2340            pending_selection.end = tail_anchor;
 2341            pending_selection.reversed = true;
 2342        }
 2343
 2344        let mut pending_mode = self.selections.pending_mode().unwrap();
 2345        match &mut pending_mode {
 2346            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2347            _ => {}
 2348        }
 2349
 2350        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2351            s.set_pending(pending_selection, pending_mode)
 2352        });
 2353    }
 2354
 2355    fn begin_selection(
 2356        &mut self,
 2357        position: DisplayPoint,
 2358        add: bool,
 2359        click_count: usize,
 2360        window: &mut Window,
 2361        cx: &mut Context<Self>,
 2362    ) {
 2363        if !self.focus_handle.is_focused(window) {
 2364            self.last_focused_descendant = None;
 2365            window.focus(&self.focus_handle);
 2366        }
 2367
 2368        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2369        let buffer = &display_map.buffer_snapshot;
 2370        let newest_selection = self.selections.newest_anchor().clone();
 2371        let position = display_map.clip_point(position, Bias::Left);
 2372
 2373        let start;
 2374        let end;
 2375        let mode;
 2376        let mut auto_scroll;
 2377        match click_count {
 2378            1 => {
 2379                start = buffer.anchor_before(position.to_point(&display_map));
 2380                end = start;
 2381                mode = SelectMode::Character;
 2382                auto_scroll = true;
 2383            }
 2384            2 => {
 2385                let range = movement::surrounding_word(&display_map, position);
 2386                start = buffer.anchor_before(range.start.to_point(&display_map));
 2387                end = buffer.anchor_before(range.end.to_point(&display_map));
 2388                mode = SelectMode::Word(start..end);
 2389                auto_scroll = true;
 2390            }
 2391            3 => {
 2392                let position = display_map
 2393                    .clip_point(position, Bias::Left)
 2394                    .to_point(&display_map);
 2395                let line_start = display_map.prev_line_boundary(position).0;
 2396                let next_line_start = buffer.clip_point(
 2397                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2398                    Bias::Left,
 2399                );
 2400                start = buffer.anchor_before(line_start);
 2401                end = buffer.anchor_before(next_line_start);
 2402                mode = SelectMode::Line(start..end);
 2403                auto_scroll = true;
 2404            }
 2405            _ => {
 2406                start = buffer.anchor_before(0);
 2407                end = buffer.anchor_before(buffer.len());
 2408                mode = SelectMode::All;
 2409                auto_scroll = false;
 2410            }
 2411        }
 2412        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2413
 2414        let point_to_delete: Option<usize> = {
 2415            let selected_points: Vec<Selection<Point>> =
 2416                self.selections.disjoint_in_range(start..end, cx);
 2417
 2418            if !add || click_count > 1 {
 2419                None
 2420            } else if !selected_points.is_empty() {
 2421                Some(selected_points[0].id)
 2422            } else {
 2423                let clicked_point_already_selected =
 2424                    self.selections.disjoint.iter().find(|selection| {
 2425                        selection.start.to_point(buffer) == start.to_point(buffer)
 2426                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2427                    });
 2428
 2429                clicked_point_already_selected.map(|selection| selection.id)
 2430            }
 2431        };
 2432
 2433        let selections_count = self.selections.count();
 2434
 2435        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2436            if let Some(point_to_delete) = point_to_delete {
 2437                s.delete(point_to_delete);
 2438
 2439                if selections_count == 1 {
 2440                    s.set_pending_anchor_range(start..end, mode);
 2441                }
 2442            } else {
 2443                if !add {
 2444                    s.clear_disjoint();
 2445                } else if click_count > 1 {
 2446                    s.delete(newest_selection.id)
 2447                }
 2448
 2449                s.set_pending_anchor_range(start..end, mode);
 2450            }
 2451        });
 2452    }
 2453
 2454    fn begin_columnar_selection(
 2455        &mut self,
 2456        position: DisplayPoint,
 2457        goal_column: u32,
 2458        reset: bool,
 2459        window: &mut Window,
 2460        cx: &mut Context<Self>,
 2461    ) {
 2462        if !self.focus_handle.is_focused(window) {
 2463            self.last_focused_descendant = None;
 2464            window.focus(&self.focus_handle);
 2465        }
 2466
 2467        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2468
 2469        if reset {
 2470            let pointer_position = display_map
 2471                .buffer_snapshot
 2472                .anchor_before(position.to_point(&display_map));
 2473
 2474            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2475                s.clear_disjoint();
 2476                s.set_pending_anchor_range(
 2477                    pointer_position..pointer_position,
 2478                    SelectMode::Character,
 2479                );
 2480            });
 2481        }
 2482
 2483        let tail = self.selections.newest::<Point>(cx).tail();
 2484        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2485
 2486        if !reset {
 2487            self.select_columns(
 2488                tail.to_display_point(&display_map),
 2489                position,
 2490                goal_column,
 2491                &display_map,
 2492                window,
 2493                cx,
 2494            );
 2495        }
 2496    }
 2497
 2498    fn update_selection(
 2499        &mut self,
 2500        position: DisplayPoint,
 2501        goal_column: u32,
 2502        scroll_delta: gpui::Point<f32>,
 2503        window: &mut Window,
 2504        cx: &mut Context<Self>,
 2505    ) {
 2506        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2507
 2508        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2509            let tail = tail.to_display_point(&display_map);
 2510            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2511        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2512            let buffer = self.buffer.read(cx).snapshot(cx);
 2513            let head;
 2514            let tail;
 2515            let mode = self.selections.pending_mode().unwrap();
 2516            match &mode {
 2517                SelectMode::Character => {
 2518                    head = position.to_point(&display_map);
 2519                    tail = pending.tail().to_point(&buffer);
 2520                }
 2521                SelectMode::Word(original_range) => {
 2522                    let original_display_range = original_range.start.to_display_point(&display_map)
 2523                        ..original_range.end.to_display_point(&display_map);
 2524                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2525                        ..original_display_range.end.to_point(&display_map);
 2526                    if movement::is_inside_word(&display_map, position)
 2527                        || original_display_range.contains(&position)
 2528                    {
 2529                        let word_range = movement::surrounding_word(&display_map, position);
 2530                        if word_range.start < original_display_range.start {
 2531                            head = word_range.start.to_point(&display_map);
 2532                        } else {
 2533                            head = word_range.end.to_point(&display_map);
 2534                        }
 2535                    } else {
 2536                        head = position.to_point(&display_map);
 2537                    }
 2538
 2539                    if head <= original_buffer_range.start {
 2540                        tail = original_buffer_range.end;
 2541                    } else {
 2542                        tail = original_buffer_range.start;
 2543                    }
 2544                }
 2545                SelectMode::Line(original_range) => {
 2546                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2547
 2548                    let position = display_map
 2549                        .clip_point(position, Bias::Left)
 2550                        .to_point(&display_map);
 2551                    let line_start = display_map.prev_line_boundary(position).0;
 2552                    let next_line_start = buffer.clip_point(
 2553                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2554                        Bias::Left,
 2555                    );
 2556
 2557                    if line_start < original_range.start {
 2558                        head = line_start
 2559                    } else {
 2560                        head = next_line_start
 2561                    }
 2562
 2563                    if head <= original_range.start {
 2564                        tail = original_range.end;
 2565                    } else {
 2566                        tail = original_range.start;
 2567                    }
 2568                }
 2569                SelectMode::All => {
 2570                    return;
 2571                }
 2572            };
 2573
 2574            if head < tail {
 2575                pending.start = buffer.anchor_before(head);
 2576                pending.end = buffer.anchor_before(tail);
 2577                pending.reversed = true;
 2578            } else {
 2579                pending.start = buffer.anchor_before(tail);
 2580                pending.end = buffer.anchor_before(head);
 2581                pending.reversed = false;
 2582            }
 2583
 2584            self.change_selections(None, window, cx, |s| {
 2585                s.set_pending(pending, mode);
 2586            });
 2587        } else {
 2588            log::error!("update_selection dispatched with no pending selection");
 2589            return;
 2590        }
 2591
 2592        self.apply_scroll_delta(scroll_delta, window, cx);
 2593        cx.notify();
 2594    }
 2595
 2596    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2597        self.columnar_selection_tail.take();
 2598        if self.selections.pending_anchor().is_some() {
 2599            let selections = self.selections.all::<usize>(cx);
 2600            self.change_selections(None, window, cx, |s| {
 2601                s.select(selections);
 2602                s.clear_pending();
 2603            });
 2604        }
 2605    }
 2606
 2607    fn select_columns(
 2608        &mut self,
 2609        tail: DisplayPoint,
 2610        head: DisplayPoint,
 2611        goal_column: u32,
 2612        display_map: &DisplaySnapshot,
 2613        window: &mut Window,
 2614        cx: &mut Context<Self>,
 2615    ) {
 2616        let start_row = cmp::min(tail.row(), head.row());
 2617        let end_row = cmp::max(tail.row(), head.row());
 2618        let start_column = cmp::min(tail.column(), goal_column);
 2619        let end_column = cmp::max(tail.column(), goal_column);
 2620        let reversed = start_column < tail.column();
 2621
 2622        let selection_ranges = (start_row.0..=end_row.0)
 2623            .map(DisplayRow)
 2624            .filter_map(|row| {
 2625                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2626                    let start = display_map
 2627                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2628                        .to_point(display_map);
 2629                    let end = display_map
 2630                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2631                        .to_point(display_map);
 2632                    if reversed {
 2633                        Some(end..start)
 2634                    } else {
 2635                        Some(start..end)
 2636                    }
 2637                } else {
 2638                    None
 2639                }
 2640            })
 2641            .collect::<Vec<_>>();
 2642
 2643        self.change_selections(None, window, cx, |s| {
 2644            s.select_ranges(selection_ranges);
 2645        });
 2646        cx.notify();
 2647    }
 2648
 2649    pub fn has_pending_nonempty_selection(&self) -> bool {
 2650        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2651            Some(Selection { start, end, .. }) => start != end,
 2652            None => false,
 2653        };
 2654
 2655        pending_nonempty_selection
 2656            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2657    }
 2658
 2659    pub fn has_pending_selection(&self) -> bool {
 2660        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2661    }
 2662
 2663    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2664        self.selection_mark_mode = false;
 2665
 2666        if self.clear_expanded_diff_hunks(cx) {
 2667            cx.notify();
 2668            return;
 2669        }
 2670        if self.dismiss_menus_and_popups(true, window, cx) {
 2671            return;
 2672        }
 2673
 2674        if self.mode == EditorMode::Full
 2675            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2676        {
 2677            return;
 2678        }
 2679
 2680        cx.propagate();
 2681    }
 2682
 2683    pub fn dismiss_menus_and_popups(
 2684        &mut self,
 2685        is_user_requested: bool,
 2686        window: &mut Window,
 2687        cx: &mut Context<Self>,
 2688    ) -> bool {
 2689        if self.take_rename(false, window, cx).is_some() {
 2690            return true;
 2691        }
 2692
 2693        if hide_hover(self, cx) {
 2694            return true;
 2695        }
 2696
 2697        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2698            return true;
 2699        }
 2700
 2701        if self.hide_context_menu(window, cx).is_some() {
 2702            return true;
 2703        }
 2704
 2705        if self.mouse_context_menu.take().is_some() {
 2706            return true;
 2707        }
 2708
 2709        if is_user_requested && self.discard_inline_completion(true, cx) {
 2710            return true;
 2711        }
 2712
 2713        if self.snippet_stack.pop().is_some() {
 2714            return true;
 2715        }
 2716
 2717        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2718            self.dismiss_diagnostics(cx);
 2719            return true;
 2720        }
 2721
 2722        false
 2723    }
 2724
 2725    fn linked_editing_ranges_for(
 2726        &self,
 2727        selection: Range<text::Anchor>,
 2728        cx: &App,
 2729    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2730        if self.linked_edit_ranges.is_empty() {
 2731            return None;
 2732        }
 2733        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2734            selection.end.buffer_id.and_then(|end_buffer_id| {
 2735                if selection.start.buffer_id != Some(end_buffer_id) {
 2736                    return None;
 2737                }
 2738                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2739                let snapshot = buffer.read(cx).snapshot();
 2740                self.linked_edit_ranges
 2741                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2742                    .map(|ranges| (ranges, snapshot, buffer))
 2743            })?;
 2744        use text::ToOffset as TO;
 2745        // find offset from the start of current range to current cursor position
 2746        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2747
 2748        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2749        let start_difference = start_offset - start_byte_offset;
 2750        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2751        let end_difference = end_offset - start_byte_offset;
 2752        // Current range has associated linked ranges.
 2753        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2754        for range in linked_ranges.iter() {
 2755            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2756            let end_offset = start_offset + end_difference;
 2757            let start_offset = start_offset + start_difference;
 2758            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2759                continue;
 2760            }
 2761            if self.selections.disjoint_anchor_ranges().any(|s| {
 2762                if s.start.buffer_id != selection.start.buffer_id
 2763                    || s.end.buffer_id != selection.end.buffer_id
 2764                {
 2765                    return false;
 2766                }
 2767                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2768                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2769            }) {
 2770                continue;
 2771            }
 2772            let start = buffer_snapshot.anchor_after(start_offset);
 2773            let end = buffer_snapshot.anchor_after(end_offset);
 2774            linked_edits
 2775                .entry(buffer.clone())
 2776                .or_default()
 2777                .push(start..end);
 2778        }
 2779        Some(linked_edits)
 2780    }
 2781
 2782    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2783        let text: Arc<str> = text.into();
 2784
 2785        if self.read_only(cx) {
 2786            return;
 2787        }
 2788
 2789        let selections = self.selections.all_adjusted(cx);
 2790        let mut bracket_inserted = false;
 2791        let mut edits = Vec::new();
 2792        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2793        let mut new_selections = Vec::with_capacity(selections.len());
 2794        let mut new_autoclose_regions = Vec::new();
 2795        let snapshot = self.buffer.read(cx).read(cx);
 2796
 2797        for (selection, autoclose_region) in
 2798            self.selections_with_autoclose_regions(selections, &snapshot)
 2799        {
 2800            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2801                // Determine if the inserted text matches the opening or closing
 2802                // bracket of any of this language's bracket pairs.
 2803                let mut bracket_pair = None;
 2804                let mut is_bracket_pair_start = false;
 2805                let mut is_bracket_pair_end = false;
 2806                if !text.is_empty() {
 2807                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2808                    //  and they are removing the character that triggered IME popup.
 2809                    for (pair, enabled) in scope.brackets() {
 2810                        if !pair.close && !pair.surround {
 2811                            continue;
 2812                        }
 2813
 2814                        if enabled && pair.start.ends_with(text.as_ref()) {
 2815                            let prefix_len = pair.start.len() - text.len();
 2816                            let preceding_text_matches_prefix = prefix_len == 0
 2817                                || (selection.start.column >= (prefix_len as u32)
 2818                                    && snapshot.contains_str_at(
 2819                                        Point::new(
 2820                                            selection.start.row,
 2821                                            selection.start.column - (prefix_len as u32),
 2822                                        ),
 2823                                        &pair.start[..prefix_len],
 2824                                    ));
 2825                            if preceding_text_matches_prefix {
 2826                                bracket_pair = Some(pair.clone());
 2827                                is_bracket_pair_start = true;
 2828                                break;
 2829                            }
 2830                        }
 2831                        if pair.end.as_str() == text.as_ref() {
 2832                            bracket_pair = Some(pair.clone());
 2833                            is_bracket_pair_end = true;
 2834                            break;
 2835                        }
 2836                    }
 2837                }
 2838
 2839                if let Some(bracket_pair) = bracket_pair {
 2840                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2841                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2842                    let auto_surround =
 2843                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2844                    if selection.is_empty() {
 2845                        if is_bracket_pair_start {
 2846                            // If the inserted text is a suffix of an opening bracket and the
 2847                            // selection is preceded by the rest of the opening bracket, then
 2848                            // insert the closing bracket.
 2849                            let following_text_allows_autoclose = snapshot
 2850                                .chars_at(selection.start)
 2851                                .next()
 2852                                .map_or(true, |c| scope.should_autoclose_before(c));
 2853
 2854                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2855                                && bracket_pair.start.len() == 1
 2856                            {
 2857                                let target = bracket_pair.start.chars().next().unwrap();
 2858                                let current_line_count = snapshot
 2859                                    .reversed_chars_at(selection.start)
 2860                                    .take_while(|&c| c != '\n')
 2861                                    .filter(|&c| c == target)
 2862                                    .count();
 2863                                current_line_count % 2 == 1
 2864                            } else {
 2865                                false
 2866                            };
 2867
 2868                            if autoclose
 2869                                && bracket_pair.close
 2870                                && following_text_allows_autoclose
 2871                                && !is_closing_quote
 2872                            {
 2873                                let anchor = snapshot.anchor_before(selection.end);
 2874                                new_selections.push((selection.map(|_| anchor), text.len()));
 2875                                new_autoclose_regions.push((
 2876                                    anchor,
 2877                                    text.len(),
 2878                                    selection.id,
 2879                                    bracket_pair.clone(),
 2880                                ));
 2881                                edits.push((
 2882                                    selection.range(),
 2883                                    format!("{}{}", text, bracket_pair.end).into(),
 2884                                ));
 2885                                bracket_inserted = true;
 2886                                continue;
 2887                            }
 2888                        }
 2889
 2890                        if let Some(region) = autoclose_region {
 2891                            // If the selection is followed by an auto-inserted closing bracket,
 2892                            // then don't insert that closing bracket again; just move the selection
 2893                            // past the closing bracket.
 2894                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2895                                && text.as_ref() == region.pair.end.as_str();
 2896                            if should_skip {
 2897                                let anchor = snapshot.anchor_after(selection.end);
 2898                                new_selections
 2899                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2900                                continue;
 2901                            }
 2902                        }
 2903
 2904                        let always_treat_brackets_as_autoclosed = snapshot
 2905                            .settings_at(selection.start, cx)
 2906                            .always_treat_brackets_as_autoclosed;
 2907                        if always_treat_brackets_as_autoclosed
 2908                            && is_bracket_pair_end
 2909                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2910                        {
 2911                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2912                            // and the inserted text is a closing bracket and the selection is followed
 2913                            // by the closing bracket then move the selection past the closing bracket.
 2914                            let anchor = snapshot.anchor_after(selection.end);
 2915                            new_selections.push((selection.map(|_| anchor), text.len()));
 2916                            continue;
 2917                        }
 2918                    }
 2919                    // If an opening bracket is 1 character long and is typed while
 2920                    // text is selected, then surround that text with the bracket pair.
 2921                    else if auto_surround
 2922                        && bracket_pair.surround
 2923                        && is_bracket_pair_start
 2924                        && bracket_pair.start.chars().count() == 1
 2925                    {
 2926                        edits.push((selection.start..selection.start, text.clone()));
 2927                        edits.push((
 2928                            selection.end..selection.end,
 2929                            bracket_pair.end.as_str().into(),
 2930                        ));
 2931                        bracket_inserted = true;
 2932                        new_selections.push((
 2933                            Selection {
 2934                                id: selection.id,
 2935                                start: snapshot.anchor_after(selection.start),
 2936                                end: snapshot.anchor_before(selection.end),
 2937                                reversed: selection.reversed,
 2938                                goal: selection.goal,
 2939                            },
 2940                            0,
 2941                        ));
 2942                        continue;
 2943                    }
 2944                }
 2945            }
 2946
 2947            if self.auto_replace_emoji_shortcode
 2948                && selection.is_empty()
 2949                && text.as_ref().ends_with(':')
 2950            {
 2951                if let Some(possible_emoji_short_code) =
 2952                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2953                {
 2954                    if !possible_emoji_short_code.is_empty() {
 2955                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2956                            let emoji_shortcode_start = Point::new(
 2957                                selection.start.row,
 2958                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2959                            );
 2960
 2961                            // Remove shortcode from buffer
 2962                            edits.push((
 2963                                emoji_shortcode_start..selection.start,
 2964                                "".to_string().into(),
 2965                            ));
 2966                            new_selections.push((
 2967                                Selection {
 2968                                    id: selection.id,
 2969                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2970                                    end: snapshot.anchor_before(selection.start),
 2971                                    reversed: selection.reversed,
 2972                                    goal: selection.goal,
 2973                                },
 2974                                0,
 2975                            ));
 2976
 2977                            // Insert emoji
 2978                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2979                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2980                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2981
 2982                            continue;
 2983                        }
 2984                    }
 2985                }
 2986            }
 2987
 2988            // If not handling any auto-close operation, then just replace the selected
 2989            // text with the given input and move the selection to the end of the
 2990            // newly inserted text.
 2991            let anchor = snapshot.anchor_after(selection.end);
 2992            if !self.linked_edit_ranges.is_empty() {
 2993                let start_anchor = snapshot.anchor_before(selection.start);
 2994
 2995                let is_word_char = text.chars().next().map_or(true, |char| {
 2996                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2997                    classifier.is_word(char)
 2998                });
 2999
 3000                if is_word_char {
 3001                    if let Some(ranges) = self
 3002                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3003                    {
 3004                        for (buffer, edits) in ranges {
 3005                            linked_edits
 3006                                .entry(buffer.clone())
 3007                                .or_default()
 3008                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3009                        }
 3010                    }
 3011                }
 3012            }
 3013
 3014            new_selections.push((selection.map(|_| anchor), 0));
 3015            edits.push((selection.start..selection.end, text.clone()));
 3016        }
 3017
 3018        drop(snapshot);
 3019
 3020        self.transact(window, cx, |this, window, cx| {
 3021            this.buffer.update(cx, |buffer, cx| {
 3022                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3023            });
 3024            for (buffer, edits) in linked_edits {
 3025                buffer.update(cx, |buffer, cx| {
 3026                    let snapshot = buffer.snapshot();
 3027                    let edits = edits
 3028                        .into_iter()
 3029                        .map(|(range, text)| {
 3030                            use text::ToPoint as TP;
 3031                            let end_point = TP::to_point(&range.end, &snapshot);
 3032                            let start_point = TP::to_point(&range.start, &snapshot);
 3033                            (start_point..end_point, text)
 3034                        })
 3035                        .sorted_by_key(|(range, _)| range.start)
 3036                        .collect::<Vec<_>>();
 3037                    buffer.edit(edits, None, cx);
 3038                })
 3039            }
 3040            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3041            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3042            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3043            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3044                .zip(new_selection_deltas)
 3045                .map(|(selection, delta)| Selection {
 3046                    id: selection.id,
 3047                    start: selection.start + delta,
 3048                    end: selection.end + delta,
 3049                    reversed: selection.reversed,
 3050                    goal: SelectionGoal::None,
 3051                })
 3052                .collect::<Vec<_>>();
 3053
 3054            let mut i = 0;
 3055            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3056                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3057                let start = map.buffer_snapshot.anchor_before(position);
 3058                let end = map.buffer_snapshot.anchor_after(position);
 3059                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3060                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3061                        Ordering::Less => i += 1,
 3062                        Ordering::Greater => break,
 3063                        Ordering::Equal => {
 3064                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3065                                Ordering::Less => i += 1,
 3066                                Ordering::Equal => break,
 3067                                Ordering::Greater => break,
 3068                            }
 3069                        }
 3070                    }
 3071                }
 3072                this.autoclose_regions.insert(
 3073                    i,
 3074                    AutocloseRegion {
 3075                        selection_id,
 3076                        range: start..end,
 3077                        pair,
 3078                    },
 3079                );
 3080            }
 3081
 3082            let had_active_inline_completion = this.has_active_inline_completion();
 3083            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3084                s.select(new_selections)
 3085            });
 3086
 3087            if !bracket_inserted {
 3088                if let Some(on_type_format_task) =
 3089                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3090                {
 3091                    on_type_format_task.detach_and_log_err(cx);
 3092                }
 3093            }
 3094
 3095            let editor_settings = EditorSettings::get_global(cx);
 3096            if bracket_inserted
 3097                && (editor_settings.auto_signature_help
 3098                    || editor_settings.show_signature_help_after_edits)
 3099            {
 3100                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3101            }
 3102
 3103            let trigger_in_words =
 3104                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3105            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3106            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3107            this.refresh_inline_completion(true, false, window, cx);
 3108        });
 3109    }
 3110
 3111    fn find_possible_emoji_shortcode_at_position(
 3112        snapshot: &MultiBufferSnapshot,
 3113        position: Point,
 3114    ) -> Option<String> {
 3115        let mut chars = Vec::new();
 3116        let mut found_colon = false;
 3117        for char in snapshot.reversed_chars_at(position).take(100) {
 3118            // Found a possible emoji shortcode in the middle of the buffer
 3119            if found_colon {
 3120                if char.is_whitespace() {
 3121                    chars.reverse();
 3122                    return Some(chars.iter().collect());
 3123                }
 3124                // If the previous character is not a whitespace, we are in the middle of a word
 3125                // and we only want to complete the shortcode if the word is made up of other emojis
 3126                let mut containing_word = String::new();
 3127                for ch in snapshot
 3128                    .reversed_chars_at(position)
 3129                    .skip(chars.len() + 1)
 3130                    .take(100)
 3131                {
 3132                    if ch.is_whitespace() {
 3133                        break;
 3134                    }
 3135                    containing_word.push(ch);
 3136                }
 3137                let containing_word = containing_word.chars().rev().collect::<String>();
 3138                if util::word_consists_of_emojis(containing_word.as_str()) {
 3139                    chars.reverse();
 3140                    return Some(chars.iter().collect());
 3141                }
 3142            }
 3143
 3144            if char.is_whitespace() || !char.is_ascii() {
 3145                return None;
 3146            }
 3147            if char == ':' {
 3148                found_colon = true;
 3149            } else {
 3150                chars.push(char);
 3151            }
 3152        }
 3153        // Found a possible emoji shortcode at the beginning of the buffer
 3154        chars.reverse();
 3155        Some(chars.iter().collect())
 3156    }
 3157
 3158    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3159        self.transact(window, cx, |this, window, cx| {
 3160            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3161                let selections = this.selections.all::<usize>(cx);
 3162                let multi_buffer = this.buffer.read(cx);
 3163                let buffer = multi_buffer.snapshot(cx);
 3164                selections
 3165                    .iter()
 3166                    .map(|selection| {
 3167                        let start_point = selection.start.to_point(&buffer);
 3168                        let mut indent =
 3169                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3170                        indent.len = cmp::min(indent.len, start_point.column);
 3171                        let start = selection.start;
 3172                        let end = selection.end;
 3173                        let selection_is_empty = start == end;
 3174                        let language_scope = buffer.language_scope_at(start);
 3175                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3176                            &language_scope
 3177                        {
 3178                            let insert_extra_newline =
 3179                                insert_extra_newline_brackets(&buffer, start..end, language)
 3180                                    || insert_extra_newline_tree_sitter(&buffer, start..end);
 3181
 3182                            // Comment extension on newline is allowed only for cursor selections
 3183                            let comment_delimiter = maybe!({
 3184                                if !selection_is_empty {
 3185                                    return None;
 3186                                }
 3187
 3188                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3189                                    return None;
 3190                                }
 3191
 3192                                let delimiters = language.line_comment_prefixes();
 3193                                let max_len_of_delimiter =
 3194                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3195                                let (snapshot, range) =
 3196                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3197
 3198                                let mut index_of_first_non_whitespace = 0;
 3199                                let comment_candidate = snapshot
 3200                                    .chars_for_range(range)
 3201                                    .skip_while(|c| {
 3202                                        let should_skip = c.is_whitespace();
 3203                                        if should_skip {
 3204                                            index_of_first_non_whitespace += 1;
 3205                                        }
 3206                                        should_skip
 3207                                    })
 3208                                    .take(max_len_of_delimiter)
 3209                                    .collect::<String>();
 3210                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3211                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3212                                })?;
 3213                                let cursor_is_placed_after_comment_marker =
 3214                                    index_of_first_non_whitespace + comment_prefix.len()
 3215                                        <= start_point.column as usize;
 3216                                if cursor_is_placed_after_comment_marker {
 3217                                    Some(comment_prefix.clone())
 3218                                } else {
 3219                                    None
 3220                                }
 3221                            });
 3222                            (comment_delimiter, insert_extra_newline)
 3223                        } else {
 3224                            (None, false)
 3225                        };
 3226
 3227                        let capacity_for_delimiter = comment_delimiter
 3228                            .as_deref()
 3229                            .map(str::len)
 3230                            .unwrap_or_default();
 3231                        let mut new_text =
 3232                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3233                        new_text.push('\n');
 3234                        new_text.extend(indent.chars());
 3235                        if let Some(delimiter) = &comment_delimiter {
 3236                            new_text.push_str(delimiter);
 3237                        }
 3238                        if insert_extra_newline {
 3239                            new_text = new_text.repeat(2);
 3240                        }
 3241
 3242                        let anchor = buffer.anchor_after(end);
 3243                        let new_selection = selection.map(|_| anchor);
 3244                        (
 3245                            (start..end, new_text),
 3246                            (insert_extra_newline, new_selection),
 3247                        )
 3248                    })
 3249                    .unzip()
 3250            };
 3251
 3252            this.edit_with_autoindent(edits, cx);
 3253            let buffer = this.buffer.read(cx).snapshot(cx);
 3254            let new_selections = selection_fixup_info
 3255                .into_iter()
 3256                .map(|(extra_newline_inserted, new_selection)| {
 3257                    let mut cursor = new_selection.end.to_point(&buffer);
 3258                    if extra_newline_inserted {
 3259                        cursor.row -= 1;
 3260                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3261                    }
 3262                    new_selection.map(|_| cursor)
 3263                })
 3264                .collect();
 3265
 3266            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3267                s.select(new_selections)
 3268            });
 3269            this.refresh_inline_completion(true, false, window, cx);
 3270        });
 3271    }
 3272
 3273    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3274        let buffer = self.buffer.read(cx);
 3275        let snapshot = buffer.snapshot(cx);
 3276
 3277        let mut edits = Vec::new();
 3278        let mut rows = Vec::new();
 3279
 3280        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3281            let cursor = selection.head();
 3282            let row = cursor.row;
 3283
 3284            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3285
 3286            let newline = "\n".to_string();
 3287            edits.push((start_of_line..start_of_line, newline));
 3288
 3289            rows.push(row + rows_inserted as u32);
 3290        }
 3291
 3292        self.transact(window, cx, |editor, window, cx| {
 3293            editor.edit(edits, cx);
 3294
 3295            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3296                let mut index = 0;
 3297                s.move_cursors_with(|map, _, _| {
 3298                    let row = rows[index];
 3299                    index += 1;
 3300
 3301                    let point = Point::new(row, 0);
 3302                    let boundary = map.next_line_boundary(point).1;
 3303                    let clipped = map.clip_point(boundary, Bias::Left);
 3304
 3305                    (clipped, SelectionGoal::None)
 3306                });
 3307            });
 3308
 3309            let mut indent_edits = Vec::new();
 3310            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3311            for row in rows {
 3312                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3313                for (row, indent) in indents {
 3314                    if indent.len == 0 {
 3315                        continue;
 3316                    }
 3317
 3318                    let text = match indent.kind {
 3319                        IndentKind::Space => " ".repeat(indent.len as usize),
 3320                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3321                    };
 3322                    let point = Point::new(row.0, 0);
 3323                    indent_edits.push((point..point, text));
 3324                }
 3325            }
 3326            editor.edit(indent_edits, cx);
 3327        });
 3328    }
 3329
 3330    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3331        let buffer = self.buffer.read(cx);
 3332        let snapshot = buffer.snapshot(cx);
 3333
 3334        let mut edits = Vec::new();
 3335        let mut rows = Vec::new();
 3336        let mut rows_inserted = 0;
 3337
 3338        for selection in self.selections.all_adjusted(cx) {
 3339            let cursor = selection.head();
 3340            let row = cursor.row;
 3341
 3342            let point = Point::new(row + 1, 0);
 3343            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3344
 3345            let newline = "\n".to_string();
 3346            edits.push((start_of_line..start_of_line, newline));
 3347
 3348            rows_inserted += 1;
 3349            rows.push(row + rows_inserted);
 3350        }
 3351
 3352        self.transact(window, cx, |editor, window, cx| {
 3353            editor.edit(edits, cx);
 3354
 3355            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3356                let mut index = 0;
 3357                s.move_cursors_with(|map, _, _| {
 3358                    let row = rows[index];
 3359                    index += 1;
 3360
 3361                    let point = Point::new(row, 0);
 3362                    let boundary = map.next_line_boundary(point).1;
 3363                    let clipped = map.clip_point(boundary, Bias::Left);
 3364
 3365                    (clipped, SelectionGoal::None)
 3366                });
 3367            });
 3368
 3369            let mut indent_edits = Vec::new();
 3370            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3371            for row in rows {
 3372                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3373                for (row, indent) in indents {
 3374                    if indent.len == 0 {
 3375                        continue;
 3376                    }
 3377
 3378                    let text = match indent.kind {
 3379                        IndentKind::Space => " ".repeat(indent.len as usize),
 3380                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3381                    };
 3382                    let point = Point::new(row.0, 0);
 3383                    indent_edits.push((point..point, text));
 3384                }
 3385            }
 3386            editor.edit(indent_edits, cx);
 3387        });
 3388    }
 3389
 3390    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3391        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3392            original_start_columns: Vec::new(),
 3393        });
 3394        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3395    }
 3396
 3397    fn insert_with_autoindent_mode(
 3398        &mut self,
 3399        text: &str,
 3400        autoindent_mode: Option<AutoindentMode>,
 3401        window: &mut Window,
 3402        cx: &mut Context<Self>,
 3403    ) {
 3404        if self.read_only(cx) {
 3405            return;
 3406        }
 3407
 3408        let text: Arc<str> = text.into();
 3409        self.transact(window, cx, |this, window, cx| {
 3410            let old_selections = this.selections.all_adjusted(cx);
 3411            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3412                let anchors = {
 3413                    let snapshot = buffer.read(cx);
 3414                    old_selections
 3415                        .iter()
 3416                        .map(|s| {
 3417                            let anchor = snapshot.anchor_after(s.head());
 3418                            s.map(|_| anchor)
 3419                        })
 3420                        .collect::<Vec<_>>()
 3421                };
 3422                buffer.edit(
 3423                    old_selections
 3424                        .iter()
 3425                        .map(|s| (s.start..s.end, text.clone())),
 3426                    autoindent_mode,
 3427                    cx,
 3428                );
 3429                anchors
 3430            });
 3431
 3432            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3433                s.select_anchors(selection_anchors);
 3434            });
 3435
 3436            cx.notify();
 3437        });
 3438    }
 3439
 3440    fn trigger_completion_on_input(
 3441        &mut self,
 3442        text: &str,
 3443        trigger_in_words: bool,
 3444        window: &mut Window,
 3445        cx: &mut Context<Self>,
 3446    ) {
 3447        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3448            self.show_completions(
 3449                &ShowCompletions {
 3450                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3451                },
 3452                window,
 3453                cx,
 3454            );
 3455        } else {
 3456            self.hide_context_menu(window, cx);
 3457        }
 3458    }
 3459
 3460    fn is_completion_trigger(
 3461        &self,
 3462        text: &str,
 3463        trigger_in_words: bool,
 3464        cx: &mut Context<Self>,
 3465    ) -> bool {
 3466        let position = self.selections.newest_anchor().head();
 3467        let multibuffer = self.buffer.read(cx);
 3468        let Some(buffer) = position
 3469            .buffer_id
 3470            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3471        else {
 3472            return false;
 3473        };
 3474
 3475        if let Some(completion_provider) = &self.completion_provider {
 3476            completion_provider.is_completion_trigger(
 3477                &buffer,
 3478                position.text_anchor,
 3479                text,
 3480                trigger_in_words,
 3481                cx,
 3482            )
 3483        } else {
 3484            false
 3485        }
 3486    }
 3487
 3488    /// If any empty selections is touching the start of its innermost containing autoclose
 3489    /// region, expand it to select the brackets.
 3490    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3491        let selections = self.selections.all::<usize>(cx);
 3492        let buffer = self.buffer.read(cx).read(cx);
 3493        let new_selections = self
 3494            .selections_with_autoclose_regions(selections, &buffer)
 3495            .map(|(mut selection, region)| {
 3496                if !selection.is_empty() {
 3497                    return selection;
 3498                }
 3499
 3500                if let Some(region) = region {
 3501                    let mut range = region.range.to_offset(&buffer);
 3502                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3503                        range.start -= region.pair.start.len();
 3504                        if buffer.contains_str_at(range.start, &region.pair.start)
 3505                            && buffer.contains_str_at(range.end, &region.pair.end)
 3506                        {
 3507                            range.end += region.pair.end.len();
 3508                            selection.start = range.start;
 3509                            selection.end = range.end;
 3510
 3511                            return selection;
 3512                        }
 3513                    }
 3514                }
 3515
 3516                let always_treat_brackets_as_autoclosed = buffer
 3517                    .settings_at(selection.start, cx)
 3518                    .always_treat_brackets_as_autoclosed;
 3519
 3520                if !always_treat_brackets_as_autoclosed {
 3521                    return selection;
 3522                }
 3523
 3524                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3525                    for (pair, enabled) in scope.brackets() {
 3526                        if !enabled || !pair.close {
 3527                            continue;
 3528                        }
 3529
 3530                        if buffer.contains_str_at(selection.start, &pair.end) {
 3531                            let pair_start_len = pair.start.len();
 3532                            if buffer.contains_str_at(
 3533                                selection.start.saturating_sub(pair_start_len),
 3534                                &pair.start,
 3535                            ) {
 3536                                selection.start -= pair_start_len;
 3537                                selection.end += pair.end.len();
 3538
 3539                                return selection;
 3540                            }
 3541                        }
 3542                    }
 3543                }
 3544
 3545                selection
 3546            })
 3547            .collect();
 3548
 3549        drop(buffer);
 3550        self.change_selections(None, window, cx, |selections| {
 3551            selections.select(new_selections)
 3552        });
 3553    }
 3554
 3555    /// Iterate the given selections, and for each one, find the smallest surrounding
 3556    /// autoclose region. This uses the ordering of the selections and the autoclose
 3557    /// regions to avoid repeated comparisons.
 3558    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3559        &'a self,
 3560        selections: impl IntoIterator<Item = Selection<D>>,
 3561        buffer: &'a MultiBufferSnapshot,
 3562    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3563        let mut i = 0;
 3564        let mut regions = self.autoclose_regions.as_slice();
 3565        selections.into_iter().map(move |selection| {
 3566            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3567
 3568            let mut enclosing = None;
 3569            while let Some(pair_state) = regions.get(i) {
 3570                if pair_state.range.end.to_offset(buffer) < range.start {
 3571                    regions = &regions[i + 1..];
 3572                    i = 0;
 3573                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3574                    break;
 3575                } else {
 3576                    if pair_state.selection_id == selection.id {
 3577                        enclosing = Some(pair_state);
 3578                    }
 3579                    i += 1;
 3580                }
 3581            }
 3582
 3583            (selection, enclosing)
 3584        })
 3585    }
 3586
 3587    /// Remove any autoclose regions that no longer contain their selection.
 3588    fn invalidate_autoclose_regions(
 3589        &mut self,
 3590        mut selections: &[Selection<Anchor>],
 3591        buffer: &MultiBufferSnapshot,
 3592    ) {
 3593        self.autoclose_regions.retain(|state| {
 3594            let mut i = 0;
 3595            while let Some(selection) = selections.get(i) {
 3596                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3597                    selections = &selections[1..];
 3598                    continue;
 3599                }
 3600                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3601                    break;
 3602                }
 3603                if selection.id == state.selection_id {
 3604                    return true;
 3605                } else {
 3606                    i += 1;
 3607                }
 3608            }
 3609            false
 3610        });
 3611    }
 3612
 3613    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3614        let offset = position.to_offset(buffer);
 3615        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3616        if offset > word_range.start && kind == Some(CharKind::Word) {
 3617            Some(
 3618                buffer
 3619                    .text_for_range(word_range.start..offset)
 3620                    .collect::<String>(),
 3621            )
 3622        } else {
 3623            None
 3624        }
 3625    }
 3626
 3627    pub fn toggle_inlay_hints(
 3628        &mut self,
 3629        _: &ToggleInlayHints,
 3630        _: &mut Window,
 3631        cx: &mut Context<Self>,
 3632    ) {
 3633        self.refresh_inlay_hints(
 3634            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3635            cx,
 3636        );
 3637    }
 3638
 3639    pub fn inlay_hints_enabled(&self) -> bool {
 3640        self.inlay_hint_cache.enabled
 3641    }
 3642
 3643    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3644        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3645            return;
 3646        }
 3647
 3648        let reason_description = reason.description();
 3649        let ignore_debounce = matches!(
 3650            reason,
 3651            InlayHintRefreshReason::SettingsChange(_)
 3652                | InlayHintRefreshReason::Toggle(_)
 3653                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3654        );
 3655        let (invalidate_cache, required_languages) = match reason {
 3656            InlayHintRefreshReason::Toggle(enabled) => {
 3657                self.inlay_hint_cache.enabled = enabled;
 3658                if enabled {
 3659                    (InvalidationStrategy::RefreshRequested, None)
 3660                } else {
 3661                    self.inlay_hint_cache.clear();
 3662                    self.splice_inlays(
 3663                        &self
 3664                            .visible_inlay_hints(cx)
 3665                            .iter()
 3666                            .map(|inlay| inlay.id)
 3667                            .collect::<Vec<InlayId>>(),
 3668                        Vec::new(),
 3669                        cx,
 3670                    );
 3671                    return;
 3672                }
 3673            }
 3674            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3675                match self.inlay_hint_cache.update_settings(
 3676                    &self.buffer,
 3677                    new_settings,
 3678                    self.visible_inlay_hints(cx),
 3679                    cx,
 3680                ) {
 3681                    ControlFlow::Break(Some(InlaySplice {
 3682                        to_remove,
 3683                        to_insert,
 3684                    })) => {
 3685                        self.splice_inlays(&to_remove, to_insert, cx);
 3686                        return;
 3687                    }
 3688                    ControlFlow::Break(None) => return,
 3689                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3690                }
 3691            }
 3692            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3693                if let Some(InlaySplice {
 3694                    to_remove,
 3695                    to_insert,
 3696                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3697                {
 3698                    self.splice_inlays(&to_remove, to_insert, cx);
 3699                }
 3700                return;
 3701            }
 3702            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3703            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3704                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3705            }
 3706            InlayHintRefreshReason::RefreshRequested => {
 3707                (InvalidationStrategy::RefreshRequested, None)
 3708            }
 3709        };
 3710
 3711        if let Some(InlaySplice {
 3712            to_remove,
 3713            to_insert,
 3714        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3715            reason_description,
 3716            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3717            invalidate_cache,
 3718            ignore_debounce,
 3719            cx,
 3720        ) {
 3721            self.splice_inlays(&to_remove, to_insert, cx);
 3722        }
 3723    }
 3724
 3725    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3726        self.display_map
 3727            .read(cx)
 3728            .current_inlays()
 3729            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3730            .cloned()
 3731            .collect()
 3732    }
 3733
 3734    pub fn excerpts_for_inlay_hints_query(
 3735        &self,
 3736        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3737        cx: &mut Context<Editor>,
 3738    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3739        let Some(project) = self.project.as_ref() else {
 3740            return HashMap::default();
 3741        };
 3742        let project = project.read(cx);
 3743        let multi_buffer = self.buffer().read(cx);
 3744        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3745        let multi_buffer_visible_start = self
 3746            .scroll_manager
 3747            .anchor()
 3748            .anchor
 3749            .to_point(&multi_buffer_snapshot);
 3750        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3751            multi_buffer_visible_start
 3752                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3753            Bias::Left,
 3754        );
 3755        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3756        multi_buffer_snapshot
 3757            .range_to_buffer_ranges(multi_buffer_visible_range)
 3758            .into_iter()
 3759            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3760            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3761                let buffer_file = project::File::from_dyn(buffer.file())?;
 3762                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3763                let worktree_entry = buffer_worktree
 3764                    .read(cx)
 3765                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3766                if worktree_entry.is_ignored {
 3767                    return None;
 3768                }
 3769
 3770                let language = buffer.language()?;
 3771                if let Some(restrict_to_languages) = restrict_to_languages {
 3772                    if !restrict_to_languages.contains(language) {
 3773                        return None;
 3774                    }
 3775                }
 3776                Some((
 3777                    excerpt_id,
 3778                    (
 3779                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3780                        buffer.version().clone(),
 3781                        excerpt_visible_range,
 3782                    ),
 3783                ))
 3784            })
 3785            .collect()
 3786    }
 3787
 3788    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3789        TextLayoutDetails {
 3790            text_system: window.text_system().clone(),
 3791            editor_style: self.style.clone().unwrap(),
 3792            rem_size: window.rem_size(),
 3793            scroll_anchor: self.scroll_manager.anchor(),
 3794            visible_rows: self.visible_line_count(),
 3795            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3796        }
 3797    }
 3798
 3799    pub fn splice_inlays(
 3800        &self,
 3801        to_remove: &[InlayId],
 3802        to_insert: Vec<Inlay>,
 3803        cx: &mut Context<Self>,
 3804    ) {
 3805        self.display_map.update(cx, |display_map, cx| {
 3806            display_map.splice_inlays(to_remove, to_insert, cx)
 3807        });
 3808        cx.notify();
 3809    }
 3810
 3811    fn trigger_on_type_formatting(
 3812        &self,
 3813        input: String,
 3814        window: &mut Window,
 3815        cx: &mut Context<Self>,
 3816    ) -> Option<Task<Result<()>>> {
 3817        if input.len() != 1 {
 3818            return None;
 3819        }
 3820
 3821        let project = self.project.as_ref()?;
 3822        let position = self.selections.newest_anchor().head();
 3823        let (buffer, buffer_position) = self
 3824            .buffer
 3825            .read(cx)
 3826            .text_anchor_for_position(position, cx)?;
 3827
 3828        let settings = language_settings::language_settings(
 3829            buffer
 3830                .read(cx)
 3831                .language_at(buffer_position)
 3832                .map(|l| l.name()),
 3833            buffer.read(cx).file(),
 3834            cx,
 3835        );
 3836        if !settings.use_on_type_format {
 3837            return None;
 3838        }
 3839
 3840        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3841        // hence we do LSP request & edit on host side only — add formats to host's history.
 3842        let push_to_lsp_host_history = true;
 3843        // If this is not the host, append its history with new edits.
 3844        let push_to_client_history = project.read(cx).is_via_collab();
 3845
 3846        let on_type_formatting = project.update(cx, |project, cx| {
 3847            project.on_type_format(
 3848                buffer.clone(),
 3849                buffer_position,
 3850                input,
 3851                push_to_lsp_host_history,
 3852                cx,
 3853            )
 3854        });
 3855        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3856            if let Some(transaction) = on_type_formatting.await? {
 3857                if push_to_client_history {
 3858                    buffer
 3859                        .update(&mut cx, |buffer, _| {
 3860                            buffer.push_transaction(transaction, Instant::now());
 3861                        })
 3862                        .ok();
 3863                }
 3864                editor.update(&mut cx, |editor, cx| {
 3865                    editor.refresh_document_highlights(cx);
 3866                })?;
 3867            }
 3868            Ok(())
 3869        }))
 3870    }
 3871
 3872    pub fn show_completions(
 3873        &mut self,
 3874        options: &ShowCompletions,
 3875        window: &mut Window,
 3876        cx: &mut Context<Self>,
 3877    ) {
 3878        if self.pending_rename.is_some() {
 3879            return;
 3880        }
 3881
 3882        let Some(provider) = self.completion_provider.as_ref() else {
 3883            return;
 3884        };
 3885
 3886        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3887            return;
 3888        }
 3889
 3890        let position = self.selections.newest_anchor().head();
 3891        if position.diff_base_anchor.is_some() {
 3892            return;
 3893        }
 3894        let (buffer, buffer_position) =
 3895            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3896                output
 3897            } else {
 3898                return;
 3899            };
 3900        let show_completion_documentation = buffer
 3901            .read(cx)
 3902            .snapshot()
 3903            .settings_at(buffer_position, cx)
 3904            .show_completion_documentation;
 3905
 3906        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3907
 3908        let trigger_kind = match &options.trigger {
 3909            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3910                CompletionTriggerKind::TRIGGER_CHARACTER
 3911            }
 3912            _ => CompletionTriggerKind::INVOKED,
 3913        };
 3914        let completion_context = CompletionContext {
 3915            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3916                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3917                    Some(String::from(trigger))
 3918                } else {
 3919                    None
 3920                }
 3921            }),
 3922            trigger_kind,
 3923        };
 3924        let completions =
 3925            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3926        let sort_completions = provider.sort_completions();
 3927
 3928        let id = post_inc(&mut self.next_completion_id);
 3929        let task = cx.spawn_in(window, |editor, mut cx| {
 3930            async move {
 3931                editor.update(&mut cx, |this, _| {
 3932                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3933                })?;
 3934                let completions = completions.await.log_err();
 3935                let menu = if let Some(completions) = completions {
 3936                    let mut menu = CompletionsMenu::new(
 3937                        id,
 3938                        sort_completions,
 3939                        show_completion_documentation,
 3940                        position,
 3941                        buffer.clone(),
 3942                        completions.into(),
 3943                    );
 3944
 3945                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3946                        .await;
 3947
 3948                    menu.visible().then_some(menu)
 3949                } else {
 3950                    None
 3951                };
 3952
 3953                editor.update_in(&mut cx, |editor, window, cx| {
 3954                    match editor.context_menu.borrow().as_ref() {
 3955                        None => {}
 3956                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3957                            if prev_menu.id > id {
 3958                                return;
 3959                            }
 3960                        }
 3961                        _ => return,
 3962                    }
 3963
 3964                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3965                        let mut menu = menu.unwrap();
 3966                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3967
 3968                        *editor.context_menu.borrow_mut() =
 3969                            Some(CodeContextMenu::Completions(menu));
 3970
 3971                        if editor.show_edit_predictions_in_menu() {
 3972                            editor.update_visible_inline_completion(window, cx);
 3973                        } else {
 3974                            editor.discard_inline_completion(false, cx);
 3975                        }
 3976
 3977                        cx.notify();
 3978                    } else if editor.completion_tasks.len() <= 1 {
 3979                        // If there are no more completion tasks and the last menu was
 3980                        // empty, we should hide it.
 3981                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3982                        // If it was already hidden and we don't show inline
 3983                        // completions in the menu, we should also show the
 3984                        // inline-completion when available.
 3985                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3986                            editor.update_visible_inline_completion(window, cx);
 3987                        }
 3988                    }
 3989                })?;
 3990
 3991                Ok::<_, anyhow::Error>(())
 3992            }
 3993            .log_err()
 3994        });
 3995
 3996        self.completion_tasks.push((id, task));
 3997    }
 3998
 3999    pub fn confirm_completion(
 4000        &mut self,
 4001        action: &ConfirmCompletion,
 4002        window: &mut Window,
 4003        cx: &mut Context<Self>,
 4004    ) -> Option<Task<Result<()>>> {
 4005        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4006    }
 4007
 4008    pub fn compose_completion(
 4009        &mut self,
 4010        action: &ComposeCompletion,
 4011        window: &mut Window,
 4012        cx: &mut Context<Self>,
 4013    ) -> Option<Task<Result<()>>> {
 4014        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4015    }
 4016
 4017    fn do_completion(
 4018        &mut self,
 4019        item_ix: Option<usize>,
 4020        intent: CompletionIntent,
 4021        window: &mut Window,
 4022        cx: &mut Context<Editor>,
 4023    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4024        use language::ToOffset as _;
 4025
 4026        let completions_menu =
 4027            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4028                menu
 4029            } else {
 4030                return None;
 4031            };
 4032
 4033        let entries = completions_menu.entries.borrow();
 4034        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4035        if self.show_edit_predictions_in_menu() {
 4036            self.discard_inline_completion(true, cx);
 4037        }
 4038        let candidate_id = mat.candidate_id;
 4039        drop(entries);
 4040
 4041        let buffer_handle = completions_menu.buffer;
 4042        let completion = completions_menu
 4043            .completions
 4044            .borrow()
 4045            .get(candidate_id)?
 4046            .clone();
 4047        cx.stop_propagation();
 4048
 4049        let snippet;
 4050        let text;
 4051
 4052        if completion.is_snippet() {
 4053            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4054            text = snippet.as_ref().unwrap().text.clone();
 4055        } else {
 4056            snippet = None;
 4057            text = completion.new_text.clone();
 4058        };
 4059        let selections = self.selections.all::<usize>(cx);
 4060        let buffer = buffer_handle.read(cx);
 4061        let old_range = completion.old_range.to_offset(buffer);
 4062        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4063
 4064        let newest_selection = self.selections.newest_anchor();
 4065        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4066            return None;
 4067        }
 4068
 4069        let lookbehind = newest_selection
 4070            .start
 4071            .text_anchor
 4072            .to_offset(buffer)
 4073            .saturating_sub(old_range.start);
 4074        let lookahead = old_range
 4075            .end
 4076            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4077        let mut common_prefix_len = old_text
 4078            .bytes()
 4079            .zip(text.bytes())
 4080            .take_while(|(a, b)| a == b)
 4081            .count();
 4082
 4083        let snapshot = self.buffer.read(cx).snapshot(cx);
 4084        let mut range_to_replace: Option<Range<isize>> = None;
 4085        let mut ranges = Vec::new();
 4086        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4087        for selection in &selections {
 4088            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4089                let start = selection.start.saturating_sub(lookbehind);
 4090                let end = selection.end + lookahead;
 4091                if selection.id == newest_selection.id {
 4092                    range_to_replace = Some(
 4093                        ((start + common_prefix_len) as isize - selection.start as isize)
 4094                            ..(end as isize - selection.start as isize),
 4095                    );
 4096                }
 4097                ranges.push(start + common_prefix_len..end);
 4098            } else {
 4099                common_prefix_len = 0;
 4100                ranges.clear();
 4101                ranges.extend(selections.iter().map(|s| {
 4102                    if s.id == newest_selection.id {
 4103                        range_to_replace = Some(
 4104                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4105                                - selection.start as isize
 4106                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4107                                    - selection.start as isize,
 4108                        );
 4109                        old_range.clone()
 4110                    } else {
 4111                        s.start..s.end
 4112                    }
 4113                }));
 4114                break;
 4115            }
 4116            if !self.linked_edit_ranges.is_empty() {
 4117                let start_anchor = snapshot.anchor_before(selection.head());
 4118                let end_anchor = snapshot.anchor_after(selection.tail());
 4119                if let Some(ranges) = self
 4120                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4121                {
 4122                    for (buffer, edits) in ranges {
 4123                        linked_edits.entry(buffer.clone()).or_default().extend(
 4124                            edits
 4125                                .into_iter()
 4126                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4127                        );
 4128                    }
 4129                }
 4130            }
 4131        }
 4132        let text = &text[common_prefix_len..];
 4133
 4134        cx.emit(EditorEvent::InputHandled {
 4135            utf16_range_to_replace: range_to_replace,
 4136            text: text.into(),
 4137        });
 4138
 4139        self.transact(window, cx, |this, window, cx| {
 4140            if let Some(mut snippet) = snippet {
 4141                snippet.text = text.to_string();
 4142                for tabstop in snippet
 4143                    .tabstops
 4144                    .iter_mut()
 4145                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4146                {
 4147                    tabstop.start -= common_prefix_len as isize;
 4148                    tabstop.end -= common_prefix_len as isize;
 4149                }
 4150
 4151                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4152            } else {
 4153                this.buffer.update(cx, |buffer, cx| {
 4154                    buffer.edit(
 4155                        ranges.iter().map(|range| (range.clone(), text)),
 4156                        this.autoindent_mode.clone(),
 4157                        cx,
 4158                    );
 4159                });
 4160            }
 4161            for (buffer, edits) in linked_edits {
 4162                buffer.update(cx, |buffer, cx| {
 4163                    let snapshot = buffer.snapshot();
 4164                    let edits = edits
 4165                        .into_iter()
 4166                        .map(|(range, text)| {
 4167                            use text::ToPoint as TP;
 4168                            let end_point = TP::to_point(&range.end, &snapshot);
 4169                            let start_point = TP::to_point(&range.start, &snapshot);
 4170                            (start_point..end_point, text)
 4171                        })
 4172                        .sorted_by_key(|(range, _)| range.start)
 4173                        .collect::<Vec<_>>();
 4174                    buffer.edit(edits, None, cx);
 4175                })
 4176            }
 4177
 4178            this.refresh_inline_completion(true, false, window, cx);
 4179        });
 4180
 4181        let show_new_completions_on_confirm = completion
 4182            .confirm
 4183            .as_ref()
 4184            .map_or(false, |confirm| confirm(intent, window, cx));
 4185        if show_new_completions_on_confirm {
 4186            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4187        }
 4188
 4189        let provider = self.completion_provider.as_ref()?;
 4190        drop(completion);
 4191        let apply_edits = provider.apply_additional_edits_for_completion(
 4192            buffer_handle,
 4193            completions_menu.completions.clone(),
 4194            candidate_id,
 4195            true,
 4196            cx,
 4197        );
 4198
 4199        let editor_settings = EditorSettings::get_global(cx);
 4200        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4201            // After the code completion is finished, users often want to know what signatures are needed.
 4202            // so we should automatically call signature_help
 4203            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4204        }
 4205
 4206        Some(cx.foreground_executor().spawn(async move {
 4207            apply_edits.await?;
 4208            Ok(())
 4209        }))
 4210    }
 4211
 4212    pub fn toggle_code_actions(
 4213        &mut self,
 4214        action: &ToggleCodeActions,
 4215        window: &mut Window,
 4216        cx: &mut Context<Self>,
 4217    ) {
 4218        let mut context_menu = self.context_menu.borrow_mut();
 4219        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4220            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4221                // Toggle if we're selecting the same one
 4222                *context_menu = None;
 4223                cx.notify();
 4224                return;
 4225            } else {
 4226                // Otherwise, clear it and start a new one
 4227                *context_menu = None;
 4228                cx.notify();
 4229            }
 4230        }
 4231        drop(context_menu);
 4232        let snapshot = self.snapshot(window, cx);
 4233        let deployed_from_indicator = action.deployed_from_indicator;
 4234        let mut task = self.code_actions_task.take();
 4235        let action = action.clone();
 4236        cx.spawn_in(window, |editor, mut cx| async move {
 4237            while let Some(prev_task) = task {
 4238                prev_task.await.log_err();
 4239                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4240            }
 4241
 4242            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4243                if editor.focus_handle.is_focused(window) {
 4244                    let multibuffer_point = action
 4245                        .deployed_from_indicator
 4246                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4247                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4248                    let (buffer, buffer_row) = snapshot
 4249                        .buffer_snapshot
 4250                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4251                        .and_then(|(buffer_snapshot, range)| {
 4252                            editor
 4253                                .buffer
 4254                                .read(cx)
 4255                                .buffer(buffer_snapshot.remote_id())
 4256                                .map(|buffer| (buffer, range.start.row))
 4257                        })?;
 4258                    let (_, code_actions) = editor
 4259                        .available_code_actions
 4260                        .clone()
 4261                        .and_then(|(location, code_actions)| {
 4262                            let snapshot = location.buffer.read(cx).snapshot();
 4263                            let point_range = location.range.to_point(&snapshot);
 4264                            let point_range = point_range.start.row..=point_range.end.row;
 4265                            if point_range.contains(&buffer_row) {
 4266                                Some((location, code_actions))
 4267                            } else {
 4268                                None
 4269                            }
 4270                        })
 4271                        .unzip();
 4272                    let buffer_id = buffer.read(cx).remote_id();
 4273                    let tasks = editor
 4274                        .tasks
 4275                        .get(&(buffer_id, buffer_row))
 4276                        .map(|t| Arc::new(t.to_owned()));
 4277                    if tasks.is_none() && code_actions.is_none() {
 4278                        return None;
 4279                    }
 4280
 4281                    editor.completion_tasks.clear();
 4282                    editor.discard_inline_completion(false, cx);
 4283                    let task_context =
 4284                        tasks
 4285                            .as_ref()
 4286                            .zip(editor.project.clone())
 4287                            .map(|(tasks, project)| {
 4288                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4289                            });
 4290
 4291                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4292                        let task_context = match task_context {
 4293                            Some(task_context) => task_context.await,
 4294                            None => None,
 4295                        };
 4296                        let resolved_tasks =
 4297                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4298                                Rc::new(ResolvedTasks {
 4299                                    templates: tasks.resolve(&task_context).collect(),
 4300                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4301                                        multibuffer_point.row,
 4302                                        tasks.column,
 4303                                    )),
 4304                                })
 4305                            });
 4306                        let spawn_straight_away = resolved_tasks
 4307                            .as_ref()
 4308                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4309                            && code_actions
 4310                                .as_ref()
 4311                                .map_or(true, |actions| actions.is_empty());
 4312                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4313                            *editor.context_menu.borrow_mut() =
 4314                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4315                                    buffer,
 4316                                    actions: CodeActionContents {
 4317                                        tasks: resolved_tasks,
 4318                                        actions: code_actions,
 4319                                    },
 4320                                    selected_item: Default::default(),
 4321                                    scroll_handle: UniformListScrollHandle::default(),
 4322                                    deployed_from_indicator,
 4323                                }));
 4324                            if spawn_straight_away {
 4325                                if let Some(task) = editor.confirm_code_action(
 4326                                    &ConfirmCodeAction { item_ix: Some(0) },
 4327                                    window,
 4328                                    cx,
 4329                                ) {
 4330                                    cx.notify();
 4331                                    return task;
 4332                                }
 4333                            }
 4334                            cx.notify();
 4335                            Task::ready(Ok(()))
 4336                        }) {
 4337                            task.await
 4338                        } else {
 4339                            Ok(())
 4340                        }
 4341                    }))
 4342                } else {
 4343                    Some(Task::ready(Ok(())))
 4344                }
 4345            })?;
 4346            if let Some(task) = spawned_test_task {
 4347                task.await?;
 4348            }
 4349
 4350            Ok::<_, anyhow::Error>(())
 4351        })
 4352        .detach_and_log_err(cx);
 4353    }
 4354
 4355    pub fn confirm_code_action(
 4356        &mut self,
 4357        action: &ConfirmCodeAction,
 4358        window: &mut Window,
 4359        cx: &mut Context<Self>,
 4360    ) -> Option<Task<Result<()>>> {
 4361        let actions_menu =
 4362            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4363                menu
 4364            } else {
 4365                return None;
 4366            };
 4367        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4368        let action = actions_menu.actions.get(action_ix)?;
 4369        let title = action.label();
 4370        let buffer = actions_menu.buffer;
 4371        let workspace = self.workspace()?;
 4372
 4373        match action {
 4374            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4375                workspace.update(cx, |workspace, cx| {
 4376                    workspace::tasks::schedule_resolved_task(
 4377                        workspace,
 4378                        task_source_kind,
 4379                        resolved_task,
 4380                        false,
 4381                        cx,
 4382                    );
 4383
 4384                    Some(Task::ready(Ok(())))
 4385                })
 4386            }
 4387            CodeActionsItem::CodeAction {
 4388                excerpt_id,
 4389                action,
 4390                provider,
 4391            } => {
 4392                let apply_code_action =
 4393                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4394                let workspace = workspace.downgrade();
 4395                Some(cx.spawn_in(window, |editor, cx| async move {
 4396                    let project_transaction = apply_code_action.await?;
 4397                    Self::open_project_transaction(
 4398                        &editor,
 4399                        workspace,
 4400                        project_transaction,
 4401                        title,
 4402                        cx,
 4403                    )
 4404                    .await
 4405                }))
 4406            }
 4407        }
 4408    }
 4409
 4410    pub async fn open_project_transaction(
 4411        this: &WeakEntity<Editor>,
 4412        workspace: WeakEntity<Workspace>,
 4413        transaction: ProjectTransaction,
 4414        title: String,
 4415        mut cx: AsyncWindowContext,
 4416    ) -> Result<()> {
 4417        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4418        cx.update(|_, cx| {
 4419            entries.sort_unstable_by_key(|(buffer, _)| {
 4420                buffer.read(cx).file().map(|f| f.path().clone())
 4421            });
 4422        })?;
 4423
 4424        // If the project transaction's edits are all contained within this editor, then
 4425        // avoid opening a new editor to display them.
 4426
 4427        if let Some((buffer, transaction)) = entries.first() {
 4428            if entries.len() == 1 {
 4429                let excerpt = this.update(&mut cx, |editor, cx| {
 4430                    editor
 4431                        .buffer()
 4432                        .read(cx)
 4433                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4434                })?;
 4435                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4436                    if excerpted_buffer == *buffer {
 4437                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4438                            let excerpt_range = excerpt_range.to_offset(buffer);
 4439                            buffer
 4440                                .edited_ranges_for_transaction::<usize>(transaction)
 4441                                .all(|range| {
 4442                                    excerpt_range.start <= range.start
 4443                                        && excerpt_range.end >= range.end
 4444                                })
 4445                        })?;
 4446
 4447                        if all_edits_within_excerpt {
 4448                            return Ok(());
 4449                        }
 4450                    }
 4451                }
 4452            }
 4453        } else {
 4454            return Ok(());
 4455        }
 4456
 4457        let mut ranges_to_highlight = Vec::new();
 4458        let excerpt_buffer = cx.new(|cx| {
 4459            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4460            for (buffer_handle, transaction) in &entries {
 4461                let buffer = buffer_handle.read(cx);
 4462                ranges_to_highlight.extend(
 4463                    multibuffer.push_excerpts_with_context_lines(
 4464                        buffer_handle.clone(),
 4465                        buffer
 4466                            .edited_ranges_for_transaction::<usize>(transaction)
 4467                            .collect(),
 4468                        DEFAULT_MULTIBUFFER_CONTEXT,
 4469                        cx,
 4470                    ),
 4471                );
 4472            }
 4473            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4474            multibuffer
 4475        })?;
 4476
 4477        workspace.update_in(&mut cx, |workspace, window, cx| {
 4478            let project = workspace.project().clone();
 4479            let editor = cx
 4480                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4481            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4482            editor.update(cx, |editor, cx| {
 4483                editor.highlight_background::<Self>(
 4484                    &ranges_to_highlight,
 4485                    |theme| theme.editor_highlighted_line_background,
 4486                    cx,
 4487                );
 4488            });
 4489        })?;
 4490
 4491        Ok(())
 4492    }
 4493
 4494    pub fn clear_code_action_providers(&mut self) {
 4495        self.code_action_providers.clear();
 4496        self.available_code_actions.take();
 4497    }
 4498
 4499    pub fn add_code_action_provider(
 4500        &mut self,
 4501        provider: Rc<dyn CodeActionProvider>,
 4502        window: &mut Window,
 4503        cx: &mut Context<Self>,
 4504    ) {
 4505        if self
 4506            .code_action_providers
 4507            .iter()
 4508            .any(|existing_provider| existing_provider.id() == provider.id())
 4509        {
 4510            return;
 4511        }
 4512
 4513        self.code_action_providers.push(provider);
 4514        self.refresh_code_actions(window, cx);
 4515    }
 4516
 4517    pub fn remove_code_action_provider(
 4518        &mut self,
 4519        id: Arc<str>,
 4520        window: &mut Window,
 4521        cx: &mut Context<Self>,
 4522    ) {
 4523        self.code_action_providers
 4524            .retain(|provider| provider.id() != id);
 4525        self.refresh_code_actions(window, cx);
 4526    }
 4527
 4528    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4529        let buffer = self.buffer.read(cx);
 4530        let newest_selection = self.selections.newest_anchor().clone();
 4531        if newest_selection.head().diff_base_anchor.is_some() {
 4532            return None;
 4533        }
 4534        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4535        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4536        if start_buffer != end_buffer {
 4537            return None;
 4538        }
 4539
 4540        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4541            cx.background_executor()
 4542                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4543                .await;
 4544
 4545            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4546                let providers = this.code_action_providers.clone();
 4547                let tasks = this
 4548                    .code_action_providers
 4549                    .iter()
 4550                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4551                    .collect::<Vec<_>>();
 4552                (providers, tasks)
 4553            })?;
 4554
 4555            let mut actions = Vec::new();
 4556            for (provider, provider_actions) in
 4557                providers.into_iter().zip(future::join_all(tasks).await)
 4558            {
 4559                if let Some(provider_actions) = provider_actions.log_err() {
 4560                    actions.extend(provider_actions.into_iter().map(|action| {
 4561                        AvailableCodeAction {
 4562                            excerpt_id: newest_selection.start.excerpt_id,
 4563                            action,
 4564                            provider: provider.clone(),
 4565                        }
 4566                    }));
 4567                }
 4568            }
 4569
 4570            this.update(&mut cx, |this, cx| {
 4571                this.available_code_actions = if actions.is_empty() {
 4572                    None
 4573                } else {
 4574                    Some((
 4575                        Location {
 4576                            buffer: start_buffer,
 4577                            range: start..end,
 4578                        },
 4579                        actions.into(),
 4580                    ))
 4581                };
 4582                cx.notify();
 4583            })
 4584        }));
 4585        None
 4586    }
 4587
 4588    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4589        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4590            self.show_git_blame_inline = false;
 4591
 4592            self.show_git_blame_inline_delay_task =
 4593                Some(cx.spawn_in(window, |this, mut cx| async move {
 4594                    cx.background_executor().timer(delay).await;
 4595
 4596                    this.update(&mut cx, |this, cx| {
 4597                        this.show_git_blame_inline = true;
 4598                        cx.notify();
 4599                    })
 4600                    .log_err();
 4601                }));
 4602        }
 4603    }
 4604
 4605    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4606        if self.pending_rename.is_some() {
 4607            return None;
 4608        }
 4609
 4610        let provider = self.semantics_provider.clone()?;
 4611        let buffer = self.buffer.read(cx);
 4612        let newest_selection = self.selections.newest_anchor().clone();
 4613        let cursor_position = newest_selection.head();
 4614        let (cursor_buffer, cursor_buffer_position) =
 4615            buffer.text_anchor_for_position(cursor_position, cx)?;
 4616        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4617        if cursor_buffer != tail_buffer {
 4618            return None;
 4619        }
 4620        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4621        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4622            cx.background_executor()
 4623                .timer(Duration::from_millis(debounce))
 4624                .await;
 4625
 4626            let highlights = if let Some(highlights) = cx
 4627                .update(|cx| {
 4628                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4629                })
 4630                .ok()
 4631                .flatten()
 4632            {
 4633                highlights.await.log_err()
 4634            } else {
 4635                None
 4636            };
 4637
 4638            if let Some(highlights) = highlights {
 4639                this.update(&mut cx, |this, cx| {
 4640                    if this.pending_rename.is_some() {
 4641                        return;
 4642                    }
 4643
 4644                    let buffer_id = cursor_position.buffer_id;
 4645                    let buffer = this.buffer.read(cx);
 4646                    if !buffer
 4647                        .text_anchor_for_position(cursor_position, cx)
 4648                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4649                    {
 4650                        return;
 4651                    }
 4652
 4653                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4654                    let mut write_ranges = Vec::new();
 4655                    let mut read_ranges = Vec::new();
 4656                    for highlight in highlights {
 4657                        for (excerpt_id, excerpt_range) in
 4658                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4659                        {
 4660                            let start = highlight
 4661                                .range
 4662                                .start
 4663                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4664                            let end = highlight
 4665                                .range
 4666                                .end
 4667                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4668                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4669                                continue;
 4670                            }
 4671
 4672                            let range = Anchor {
 4673                                buffer_id,
 4674                                excerpt_id,
 4675                                text_anchor: start,
 4676                                diff_base_anchor: None,
 4677                            }..Anchor {
 4678                                buffer_id,
 4679                                excerpt_id,
 4680                                text_anchor: end,
 4681                                diff_base_anchor: None,
 4682                            };
 4683                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4684                                write_ranges.push(range);
 4685                            } else {
 4686                                read_ranges.push(range);
 4687                            }
 4688                        }
 4689                    }
 4690
 4691                    this.highlight_background::<DocumentHighlightRead>(
 4692                        &read_ranges,
 4693                        |theme| theme.editor_document_highlight_read_background,
 4694                        cx,
 4695                    );
 4696                    this.highlight_background::<DocumentHighlightWrite>(
 4697                        &write_ranges,
 4698                        |theme| theme.editor_document_highlight_write_background,
 4699                        cx,
 4700                    );
 4701                    cx.notify();
 4702                })
 4703                .log_err();
 4704            }
 4705        }));
 4706        None
 4707    }
 4708
 4709    pub fn refresh_selected_text_highlights(
 4710        &mut self,
 4711        window: &mut Window,
 4712        cx: &mut Context<Editor>,
 4713    ) {
 4714        self.selection_highlight_task.take();
 4715        if !EditorSettings::get_global(cx).selection_highlight {
 4716            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4717            return;
 4718        }
 4719        if self.selections.count() != 1 || self.selections.line_mode {
 4720            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4721            return;
 4722        }
 4723        let selection = self.selections.newest::<Point>(cx);
 4724        if selection.is_empty() || selection.start.row != selection.end.row {
 4725            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4726            return;
 4727        }
 4728        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4729        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4730            cx.background_executor()
 4731                .timer(Duration::from_millis(debounce))
 4732                .await;
 4733            let Some(Some(matches_task)) = editor
 4734                .update_in(&mut cx, |editor, _, cx| {
 4735                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4736                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4737                        return None;
 4738                    }
 4739                    let selection = editor.selections.newest::<Point>(cx);
 4740                    if selection.is_empty() || selection.start.row != selection.end.row {
 4741                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4742                        return None;
 4743                    }
 4744                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4745                    let query = buffer.text_for_range(selection.range()).collect::<String>();
 4746                    if query.trim().is_empty() {
 4747                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4748                        return None;
 4749                    }
 4750                    Some(cx.background_spawn(async move {
 4751                        let mut ranges = Vec::new();
 4752                        let selection_anchors = selection.range().to_anchors(&buffer);
 4753                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4754                            for (search_buffer, search_range, excerpt_id) in
 4755                                buffer.range_to_buffer_ranges(range)
 4756                            {
 4757                                ranges.extend(
 4758                                    project::search::SearchQuery::text(
 4759                                        query.clone(),
 4760                                        false,
 4761                                        false,
 4762                                        false,
 4763                                        Default::default(),
 4764                                        Default::default(),
 4765                                        None,
 4766                                    )
 4767                                    .unwrap()
 4768                                    .search(search_buffer, Some(search_range.clone()))
 4769                                    .await
 4770                                    .into_iter()
 4771                                    .filter_map(
 4772                                        |match_range| {
 4773                                            let start = search_buffer.anchor_after(
 4774                                                search_range.start + match_range.start,
 4775                                            );
 4776                                            let end = search_buffer.anchor_before(
 4777                                                search_range.start + match_range.end,
 4778                                            );
 4779                                            let range = Anchor::range_in_buffer(
 4780                                                excerpt_id,
 4781                                                search_buffer.remote_id(),
 4782                                                start..end,
 4783                                            );
 4784                                            (range != selection_anchors).then_some(range)
 4785                                        },
 4786                                    ),
 4787                                );
 4788                            }
 4789                        }
 4790                        ranges
 4791                    }))
 4792                })
 4793                .log_err()
 4794            else {
 4795                return;
 4796            };
 4797            let matches = matches_task.await;
 4798            editor
 4799                .update_in(&mut cx, |editor, _, cx| {
 4800                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4801                    if !matches.is_empty() {
 4802                        editor.highlight_background::<SelectedTextHighlight>(
 4803                            &matches,
 4804                            |theme| theme.editor_document_highlight_bracket_background,
 4805                            cx,
 4806                        )
 4807                    }
 4808                })
 4809                .log_err();
 4810        }));
 4811    }
 4812
 4813    pub fn refresh_inline_completion(
 4814        &mut self,
 4815        debounce: bool,
 4816        user_requested: bool,
 4817        window: &mut Window,
 4818        cx: &mut Context<Self>,
 4819    ) -> Option<()> {
 4820        let provider = self.edit_prediction_provider()?;
 4821        let cursor = self.selections.newest_anchor().head();
 4822        let (buffer, cursor_buffer_position) =
 4823            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4824
 4825        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4826            self.discard_inline_completion(false, cx);
 4827            return None;
 4828        }
 4829
 4830        if !user_requested
 4831            && (!self.should_show_edit_predictions()
 4832                || !self.is_focused(window)
 4833                || buffer.read(cx).is_empty())
 4834        {
 4835            self.discard_inline_completion(false, cx);
 4836            return None;
 4837        }
 4838
 4839        self.update_visible_inline_completion(window, cx);
 4840        provider.refresh(
 4841            self.project.clone(),
 4842            buffer,
 4843            cursor_buffer_position,
 4844            debounce,
 4845            cx,
 4846        );
 4847        Some(())
 4848    }
 4849
 4850    fn show_edit_predictions_in_menu(&self) -> bool {
 4851        match self.edit_prediction_settings {
 4852            EditPredictionSettings::Disabled => false,
 4853            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4854        }
 4855    }
 4856
 4857    pub fn edit_predictions_enabled(&self) -> bool {
 4858        match self.edit_prediction_settings {
 4859            EditPredictionSettings::Disabled => false,
 4860            EditPredictionSettings::Enabled { .. } => true,
 4861        }
 4862    }
 4863
 4864    fn edit_prediction_requires_modifier(&self) -> bool {
 4865        match self.edit_prediction_settings {
 4866            EditPredictionSettings::Disabled => false,
 4867            EditPredictionSettings::Enabled {
 4868                preview_requires_modifier,
 4869                ..
 4870            } => preview_requires_modifier,
 4871        }
 4872    }
 4873
 4874    fn edit_prediction_settings_at_position(
 4875        &self,
 4876        buffer: &Entity<Buffer>,
 4877        buffer_position: language::Anchor,
 4878        cx: &App,
 4879    ) -> EditPredictionSettings {
 4880        if self.mode != EditorMode::Full
 4881            || !self.show_inline_completions_override.unwrap_or(true)
 4882            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4883        {
 4884            return EditPredictionSettings::Disabled;
 4885        }
 4886
 4887        let buffer = buffer.read(cx);
 4888
 4889        let file = buffer.file();
 4890
 4891        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4892            return EditPredictionSettings::Disabled;
 4893        };
 4894
 4895        let by_provider = matches!(
 4896            self.menu_inline_completions_policy,
 4897            MenuInlineCompletionsPolicy::ByProvider
 4898        );
 4899
 4900        let show_in_menu = by_provider
 4901            && self
 4902                .edit_prediction_provider
 4903                .as_ref()
 4904                .map_or(false, |provider| {
 4905                    provider.provider.show_completions_in_menu()
 4906                });
 4907
 4908        let preview_requires_modifier =
 4909            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4910
 4911        EditPredictionSettings::Enabled {
 4912            show_in_menu,
 4913            preview_requires_modifier,
 4914        }
 4915    }
 4916
 4917    fn should_show_edit_predictions(&self) -> bool {
 4918        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4919    }
 4920
 4921    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4922        matches!(
 4923            self.edit_prediction_preview,
 4924            EditPredictionPreview::Active { .. }
 4925        )
 4926    }
 4927
 4928    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4929        let cursor = self.selections.newest_anchor().head();
 4930        if let Some((buffer, cursor_position)) =
 4931            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4932        {
 4933            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4934        } else {
 4935            false
 4936        }
 4937    }
 4938
 4939    fn inline_completions_enabled_in_buffer(
 4940        &self,
 4941        buffer: &Entity<Buffer>,
 4942        buffer_position: language::Anchor,
 4943        cx: &App,
 4944    ) -> bool {
 4945        maybe!({
 4946            let provider = self.edit_prediction_provider()?;
 4947            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4948                return Some(false);
 4949            }
 4950            let buffer = buffer.read(cx);
 4951            let Some(file) = buffer.file() else {
 4952                return Some(true);
 4953            };
 4954            let settings = all_language_settings(Some(file), cx);
 4955            Some(settings.inline_completions_enabled_for_path(file.path()))
 4956        })
 4957        .unwrap_or(false)
 4958    }
 4959
 4960    fn cycle_inline_completion(
 4961        &mut self,
 4962        direction: Direction,
 4963        window: &mut Window,
 4964        cx: &mut Context<Self>,
 4965    ) -> Option<()> {
 4966        let provider = self.edit_prediction_provider()?;
 4967        let cursor = self.selections.newest_anchor().head();
 4968        let (buffer, cursor_buffer_position) =
 4969            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4970        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4971            return None;
 4972        }
 4973
 4974        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4975        self.update_visible_inline_completion(window, cx);
 4976
 4977        Some(())
 4978    }
 4979
 4980    pub fn show_inline_completion(
 4981        &mut self,
 4982        _: &ShowEditPrediction,
 4983        window: &mut Window,
 4984        cx: &mut Context<Self>,
 4985    ) {
 4986        if !self.has_active_inline_completion() {
 4987            self.refresh_inline_completion(false, true, window, cx);
 4988            return;
 4989        }
 4990
 4991        self.update_visible_inline_completion(window, cx);
 4992    }
 4993
 4994    pub fn display_cursor_names(
 4995        &mut self,
 4996        _: &DisplayCursorNames,
 4997        window: &mut Window,
 4998        cx: &mut Context<Self>,
 4999    ) {
 5000        self.show_cursor_names(window, cx);
 5001    }
 5002
 5003    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5004        self.show_cursor_names = true;
 5005        cx.notify();
 5006        cx.spawn_in(window, |this, mut cx| async move {
 5007            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5008            this.update(&mut cx, |this, cx| {
 5009                this.show_cursor_names = false;
 5010                cx.notify()
 5011            })
 5012            .ok()
 5013        })
 5014        .detach();
 5015    }
 5016
 5017    pub fn next_edit_prediction(
 5018        &mut self,
 5019        _: &NextEditPrediction,
 5020        window: &mut Window,
 5021        cx: &mut Context<Self>,
 5022    ) {
 5023        if self.has_active_inline_completion() {
 5024            self.cycle_inline_completion(Direction::Next, window, cx);
 5025        } else {
 5026            let is_copilot_disabled = self
 5027                .refresh_inline_completion(false, true, window, cx)
 5028                .is_none();
 5029            if is_copilot_disabled {
 5030                cx.propagate();
 5031            }
 5032        }
 5033    }
 5034
 5035    pub fn previous_edit_prediction(
 5036        &mut self,
 5037        _: &PreviousEditPrediction,
 5038        window: &mut Window,
 5039        cx: &mut Context<Self>,
 5040    ) {
 5041        if self.has_active_inline_completion() {
 5042            self.cycle_inline_completion(Direction::Prev, window, cx);
 5043        } else {
 5044            let is_copilot_disabled = self
 5045                .refresh_inline_completion(false, true, window, cx)
 5046                .is_none();
 5047            if is_copilot_disabled {
 5048                cx.propagate();
 5049            }
 5050        }
 5051    }
 5052
 5053    pub fn accept_edit_prediction(
 5054        &mut self,
 5055        _: &AcceptEditPrediction,
 5056        window: &mut Window,
 5057        cx: &mut Context<Self>,
 5058    ) {
 5059        if self.show_edit_predictions_in_menu() {
 5060            self.hide_context_menu(window, cx);
 5061        }
 5062
 5063        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5064            return;
 5065        };
 5066
 5067        self.report_inline_completion_event(
 5068            active_inline_completion.completion_id.clone(),
 5069            true,
 5070            cx,
 5071        );
 5072
 5073        match &active_inline_completion.completion {
 5074            InlineCompletion::Move { target, .. } => {
 5075                let target = *target;
 5076
 5077                if let Some(position_map) = &self.last_position_map {
 5078                    if position_map
 5079                        .visible_row_range
 5080                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5081                        || !self.edit_prediction_requires_modifier()
 5082                    {
 5083                        self.unfold_ranges(&[target..target], true, false, cx);
 5084                        // Note that this is also done in vim's handler of the Tab action.
 5085                        self.change_selections(
 5086                            Some(Autoscroll::newest()),
 5087                            window,
 5088                            cx,
 5089                            |selections| {
 5090                                selections.select_anchor_ranges([target..target]);
 5091                            },
 5092                        );
 5093                        self.clear_row_highlights::<EditPredictionPreview>();
 5094
 5095                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5096                            previous_scroll_position: None,
 5097                        };
 5098                    } else {
 5099                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5100                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5101                        };
 5102                        self.highlight_rows::<EditPredictionPreview>(
 5103                            target..target,
 5104                            cx.theme().colors().editor_highlighted_line_background,
 5105                            true,
 5106                            cx,
 5107                        );
 5108                        self.request_autoscroll(Autoscroll::fit(), cx);
 5109                    }
 5110                }
 5111            }
 5112            InlineCompletion::Edit { edits, .. } => {
 5113                if let Some(provider) = self.edit_prediction_provider() {
 5114                    provider.accept(cx);
 5115                }
 5116
 5117                let snapshot = self.buffer.read(cx).snapshot(cx);
 5118                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5119
 5120                self.buffer.update(cx, |buffer, cx| {
 5121                    buffer.edit(edits.iter().cloned(), None, cx)
 5122                });
 5123
 5124                self.change_selections(None, window, cx, |s| {
 5125                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5126                });
 5127
 5128                self.update_visible_inline_completion(window, cx);
 5129                if self.active_inline_completion.is_none() {
 5130                    self.refresh_inline_completion(true, true, window, cx);
 5131                }
 5132
 5133                cx.notify();
 5134            }
 5135        }
 5136
 5137        self.edit_prediction_requires_modifier_in_indent_conflict = false;
 5138    }
 5139
 5140    pub fn accept_partial_inline_completion(
 5141        &mut self,
 5142        _: &AcceptPartialEditPrediction,
 5143        window: &mut Window,
 5144        cx: &mut Context<Self>,
 5145    ) {
 5146        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5147            return;
 5148        };
 5149        if self.selections.count() != 1 {
 5150            return;
 5151        }
 5152
 5153        self.report_inline_completion_event(
 5154            active_inline_completion.completion_id.clone(),
 5155            true,
 5156            cx,
 5157        );
 5158
 5159        match &active_inline_completion.completion {
 5160            InlineCompletion::Move { target, .. } => {
 5161                let target = *target;
 5162                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5163                    selections.select_anchor_ranges([target..target]);
 5164                });
 5165            }
 5166            InlineCompletion::Edit { edits, .. } => {
 5167                // Find an insertion that starts at the cursor position.
 5168                let snapshot = self.buffer.read(cx).snapshot(cx);
 5169                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5170                let insertion = edits.iter().find_map(|(range, text)| {
 5171                    let range = range.to_offset(&snapshot);
 5172                    if range.is_empty() && range.start == cursor_offset {
 5173                        Some(text)
 5174                    } else {
 5175                        None
 5176                    }
 5177                });
 5178
 5179                if let Some(text) = insertion {
 5180                    let mut partial_completion = text
 5181                        .chars()
 5182                        .by_ref()
 5183                        .take_while(|c| c.is_alphabetic())
 5184                        .collect::<String>();
 5185                    if partial_completion.is_empty() {
 5186                        partial_completion = text
 5187                            .chars()
 5188                            .by_ref()
 5189                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5190                            .collect::<String>();
 5191                    }
 5192
 5193                    cx.emit(EditorEvent::InputHandled {
 5194                        utf16_range_to_replace: None,
 5195                        text: partial_completion.clone().into(),
 5196                    });
 5197
 5198                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5199
 5200                    self.refresh_inline_completion(true, true, window, cx);
 5201                    cx.notify();
 5202                } else {
 5203                    self.accept_edit_prediction(&Default::default(), window, cx);
 5204                }
 5205            }
 5206        }
 5207    }
 5208
 5209    fn discard_inline_completion(
 5210        &mut self,
 5211        should_report_inline_completion_event: bool,
 5212        cx: &mut Context<Self>,
 5213    ) -> bool {
 5214        if should_report_inline_completion_event {
 5215            let completion_id = self
 5216                .active_inline_completion
 5217                .as_ref()
 5218                .and_then(|active_completion| active_completion.completion_id.clone());
 5219
 5220            self.report_inline_completion_event(completion_id, false, cx);
 5221        }
 5222
 5223        if let Some(provider) = self.edit_prediction_provider() {
 5224            provider.discard(cx);
 5225        }
 5226
 5227        self.take_active_inline_completion(cx)
 5228    }
 5229
 5230    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5231        let Some(provider) = self.edit_prediction_provider() else {
 5232            return;
 5233        };
 5234
 5235        let Some((_, buffer, _)) = self
 5236            .buffer
 5237            .read(cx)
 5238            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5239        else {
 5240            return;
 5241        };
 5242
 5243        let extension = buffer
 5244            .read(cx)
 5245            .file()
 5246            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5247
 5248        let event_type = match accepted {
 5249            true => "Edit Prediction Accepted",
 5250            false => "Edit Prediction Discarded",
 5251        };
 5252        telemetry::event!(
 5253            event_type,
 5254            provider = provider.name(),
 5255            prediction_id = id,
 5256            suggestion_accepted = accepted,
 5257            file_extension = extension,
 5258        );
 5259    }
 5260
 5261    pub fn has_active_inline_completion(&self) -> bool {
 5262        self.active_inline_completion.is_some()
 5263    }
 5264
 5265    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5266        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5267            return false;
 5268        };
 5269
 5270        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5271        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5272        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5273        true
 5274    }
 5275
 5276    /// Returns true when we're displaying the edit prediction popover below the cursor
 5277    /// like we are not previewing and the LSP autocomplete menu is visible
 5278    /// or we are in `when_holding_modifier` mode.
 5279    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5280        if self.edit_prediction_preview_is_active()
 5281            || !self.show_edit_predictions_in_menu()
 5282            || !self.edit_predictions_enabled()
 5283        {
 5284            return false;
 5285        }
 5286
 5287        if self.has_visible_completions_menu() {
 5288            return true;
 5289        }
 5290
 5291        has_completion && self.edit_prediction_requires_modifier()
 5292    }
 5293
 5294    fn handle_modifiers_changed(
 5295        &mut self,
 5296        modifiers: Modifiers,
 5297        position_map: &PositionMap,
 5298        window: &mut Window,
 5299        cx: &mut Context<Self>,
 5300    ) {
 5301        if self.show_edit_predictions_in_menu() {
 5302            self.update_edit_prediction_preview(&modifiers, window, cx);
 5303        }
 5304
 5305        self.update_selection_mode(&modifiers, position_map, window, cx);
 5306
 5307        let mouse_position = window.mouse_position();
 5308        if !position_map.text_hitbox.is_hovered(window) {
 5309            return;
 5310        }
 5311
 5312        self.update_hovered_link(
 5313            position_map.point_for_position(mouse_position),
 5314            &position_map.snapshot,
 5315            modifiers,
 5316            window,
 5317            cx,
 5318        )
 5319    }
 5320
 5321    fn update_selection_mode(
 5322        &mut self,
 5323        modifiers: &Modifiers,
 5324        position_map: &PositionMap,
 5325        window: &mut Window,
 5326        cx: &mut Context<Self>,
 5327    ) {
 5328        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5329            return;
 5330        }
 5331
 5332        let mouse_position = window.mouse_position();
 5333        let point_for_position = position_map.point_for_position(mouse_position);
 5334        let position = point_for_position.previous_valid;
 5335
 5336        self.select(
 5337            SelectPhase::BeginColumnar {
 5338                position,
 5339                reset: false,
 5340                goal_column: point_for_position.exact_unclipped.column(),
 5341            },
 5342            window,
 5343            cx,
 5344        );
 5345    }
 5346
 5347    fn update_edit_prediction_preview(
 5348        &mut self,
 5349        modifiers: &Modifiers,
 5350        window: &mut Window,
 5351        cx: &mut Context<Self>,
 5352    ) {
 5353        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5354        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5355            return;
 5356        };
 5357
 5358        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5359            if matches!(
 5360                self.edit_prediction_preview,
 5361                EditPredictionPreview::Inactive
 5362            ) {
 5363                self.edit_prediction_preview = EditPredictionPreview::Active {
 5364                    previous_scroll_position: None,
 5365                };
 5366
 5367                self.update_visible_inline_completion(window, cx);
 5368                cx.notify();
 5369            }
 5370        } else if let EditPredictionPreview::Active {
 5371            previous_scroll_position,
 5372        } = self.edit_prediction_preview
 5373        {
 5374            if let (Some(previous_scroll_position), Some(position_map)) =
 5375                (previous_scroll_position, self.last_position_map.as_ref())
 5376            {
 5377                self.set_scroll_position(
 5378                    previous_scroll_position
 5379                        .scroll_position(&position_map.snapshot.display_snapshot),
 5380                    window,
 5381                    cx,
 5382                );
 5383            }
 5384
 5385            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5386            self.clear_row_highlights::<EditPredictionPreview>();
 5387            self.update_visible_inline_completion(window, cx);
 5388            cx.notify();
 5389        }
 5390    }
 5391
 5392    fn update_visible_inline_completion(
 5393        &mut self,
 5394        _window: &mut Window,
 5395        cx: &mut Context<Self>,
 5396    ) -> Option<()> {
 5397        let selection = self.selections.newest_anchor();
 5398        let cursor = selection.head();
 5399        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5400        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5401        let excerpt_id = cursor.excerpt_id;
 5402
 5403        let show_in_menu = self.show_edit_predictions_in_menu();
 5404        let completions_menu_has_precedence = !show_in_menu
 5405            && (self.context_menu.borrow().is_some()
 5406                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5407
 5408        if completions_menu_has_precedence
 5409            || !offset_selection.is_empty()
 5410            || self
 5411                .active_inline_completion
 5412                .as_ref()
 5413                .map_or(false, |completion| {
 5414                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5415                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5416                    !invalidation_range.contains(&offset_selection.head())
 5417                })
 5418        {
 5419            self.discard_inline_completion(false, cx);
 5420            return None;
 5421        }
 5422
 5423        self.take_active_inline_completion(cx);
 5424        let Some(provider) = self.edit_prediction_provider() else {
 5425            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5426            return None;
 5427        };
 5428
 5429        let (buffer, cursor_buffer_position) =
 5430            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5431
 5432        self.edit_prediction_settings =
 5433            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5434
 5435        self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
 5436
 5437        if self.edit_prediction_indent_conflict {
 5438            let cursor_point = cursor.to_point(&multibuffer);
 5439
 5440            let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
 5441
 5442            if let Some((_, indent)) = indents.iter().next() {
 5443                if indent.len == cursor_point.column {
 5444                    self.edit_prediction_indent_conflict = false;
 5445                }
 5446            }
 5447        }
 5448
 5449        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5450        let edits = inline_completion
 5451            .edits
 5452            .into_iter()
 5453            .flat_map(|(range, new_text)| {
 5454                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5455                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5456                Some((start..end, new_text))
 5457            })
 5458            .collect::<Vec<_>>();
 5459        if edits.is_empty() {
 5460            return None;
 5461        }
 5462
 5463        let first_edit_start = edits.first().unwrap().0.start;
 5464        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5465        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5466
 5467        let last_edit_end = edits.last().unwrap().0.end;
 5468        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5469        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5470
 5471        let cursor_row = cursor.to_point(&multibuffer).row;
 5472
 5473        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5474
 5475        let mut inlay_ids = Vec::new();
 5476        let invalidation_row_range;
 5477        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5478            Some(cursor_row..edit_end_row)
 5479        } else if cursor_row > edit_end_row {
 5480            Some(edit_start_row..cursor_row)
 5481        } else {
 5482            None
 5483        };
 5484        let is_move =
 5485            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5486        let completion = if is_move {
 5487            invalidation_row_range =
 5488                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5489            let target = first_edit_start;
 5490            InlineCompletion::Move { target, snapshot }
 5491        } else {
 5492            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5493                && !self.inline_completions_hidden_for_vim_mode;
 5494
 5495            if show_completions_in_buffer {
 5496                if edits
 5497                    .iter()
 5498                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5499                {
 5500                    let mut inlays = Vec::new();
 5501                    for (range, new_text) in &edits {
 5502                        let inlay = Inlay::inline_completion(
 5503                            post_inc(&mut self.next_inlay_id),
 5504                            range.start,
 5505                            new_text.as_str(),
 5506                        );
 5507                        inlay_ids.push(inlay.id);
 5508                        inlays.push(inlay);
 5509                    }
 5510
 5511                    self.splice_inlays(&[], inlays, cx);
 5512                } else {
 5513                    let background_color = cx.theme().status().deleted_background;
 5514                    self.highlight_text::<InlineCompletionHighlight>(
 5515                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5516                        HighlightStyle {
 5517                            background_color: Some(background_color),
 5518                            ..Default::default()
 5519                        },
 5520                        cx,
 5521                    );
 5522                }
 5523            }
 5524
 5525            invalidation_row_range = edit_start_row..edit_end_row;
 5526
 5527            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5528                if provider.show_tab_accept_marker() {
 5529                    EditDisplayMode::TabAccept
 5530                } else {
 5531                    EditDisplayMode::Inline
 5532                }
 5533            } else {
 5534                EditDisplayMode::DiffPopover
 5535            };
 5536
 5537            InlineCompletion::Edit {
 5538                edits,
 5539                edit_preview: inline_completion.edit_preview,
 5540                display_mode,
 5541                snapshot,
 5542            }
 5543        };
 5544
 5545        let invalidation_range = multibuffer
 5546            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5547            ..multibuffer.anchor_after(Point::new(
 5548                invalidation_row_range.end,
 5549                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5550            ));
 5551
 5552        self.stale_inline_completion_in_menu = None;
 5553        self.active_inline_completion = Some(InlineCompletionState {
 5554            inlay_ids,
 5555            completion,
 5556            completion_id: inline_completion.id,
 5557            invalidation_range,
 5558        });
 5559
 5560        cx.notify();
 5561
 5562        Some(())
 5563    }
 5564
 5565    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5566        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5567    }
 5568
 5569    fn render_code_actions_indicator(
 5570        &self,
 5571        _style: &EditorStyle,
 5572        row: DisplayRow,
 5573        is_active: bool,
 5574        cx: &mut Context<Self>,
 5575    ) -> Option<IconButton> {
 5576        if self.available_code_actions.is_some() {
 5577            Some(
 5578                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5579                    .shape(ui::IconButtonShape::Square)
 5580                    .icon_size(IconSize::XSmall)
 5581                    .icon_color(Color::Muted)
 5582                    .toggle_state(is_active)
 5583                    .tooltip({
 5584                        let focus_handle = self.focus_handle.clone();
 5585                        move |window, cx| {
 5586                            Tooltip::for_action_in(
 5587                                "Toggle Code Actions",
 5588                                &ToggleCodeActions {
 5589                                    deployed_from_indicator: None,
 5590                                },
 5591                                &focus_handle,
 5592                                window,
 5593                                cx,
 5594                            )
 5595                        }
 5596                    })
 5597                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5598                        window.focus(&editor.focus_handle(cx));
 5599                        editor.toggle_code_actions(
 5600                            &ToggleCodeActions {
 5601                                deployed_from_indicator: Some(row),
 5602                            },
 5603                            window,
 5604                            cx,
 5605                        );
 5606                    })),
 5607            )
 5608        } else {
 5609            None
 5610        }
 5611    }
 5612
 5613    fn clear_tasks(&mut self) {
 5614        self.tasks.clear()
 5615    }
 5616
 5617    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5618        if self.tasks.insert(key, value).is_some() {
 5619            // This case should hopefully be rare, but just in case...
 5620            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5621        }
 5622    }
 5623
 5624    fn build_tasks_context(
 5625        project: &Entity<Project>,
 5626        buffer: &Entity<Buffer>,
 5627        buffer_row: u32,
 5628        tasks: &Arc<RunnableTasks>,
 5629        cx: &mut Context<Self>,
 5630    ) -> Task<Option<task::TaskContext>> {
 5631        let position = Point::new(buffer_row, tasks.column);
 5632        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5633        let location = Location {
 5634            buffer: buffer.clone(),
 5635            range: range_start..range_start,
 5636        };
 5637        // Fill in the environmental variables from the tree-sitter captures
 5638        let mut captured_task_variables = TaskVariables::default();
 5639        for (capture_name, value) in tasks.extra_variables.clone() {
 5640            captured_task_variables.insert(
 5641                task::VariableName::Custom(capture_name.into()),
 5642                value.clone(),
 5643            );
 5644        }
 5645        project.update(cx, |project, cx| {
 5646            project.task_store().update(cx, |task_store, cx| {
 5647                task_store.task_context_for_location(captured_task_variables, location, cx)
 5648            })
 5649        })
 5650    }
 5651
 5652    pub fn spawn_nearest_task(
 5653        &mut self,
 5654        action: &SpawnNearestTask,
 5655        window: &mut Window,
 5656        cx: &mut Context<Self>,
 5657    ) {
 5658        let Some((workspace, _)) = self.workspace.clone() else {
 5659            return;
 5660        };
 5661        let Some(project) = self.project.clone() else {
 5662            return;
 5663        };
 5664
 5665        // Try to find a closest, enclosing node using tree-sitter that has a
 5666        // task
 5667        let Some((buffer, buffer_row, tasks)) = self
 5668            .find_enclosing_node_task(cx)
 5669            // Or find the task that's closest in row-distance.
 5670            .or_else(|| self.find_closest_task(cx))
 5671        else {
 5672            return;
 5673        };
 5674
 5675        let reveal_strategy = action.reveal;
 5676        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5677        cx.spawn_in(window, |_, mut cx| async move {
 5678            let context = task_context.await?;
 5679            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5680
 5681            let resolved = resolved_task.resolved.as_mut()?;
 5682            resolved.reveal = reveal_strategy;
 5683
 5684            workspace
 5685                .update(&mut cx, |workspace, cx| {
 5686                    workspace::tasks::schedule_resolved_task(
 5687                        workspace,
 5688                        task_source_kind,
 5689                        resolved_task,
 5690                        false,
 5691                        cx,
 5692                    );
 5693                })
 5694                .ok()
 5695        })
 5696        .detach();
 5697    }
 5698
 5699    fn find_closest_task(
 5700        &mut self,
 5701        cx: &mut Context<Self>,
 5702    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5703        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5704
 5705        let ((buffer_id, row), tasks) = self
 5706            .tasks
 5707            .iter()
 5708            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5709
 5710        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5711        let tasks = Arc::new(tasks.to_owned());
 5712        Some((buffer, *row, tasks))
 5713    }
 5714
 5715    fn find_enclosing_node_task(
 5716        &mut self,
 5717        cx: &mut Context<Self>,
 5718    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5719        let snapshot = self.buffer.read(cx).snapshot(cx);
 5720        let offset = self.selections.newest::<usize>(cx).head();
 5721        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5722        let buffer_id = excerpt.buffer().remote_id();
 5723
 5724        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5725        let mut cursor = layer.node().walk();
 5726
 5727        while cursor.goto_first_child_for_byte(offset).is_some() {
 5728            if cursor.node().end_byte() == offset {
 5729                cursor.goto_next_sibling();
 5730            }
 5731        }
 5732
 5733        // Ascend to the smallest ancestor that contains the range and has a task.
 5734        loop {
 5735            let node = cursor.node();
 5736            let node_range = node.byte_range();
 5737            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5738
 5739            // Check if this node contains our offset
 5740            if node_range.start <= offset && node_range.end >= offset {
 5741                // If it contains offset, check for task
 5742                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5743                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5744                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5745                }
 5746            }
 5747
 5748            if !cursor.goto_parent() {
 5749                break;
 5750            }
 5751        }
 5752        None
 5753    }
 5754
 5755    fn render_run_indicator(
 5756        &self,
 5757        _style: &EditorStyle,
 5758        is_active: bool,
 5759        row: DisplayRow,
 5760        cx: &mut Context<Self>,
 5761    ) -> IconButton {
 5762        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5763            .shape(ui::IconButtonShape::Square)
 5764            .icon_size(IconSize::XSmall)
 5765            .icon_color(Color::Muted)
 5766            .toggle_state(is_active)
 5767            .on_click(cx.listener(move |editor, _e, window, cx| {
 5768                window.focus(&editor.focus_handle(cx));
 5769                editor.toggle_code_actions(
 5770                    &ToggleCodeActions {
 5771                        deployed_from_indicator: Some(row),
 5772                    },
 5773                    window,
 5774                    cx,
 5775                );
 5776            }))
 5777    }
 5778
 5779    pub fn context_menu_visible(&self) -> bool {
 5780        !self.edit_prediction_preview_is_active()
 5781            && self
 5782                .context_menu
 5783                .borrow()
 5784                .as_ref()
 5785                .map_or(false, |menu| menu.visible())
 5786    }
 5787
 5788    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5789        self.context_menu
 5790            .borrow()
 5791            .as_ref()
 5792            .map(|menu| menu.origin())
 5793    }
 5794
 5795    const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
 5796    const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
 5797
 5798    #[allow(clippy::too_many_arguments)]
 5799    fn render_edit_prediction_popover(
 5800        &mut self,
 5801        text_bounds: &Bounds<Pixels>,
 5802        content_origin: gpui::Point<Pixels>,
 5803        editor_snapshot: &EditorSnapshot,
 5804        visible_row_range: Range<DisplayRow>,
 5805        scroll_top: f32,
 5806        scroll_bottom: f32,
 5807        line_layouts: &[LineWithInvisibles],
 5808        line_height: Pixels,
 5809        scroll_pixel_position: gpui::Point<Pixels>,
 5810        newest_selection_head: Option<DisplayPoint>,
 5811        editor_width: Pixels,
 5812        style: &EditorStyle,
 5813        window: &mut Window,
 5814        cx: &mut App,
 5815    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5816        let active_inline_completion = self.active_inline_completion.as_ref()?;
 5817
 5818        if self.edit_prediction_visible_in_cursor_popover(true) {
 5819            return None;
 5820        }
 5821
 5822        match &active_inline_completion.completion {
 5823            InlineCompletion::Move { target, .. } => {
 5824                let target_display_point = target.to_display_point(editor_snapshot);
 5825
 5826                if self.edit_prediction_requires_modifier() {
 5827                    if !self.edit_prediction_preview_is_active() {
 5828                        return None;
 5829                    }
 5830
 5831                    self.render_edit_prediction_modifier_jump_popover(
 5832                        text_bounds,
 5833                        content_origin,
 5834                        visible_row_range,
 5835                        line_layouts,
 5836                        line_height,
 5837                        scroll_pixel_position,
 5838                        newest_selection_head,
 5839                        target_display_point,
 5840                        window,
 5841                        cx,
 5842                    )
 5843                } else {
 5844                    self.render_edit_prediction_eager_jump_popover(
 5845                        text_bounds,
 5846                        content_origin,
 5847                        editor_snapshot,
 5848                        visible_row_range,
 5849                        scroll_top,
 5850                        scroll_bottom,
 5851                        line_height,
 5852                        scroll_pixel_position,
 5853                        target_display_point,
 5854                        editor_width,
 5855                        window,
 5856                        cx,
 5857                    )
 5858                }
 5859            }
 5860            InlineCompletion::Edit {
 5861                display_mode: EditDisplayMode::Inline,
 5862                ..
 5863            } => None,
 5864            InlineCompletion::Edit {
 5865                display_mode: EditDisplayMode::TabAccept,
 5866                edits,
 5867                ..
 5868            } => {
 5869                let range = &edits.first()?.0;
 5870                let target_display_point = range.end.to_display_point(editor_snapshot);
 5871
 5872                self.render_edit_prediction_end_of_line_popover(
 5873                    "Accept",
 5874                    editor_snapshot,
 5875                    visible_row_range,
 5876                    target_display_point,
 5877                    line_height,
 5878                    scroll_pixel_position,
 5879                    content_origin,
 5880                    editor_width,
 5881                    window,
 5882                    cx,
 5883                )
 5884            }
 5885            InlineCompletion::Edit {
 5886                edits,
 5887                edit_preview,
 5888                display_mode: EditDisplayMode::DiffPopover,
 5889                snapshot,
 5890            } => self.render_edit_prediction_diff_popover(
 5891                text_bounds,
 5892                content_origin,
 5893                editor_snapshot,
 5894                visible_row_range,
 5895                line_layouts,
 5896                line_height,
 5897                scroll_pixel_position,
 5898                newest_selection_head,
 5899                editor_width,
 5900                style,
 5901                edits,
 5902                edit_preview,
 5903                snapshot,
 5904                window,
 5905                cx,
 5906            ),
 5907        }
 5908    }
 5909
 5910    #[allow(clippy::too_many_arguments)]
 5911    fn render_edit_prediction_modifier_jump_popover(
 5912        &mut self,
 5913        text_bounds: &Bounds<Pixels>,
 5914        content_origin: gpui::Point<Pixels>,
 5915        visible_row_range: Range<DisplayRow>,
 5916        line_layouts: &[LineWithInvisibles],
 5917        line_height: Pixels,
 5918        scroll_pixel_position: gpui::Point<Pixels>,
 5919        newest_selection_head: Option<DisplayPoint>,
 5920        target_display_point: DisplayPoint,
 5921        window: &mut Window,
 5922        cx: &mut App,
 5923    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 5924        let scrolled_content_origin =
 5925            content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
 5926
 5927        const SCROLL_PADDING_Y: Pixels = px(12.);
 5928
 5929        if target_display_point.row() < visible_row_range.start {
 5930            return self.render_edit_prediction_scroll_popover(
 5931                |_| SCROLL_PADDING_Y,
 5932                IconName::ArrowUp,
 5933                visible_row_range,
 5934                line_layouts,
 5935                newest_selection_head,
 5936                scrolled_content_origin,
 5937                window,
 5938                cx,
 5939            );
 5940        } else if target_display_point.row() >= visible_row_range.end {
 5941            return self.render_edit_prediction_scroll_popover(
 5942                |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
 5943                IconName::ArrowDown,
 5944                visible_row_range,
 5945                line_layouts,
 5946                newest_selection_head,
 5947                scrolled_content_origin,
 5948                window,
 5949                cx,
 5950            );
 5951        }
 5952
 5953        const POLE_WIDTH: Pixels = px(2.);
 5954
 5955        let mut element = v_flex()
 5956            .items_end()
 5957            .child(
 5958                self.render_edit_prediction_line_popover("Jump", None, window, cx)?
 5959                    .rounded_br(px(0.))
 5960                    .rounded_tr(px(0.))
 5961                    .border_r_2(),
 5962            )
 5963            .child(
 5964                div()
 5965                    .w(POLE_WIDTH)
 5966                    .bg(Editor::edit_prediction_callout_popover_border_color(cx))
 5967                    .h(line_height),
 5968            )
 5969            .into_any();
 5970
 5971        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 5972
 5973        let line_layout =
 5974            line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
 5975        let target_column = target_display_point.column() as usize;
 5976
 5977        let target_x = line_layout.x_for_index(target_column);
 5978        let target_y =
 5979            (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
 5980
 5981        let mut origin = scrolled_content_origin + point(target_x, target_y)
 5982            - point(size.width - POLE_WIDTH, size.height - line_height);
 5983
 5984        origin.x = origin.x.max(content_origin.x);
 5985
 5986        element.prepaint_at(origin, window, cx);
 5987
 5988        Some((element, origin))
 5989    }
 5990
 5991    #[allow(clippy::too_many_arguments)]
 5992    fn render_edit_prediction_scroll_popover(
 5993        &mut self,
 5994        to_y: impl Fn(Size<Pixels>) -> Pixels,
 5995        scroll_icon: IconName,
 5996        visible_row_range: Range<DisplayRow>,
 5997        line_layouts: &[LineWithInvisibles],
 5998        newest_selection_head: Option<DisplayPoint>,
 5999        scrolled_content_origin: gpui::Point<Pixels>,
 6000        window: &mut Window,
 6001        cx: &mut App,
 6002    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6003        let mut element = self
 6004            .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
 6005            .into_any();
 6006
 6007        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6008
 6009        let cursor = newest_selection_head?;
 6010        let cursor_row_layout =
 6011            line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
 6012        let cursor_column = cursor.column() as usize;
 6013
 6014        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 6015
 6016        let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
 6017
 6018        element.prepaint_at(origin, window, cx);
 6019        Some((element, origin))
 6020    }
 6021
 6022    #[allow(clippy::too_many_arguments)]
 6023    fn render_edit_prediction_eager_jump_popover(
 6024        &mut self,
 6025        text_bounds: &Bounds<Pixels>,
 6026        content_origin: gpui::Point<Pixels>,
 6027        editor_snapshot: &EditorSnapshot,
 6028        visible_row_range: Range<DisplayRow>,
 6029        scroll_top: f32,
 6030        scroll_bottom: f32,
 6031        line_height: Pixels,
 6032        scroll_pixel_position: gpui::Point<Pixels>,
 6033        target_display_point: DisplayPoint,
 6034        editor_width: Pixels,
 6035        window: &mut Window,
 6036        cx: &mut App,
 6037    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6038        if target_display_point.row().as_f32() < scroll_top {
 6039            let mut element = self
 6040                .render_edit_prediction_line_popover(
 6041                    "Jump to Edit",
 6042                    Some(IconName::ArrowUp),
 6043                    window,
 6044                    cx,
 6045                )?
 6046                .into_any();
 6047
 6048            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6049            let offset = point(
 6050                (text_bounds.size.width - size.width) / 2.,
 6051                Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6052            );
 6053
 6054            let origin = text_bounds.origin + offset;
 6055            element.prepaint_at(origin, window, cx);
 6056            Some((element, origin))
 6057        } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
 6058            let mut element = self
 6059                .render_edit_prediction_line_popover(
 6060                    "Jump to Edit",
 6061                    Some(IconName::ArrowDown),
 6062                    window,
 6063                    cx,
 6064                )?
 6065                .into_any();
 6066
 6067            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6068            let offset = point(
 6069                (text_bounds.size.width - size.width) / 2.,
 6070                text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
 6071            );
 6072
 6073            let origin = text_bounds.origin + offset;
 6074            element.prepaint_at(origin, window, cx);
 6075            Some((element, origin))
 6076        } else {
 6077            self.render_edit_prediction_end_of_line_popover(
 6078                "Jump to Edit",
 6079                editor_snapshot,
 6080                visible_row_range,
 6081                target_display_point,
 6082                line_height,
 6083                scroll_pixel_position,
 6084                content_origin,
 6085                editor_width,
 6086                window,
 6087                cx,
 6088            )
 6089        }
 6090    }
 6091
 6092    #[allow(clippy::too_many_arguments)]
 6093    fn render_edit_prediction_end_of_line_popover(
 6094        self: &mut Editor,
 6095        label: &'static str,
 6096        editor_snapshot: &EditorSnapshot,
 6097        visible_row_range: Range<DisplayRow>,
 6098        target_display_point: DisplayPoint,
 6099        line_height: Pixels,
 6100        scroll_pixel_position: gpui::Point<Pixels>,
 6101        content_origin: gpui::Point<Pixels>,
 6102        editor_width: Pixels,
 6103        window: &mut Window,
 6104        cx: &mut App,
 6105    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6106        let target_line_end = DisplayPoint::new(
 6107            target_display_point.row(),
 6108            editor_snapshot.line_len(target_display_point.row()),
 6109        );
 6110
 6111        let mut element = self
 6112            .render_edit_prediction_line_popover(label, None, window, cx)?
 6113            .into_any();
 6114
 6115        let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6116
 6117        let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
 6118
 6119        let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
 6120        let mut origin = start_point
 6121            + line_origin
 6122            + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
 6123        origin.x = origin.x.max(content_origin.x);
 6124
 6125        let max_x = content_origin.x + editor_width - size.width;
 6126
 6127        if origin.x > max_x {
 6128            let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
 6129
 6130            let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
 6131                origin.y += offset;
 6132                IconName::ArrowUp
 6133            } else {
 6134                origin.y -= offset;
 6135                IconName::ArrowDown
 6136            };
 6137
 6138            element = self
 6139                .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
 6140                .into_any();
 6141
 6142            let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6143
 6144            origin.x = content_origin.x + editor_width - size.width - px(2.);
 6145        }
 6146
 6147        element.prepaint_at(origin, window, cx);
 6148        Some((element, origin))
 6149    }
 6150
 6151    #[allow(clippy::too_many_arguments)]
 6152    fn render_edit_prediction_diff_popover(
 6153        self: &Editor,
 6154        text_bounds: &Bounds<Pixels>,
 6155        content_origin: gpui::Point<Pixels>,
 6156        editor_snapshot: &EditorSnapshot,
 6157        visible_row_range: Range<DisplayRow>,
 6158        line_layouts: &[LineWithInvisibles],
 6159        line_height: Pixels,
 6160        scroll_pixel_position: gpui::Point<Pixels>,
 6161        newest_selection_head: Option<DisplayPoint>,
 6162        editor_width: Pixels,
 6163        style: &EditorStyle,
 6164        edits: &Vec<(Range<Anchor>, String)>,
 6165        edit_preview: &Option<language::EditPreview>,
 6166        snapshot: &language::BufferSnapshot,
 6167        window: &mut Window,
 6168        cx: &mut App,
 6169    ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
 6170        let edit_start = edits
 6171            .first()
 6172            .unwrap()
 6173            .0
 6174            .start
 6175            .to_display_point(editor_snapshot);
 6176        let edit_end = edits
 6177            .last()
 6178            .unwrap()
 6179            .0
 6180            .end
 6181            .to_display_point(editor_snapshot);
 6182
 6183        let is_visible = visible_row_range.contains(&edit_start.row())
 6184            || visible_row_range.contains(&edit_end.row());
 6185        if !is_visible {
 6186            return None;
 6187        }
 6188
 6189        let highlighted_edits =
 6190            crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
 6191
 6192        let styled_text = highlighted_edits.to_styled_text(&style.text);
 6193        let line_count = highlighted_edits.text.lines().count();
 6194
 6195        const BORDER_WIDTH: Pixels = px(1.);
 6196
 6197        let mut element = h_flex()
 6198            .items_start()
 6199            .child(
 6200                h_flex()
 6201                    .bg(cx.theme().colors().editor_background)
 6202                    .border(BORDER_WIDTH)
 6203                    .shadow_sm()
 6204                    .border_color(cx.theme().colors().border)
 6205                    .rounded_l_lg()
 6206                    .when(line_count > 1, |el| el.rounded_br_lg())
 6207                    .pr_1()
 6208                    .child(styled_text),
 6209            )
 6210            .child(
 6211                h_flex()
 6212                    .h(line_height + BORDER_WIDTH * px(2.))
 6213                    .px_1p5()
 6214                    .gap_1()
 6215                    // Workaround: For some reason, there's a gap if we don't do this
 6216                    .ml(-BORDER_WIDTH)
 6217                    .shadow(smallvec![gpui::BoxShadow {
 6218                        color: gpui::black().opacity(0.05),
 6219                        offset: point(px(1.), px(1.)),
 6220                        blur_radius: px(2.),
 6221                        spread_radius: px(0.),
 6222                    }])
 6223                    .bg(Editor::edit_prediction_line_popover_bg_color(cx))
 6224                    .border(BORDER_WIDTH)
 6225                    .border_color(cx.theme().colors().border)
 6226                    .rounded_r_lg()
 6227                    .children(self.render_edit_prediction_accept_keybind(window, cx)),
 6228            )
 6229            .into_any();
 6230
 6231        let longest_row =
 6232            editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
 6233        let longest_line_width = if visible_row_range.contains(&longest_row) {
 6234            line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
 6235        } else {
 6236            layout_line(
 6237                longest_row,
 6238                editor_snapshot,
 6239                style,
 6240                editor_width,
 6241                |_| false,
 6242                window,
 6243                cx,
 6244            )
 6245            .width
 6246        };
 6247
 6248        let viewport_bounds =
 6249            Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
 6250                right: -EditorElement::SCROLLBAR_WIDTH,
 6251                ..Default::default()
 6252            });
 6253
 6254        let x_after_longest =
 6255            text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
 6256                - scroll_pixel_position.x;
 6257
 6258        let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
 6259
 6260        // Fully visible if it can be displayed within the window (allow overlapping other
 6261        // panes). However, this is only allowed if the popover starts within text_bounds.
 6262        let can_position_to_the_right = x_after_longest < text_bounds.right()
 6263            && x_after_longest + element_bounds.width < viewport_bounds.right();
 6264
 6265        let mut origin = if can_position_to_the_right {
 6266            point(
 6267                x_after_longest,
 6268                text_bounds.origin.y + edit_start.row().as_f32() * line_height
 6269                    - scroll_pixel_position.y,
 6270            )
 6271        } else {
 6272            let cursor_row = newest_selection_head.map(|head| head.row());
 6273            let above_edit = edit_start
 6274                .row()
 6275                .0
 6276                .checked_sub(line_count as u32)
 6277                .map(DisplayRow);
 6278            let below_edit = Some(edit_end.row() + 1);
 6279            let above_cursor =
 6280                cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
 6281            let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
 6282
 6283            // Place the edit popover adjacent to the edit if there is a location
 6284            // available that is onscreen and does not obscure the cursor. Otherwise,
 6285            // place it adjacent to the cursor.
 6286            let row_target = [above_edit, below_edit, above_cursor, below_cursor]
 6287                .into_iter()
 6288                .flatten()
 6289                .find(|&start_row| {
 6290                    let end_row = start_row + line_count as u32;
 6291                    visible_row_range.contains(&start_row)
 6292                        && visible_row_range.contains(&end_row)
 6293                        && cursor_row.map_or(true, |cursor_row| {
 6294                            !((start_row..end_row).contains(&cursor_row))
 6295                        })
 6296                })?;
 6297
 6298            content_origin
 6299                + point(
 6300                    -scroll_pixel_position.x,
 6301                    row_target.as_f32() * line_height - scroll_pixel_position.y,
 6302                )
 6303        };
 6304
 6305        origin.x -= BORDER_WIDTH;
 6306
 6307        window.defer_draw(element, origin, 1);
 6308
 6309        // Do not return an element, since it will already be drawn due to defer_draw.
 6310        None
 6311    }
 6312
 6313    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 6314        px(30.)
 6315    }
 6316
 6317    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 6318        if self.read_only(cx) {
 6319            cx.theme().players().read_only()
 6320        } else {
 6321            self.style.as_ref().unwrap().local_player
 6322        }
 6323    }
 6324
 6325    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 6326        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 6327        let accept_keystroke = accept_binding.keystroke()?;
 6328
 6329        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6330
 6331        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 6332            Color::Accent
 6333        } else {
 6334            Color::Muted
 6335        };
 6336
 6337        h_flex()
 6338            .px_0p5()
 6339            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 6340            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6341            .text_size(TextSize::XSmall.rems(cx))
 6342            .child(h_flex().children(ui::render_modifiers(
 6343                &accept_keystroke.modifiers,
 6344                PlatformStyle::platform(),
 6345                Some(modifiers_color),
 6346                Some(IconSize::XSmall.rems().into()),
 6347                true,
 6348            )))
 6349            .when(is_platform_style_mac, |parent| {
 6350                parent.child(accept_keystroke.key.clone())
 6351            })
 6352            .when(!is_platform_style_mac, |parent| {
 6353                parent.child(
 6354                    Key::new(
 6355                        util::capitalize(&accept_keystroke.key),
 6356                        Some(Color::Default),
 6357                    )
 6358                    .size(Some(IconSize::XSmall.rems().into())),
 6359                )
 6360            })
 6361            .into()
 6362    }
 6363
 6364    fn render_edit_prediction_line_popover(
 6365        &self,
 6366        label: impl Into<SharedString>,
 6367        icon: Option<IconName>,
 6368        window: &mut Window,
 6369        cx: &App,
 6370    ) -> Option<Div> {
 6371        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 6372
 6373        let result = h_flex()
 6374            .py_0p5()
 6375            .pl_1()
 6376            .pr(padding_right)
 6377            .gap_1()
 6378            .rounded(px(6.))
 6379            .border_1()
 6380            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6381            .border_color(Self::edit_prediction_callout_popover_border_color(cx))
 6382            .shadow_sm()
 6383            .children(self.render_edit_prediction_accept_keybind(window, cx))
 6384            .child(Label::new(label).size(LabelSize::Small))
 6385            .when_some(icon, |element, icon| {
 6386                element.child(
 6387                    div()
 6388                        .mt(px(1.5))
 6389                        .child(Icon::new(icon).size(IconSize::Small)),
 6390                )
 6391            });
 6392
 6393        Some(result)
 6394    }
 6395
 6396    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 6397        let accent_color = cx.theme().colors().text_accent;
 6398        let editor_bg_color = cx.theme().colors().editor_background;
 6399        editor_bg_color.blend(accent_color.opacity(0.1))
 6400    }
 6401
 6402    fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
 6403        let accent_color = cx.theme().colors().text_accent;
 6404        let editor_bg_color = cx.theme().colors().editor_background;
 6405        editor_bg_color.blend(accent_color.opacity(0.6))
 6406    }
 6407
 6408    #[allow(clippy::too_many_arguments)]
 6409    fn render_edit_prediction_cursor_popover(
 6410        &self,
 6411        min_width: Pixels,
 6412        max_width: Pixels,
 6413        cursor_point: Point,
 6414        style: &EditorStyle,
 6415        accept_keystroke: Option<&gpui::Keystroke>,
 6416        _window: &Window,
 6417        cx: &mut Context<Editor>,
 6418    ) -> Option<AnyElement> {
 6419        let provider = self.edit_prediction_provider.as_ref()?;
 6420
 6421        if provider.provider.needs_terms_acceptance(cx) {
 6422            return Some(
 6423                h_flex()
 6424                    .min_w(min_width)
 6425                    .flex_1()
 6426                    .px_2()
 6427                    .py_1()
 6428                    .gap_3()
 6429                    .elevation_2(cx)
 6430                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 6431                    .id("accept-terms")
 6432                    .cursor_pointer()
 6433                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 6434                    .on_click(cx.listener(|this, _event, window, cx| {
 6435                        cx.stop_propagation();
 6436                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 6437                        window.dispatch_action(
 6438                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 6439                            cx,
 6440                        );
 6441                    }))
 6442                    .child(
 6443                        h_flex()
 6444                            .flex_1()
 6445                            .gap_2()
 6446                            .child(Icon::new(IconName::ZedPredict))
 6447                            .child(Label::new("Accept Terms of Service"))
 6448                            .child(div().w_full())
 6449                            .child(
 6450                                Icon::new(IconName::ArrowUpRight)
 6451                                    .color(Color::Muted)
 6452                                    .size(IconSize::Small),
 6453                            )
 6454                            .into_any_element(),
 6455                    )
 6456                    .into_any(),
 6457            );
 6458        }
 6459
 6460        let is_refreshing = provider.provider.is_refreshing(cx);
 6461
 6462        fn pending_completion_container() -> Div {
 6463            h_flex()
 6464                .h_full()
 6465                .flex_1()
 6466                .gap_2()
 6467                .child(Icon::new(IconName::ZedPredict))
 6468        }
 6469
 6470        let completion = match &self.active_inline_completion {
 6471            Some(completion) => match &completion.completion {
 6472                InlineCompletion::Move {
 6473                    target, snapshot, ..
 6474                } if !self.has_visible_completions_menu() => {
 6475                    use text::ToPoint as _;
 6476
 6477                    return Some(
 6478                        h_flex()
 6479                            .px_2()
 6480                            .py_1()
 6481                            .gap_2()
 6482                            .elevation_2(cx)
 6483                            .border_color(cx.theme().colors().border)
 6484                            .rounded(px(6.))
 6485                            .rounded_tl(px(0.))
 6486                            .child(
 6487                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6488                                    Icon::new(IconName::ZedPredictDown)
 6489                                } else {
 6490                                    Icon::new(IconName::ZedPredictUp)
 6491                                },
 6492                            )
 6493                            .child(Label::new("Hold").size(LabelSize::Small))
 6494                            .child(h_flex().children(ui::render_modifiers(
 6495                                &accept_keystroke?.modifiers,
 6496                                PlatformStyle::platform(),
 6497                                Some(Color::Default),
 6498                                Some(IconSize::Small.rems().into()),
 6499                                false,
 6500                            )))
 6501                            .into_any(),
 6502                    );
 6503                }
 6504                _ => self.render_edit_prediction_cursor_popover_preview(
 6505                    completion,
 6506                    cursor_point,
 6507                    style,
 6508                    cx,
 6509                )?,
 6510            },
 6511
 6512            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6513                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6514                    stale_completion,
 6515                    cursor_point,
 6516                    style,
 6517                    cx,
 6518                )?,
 6519
 6520                None => {
 6521                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6522                }
 6523            },
 6524
 6525            None => pending_completion_container().child(Label::new("No Prediction")),
 6526        };
 6527
 6528        let completion = if is_refreshing {
 6529            completion
 6530                .with_animation(
 6531                    "loading-completion",
 6532                    Animation::new(Duration::from_secs(2))
 6533                        .repeat()
 6534                        .with_easing(pulsating_between(0.4, 0.8)),
 6535                    |label, delta| label.opacity(delta),
 6536                )
 6537                .into_any_element()
 6538        } else {
 6539            completion.into_any_element()
 6540        };
 6541
 6542        let has_completion = self.active_inline_completion.is_some();
 6543
 6544        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6545        Some(
 6546            h_flex()
 6547                .min_w(min_width)
 6548                .max_w(max_width)
 6549                .flex_1()
 6550                .elevation_2(cx)
 6551                .border_color(cx.theme().colors().border)
 6552                .child(
 6553                    div()
 6554                        .flex_1()
 6555                        .py_1()
 6556                        .px_2()
 6557                        .overflow_hidden()
 6558                        .child(completion),
 6559                )
 6560                .when_some(accept_keystroke, |el, accept_keystroke| {
 6561                    if !accept_keystroke.modifiers.modified() {
 6562                        return el;
 6563                    }
 6564
 6565                    el.child(
 6566                        h_flex()
 6567                            .h_full()
 6568                            .border_l_1()
 6569                            .rounded_r_lg()
 6570                            .border_color(cx.theme().colors().border)
 6571                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6572                            .gap_1()
 6573                            .py_1()
 6574                            .px_2()
 6575                            .child(
 6576                                h_flex()
 6577                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6578                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6579                                    .child(h_flex().children(ui::render_modifiers(
 6580                                        &accept_keystroke.modifiers,
 6581                                        PlatformStyle::platform(),
 6582                                        Some(if !has_completion {
 6583                                            Color::Muted
 6584                                        } else {
 6585                                            Color::Default
 6586                                        }),
 6587                                        None,
 6588                                        false,
 6589                                    ))),
 6590                            )
 6591                            .child(Label::new("Preview").into_any_element())
 6592                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6593                    )
 6594                })
 6595                .into_any(),
 6596        )
 6597    }
 6598
 6599    fn render_edit_prediction_cursor_popover_preview(
 6600        &self,
 6601        completion: &InlineCompletionState,
 6602        cursor_point: Point,
 6603        style: &EditorStyle,
 6604        cx: &mut Context<Editor>,
 6605    ) -> Option<Div> {
 6606        use text::ToPoint as _;
 6607
 6608        fn render_relative_row_jump(
 6609            prefix: impl Into<String>,
 6610            current_row: u32,
 6611            target_row: u32,
 6612        ) -> Div {
 6613            let (row_diff, arrow) = if target_row < current_row {
 6614                (current_row - target_row, IconName::ArrowUp)
 6615            } else {
 6616                (target_row - current_row, IconName::ArrowDown)
 6617            };
 6618
 6619            h_flex()
 6620                .child(
 6621                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6622                        .color(Color::Muted)
 6623                        .size(LabelSize::Small),
 6624                )
 6625                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6626        }
 6627
 6628        match &completion.completion {
 6629            InlineCompletion::Move {
 6630                target, snapshot, ..
 6631            } => Some(
 6632                h_flex()
 6633                    .px_2()
 6634                    .gap_2()
 6635                    .flex_1()
 6636                    .child(
 6637                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6638                            Icon::new(IconName::ZedPredictDown)
 6639                        } else {
 6640                            Icon::new(IconName::ZedPredictUp)
 6641                        },
 6642                    )
 6643                    .child(Label::new("Jump to Edit")),
 6644            ),
 6645
 6646            InlineCompletion::Edit {
 6647                edits,
 6648                edit_preview,
 6649                snapshot,
 6650                display_mode: _,
 6651            } => {
 6652                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6653
 6654                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6655                    &snapshot,
 6656                    &edits,
 6657                    edit_preview.as_ref()?,
 6658                    true,
 6659                    cx,
 6660                )
 6661                .first_line_preview();
 6662
 6663                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6664                    .with_highlights(&style.text, highlighted_edits.highlights);
 6665
 6666                let preview = h_flex()
 6667                    .gap_1()
 6668                    .min_w_16()
 6669                    .child(styled_text)
 6670                    .when(has_more_lines, |parent| parent.child(""));
 6671
 6672                let left = if first_edit_row != cursor_point.row {
 6673                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6674                        .into_any_element()
 6675                } else {
 6676                    Icon::new(IconName::ZedPredict).into_any_element()
 6677                };
 6678
 6679                Some(
 6680                    h_flex()
 6681                        .h_full()
 6682                        .flex_1()
 6683                        .gap_2()
 6684                        .pr_1()
 6685                        .overflow_x_hidden()
 6686                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6687                        .child(left)
 6688                        .child(preview),
 6689                )
 6690            }
 6691        }
 6692    }
 6693
 6694    fn render_context_menu(
 6695        &self,
 6696        style: &EditorStyle,
 6697        max_height_in_lines: u32,
 6698        y_flipped: bool,
 6699        window: &mut Window,
 6700        cx: &mut Context<Editor>,
 6701    ) -> Option<AnyElement> {
 6702        let menu = self.context_menu.borrow();
 6703        let menu = menu.as_ref()?;
 6704        if !menu.visible() {
 6705            return None;
 6706        };
 6707        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6708    }
 6709
 6710    fn render_context_menu_aside(
 6711        &mut self,
 6712        max_size: Size<Pixels>,
 6713        window: &mut Window,
 6714        cx: &mut Context<Editor>,
 6715    ) -> Option<AnyElement> {
 6716        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6717            if menu.visible() {
 6718                menu.render_aside(self, max_size, window, cx)
 6719            } else {
 6720                None
 6721            }
 6722        })
 6723    }
 6724
 6725    fn hide_context_menu(
 6726        &mut self,
 6727        window: &mut Window,
 6728        cx: &mut Context<Self>,
 6729    ) -> Option<CodeContextMenu> {
 6730        cx.notify();
 6731        self.completion_tasks.clear();
 6732        let context_menu = self.context_menu.borrow_mut().take();
 6733        self.stale_inline_completion_in_menu.take();
 6734        self.update_visible_inline_completion(window, cx);
 6735        context_menu
 6736    }
 6737
 6738    fn show_snippet_choices(
 6739        &mut self,
 6740        choices: &Vec<String>,
 6741        selection: Range<Anchor>,
 6742        cx: &mut Context<Self>,
 6743    ) {
 6744        if selection.start.buffer_id.is_none() {
 6745            return;
 6746        }
 6747        let buffer_id = selection.start.buffer_id.unwrap();
 6748        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6749        let id = post_inc(&mut self.next_completion_id);
 6750
 6751        if let Some(buffer) = buffer {
 6752            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6753                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6754            ));
 6755        }
 6756    }
 6757
 6758    pub fn insert_snippet(
 6759        &mut self,
 6760        insertion_ranges: &[Range<usize>],
 6761        snippet: Snippet,
 6762        window: &mut Window,
 6763        cx: &mut Context<Self>,
 6764    ) -> Result<()> {
 6765        struct Tabstop<T> {
 6766            is_end_tabstop: bool,
 6767            ranges: Vec<Range<T>>,
 6768            choices: Option<Vec<String>>,
 6769        }
 6770
 6771        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6772            let snippet_text: Arc<str> = snippet.text.clone().into();
 6773            buffer.edit(
 6774                insertion_ranges
 6775                    .iter()
 6776                    .cloned()
 6777                    .map(|range| (range, snippet_text.clone())),
 6778                Some(AutoindentMode::EachLine),
 6779                cx,
 6780            );
 6781
 6782            let snapshot = &*buffer.read(cx);
 6783            let snippet = &snippet;
 6784            snippet
 6785                .tabstops
 6786                .iter()
 6787                .map(|tabstop| {
 6788                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6789                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6790                    });
 6791                    let mut tabstop_ranges = tabstop
 6792                        .ranges
 6793                        .iter()
 6794                        .flat_map(|tabstop_range| {
 6795                            let mut delta = 0_isize;
 6796                            insertion_ranges.iter().map(move |insertion_range| {
 6797                                let insertion_start = insertion_range.start as isize + delta;
 6798                                delta +=
 6799                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6800
 6801                                let start = ((insertion_start + tabstop_range.start) as usize)
 6802                                    .min(snapshot.len());
 6803                                let end = ((insertion_start + tabstop_range.end) as usize)
 6804                                    .min(snapshot.len());
 6805                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6806                            })
 6807                        })
 6808                        .collect::<Vec<_>>();
 6809                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6810
 6811                    Tabstop {
 6812                        is_end_tabstop,
 6813                        ranges: tabstop_ranges,
 6814                        choices: tabstop.choices.clone(),
 6815                    }
 6816                })
 6817                .collect::<Vec<_>>()
 6818        });
 6819        if let Some(tabstop) = tabstops.first() {
 6820            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6821                s.select_ranges(tabstop.ranges.iter().cloned());
 6822            });
 6823
 6824            if let Some(choices) = &tabstop.choices {
 6825                if let Some(selection) = tabstop.ranges.first() {
 6826                    self.show_snippet_choices(choices, selection.clone(), cx)
 6827                }
 6828            }
 6829
 6830            // If we're already at the last tabstop and it's at the end of the snippet,
 6831            // we're done, we don't need to keep the state around.
 6832            if !tabstop.is_end_tabstop {
 6833                let choices = tabstops
 6834                    .iter()
 6835                    .map(|tabstop| tabstop.choices.clone())
 6836                    .collect();
 6837
 6838                let ranges = tabstops
 6839                    .into_iter()
 6840                    .map(|tabstop| tabstop.ranges)
 6841                    .collect::<Vec<_>>();
 6842
 6843                self.snippet_stack.push(SnippetState {
 6844                    active_index: 0,
 6845                    ranges,
 6846                    choices,
 6847                });
 6848            }
 6849
 6850            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6851            if self.autoclose_regions.is_empty() {
 6852                let snapshot = self.buffer.read(cx).snapshot(cx);
 6853                for selection in &mut self.selections.all::<Point>(cx) {
 6854                    let selection_head = selection.head();
 6855                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6856                        continue;
 6857                    };
 6858
 6859                    let mut bracket_pair = None;
 6860                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6861                    let prev_chars = snapshot
 6862                        .reversed_chars_at(selection_head)
 6863                        .collect::<String>();
 6864                    for (pair, enabled) in scope.brackets() {
 6865                        if enabled
 6866                            && pair.close
 6867                            && prev_chars.starts_with(pair.start.as_str())
 6868                            && next_chars.starts_with(pair.end.as_str())
 6869                        {
 6870                            bracket_pair = Some(pair.clone());
 6871                            break;
 6872                        }
 6873                    }
 6874                    if let Some(pair) = bracket_pair {
 6875                        let start = snapshot.anchor_after(selection_head);
 6876                        let end = snapshot.anchor_after(selection_head);
 6877                        self.autoclose_regions.push(AutocloseRegion {
 6878                            selection_id: selection.id,
 6879                            range: start..end,
 6880                            pair,
 6881                        });
 6882                    }
 6883                }
 6884            }
 6885        }
 6886        Ok(())
 6887    }
 6888
 6889    pub fn move_to_next_snippet_tabstop(
 6890        &mut self,
 6891        window: &mut Window,
 6892        cx: &mut Context<Self>,
 6893    ) -> bool {
 6894        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6895    }
 6896
 6897    pub fn move_to_prev_snippet_tabstop(
 6898        &mut self,
 6899        window: &mut Window,
 6900        cx: &mut Context<Self>,
 6901    ) -> bool {
 6902        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6903    }
 6904
 6905    pub fn move_to_snippet_tabstop(
 6906        &mut self,
 6907        bias: Bias,
 6908        window: &mut Window,
 6909        cx: &mut Context<Self>,
 6910    ) -> bool {
 6911        if let Some(mut snippet) = self.snippet_stack.pop() {
 6912            match bias {
 6913                Bias::Left => {
 6914                    if snippet.active_index > 0 {
 6915                        snippet.active_index -= 1;
 6916                    } else {
 6917                        self.snippet_stack.push(snippet);
 6918                        return false;
 6919                    }
 6920                }
 6921                Bias::Right => {
 6922                    if snippet.active_index + 1 < snippet.ranges.len() {
 6923                        snippet.active_index += 1;
 6924                    } else {
 6925                        self.snippet_stack.push(snippet);
 6926                        return false;
 6927                    }
 6928                }
 6929            }
 6930            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6931                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6932                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6933                });
 6934
 6935                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6936                    if let Some(selection) = current_ranges.first() {
 6937                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6938                    }
 6939                }
 6940
 6941                // If snippet state is not at the last tabstop, push it back on the stack
 6942                if snippet.active_index + 1 < snippet.ranges.len() {
 6943                    self.snippet_stack.push(snippet);
 6944                }
 6945                return true;
 6946            }
 6947        }
 6948
 6949        false
 6950    }
 6951
 6952    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6953        self.transact(window, cx, |this, window, cx| {
 6954            this.select_all(&SelectAll, window, cx);
 6955            this.insert("", window, cx);
 6956        });
 6957    }
 6958
 6959    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6960        self.transact(window, cx, |this, window, cx| {
 6961            this.select_autoclose_pair(window, cx);
 6962            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6963            if !this.linked_edit_ranges.is_empty() {
 6964                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6965                let snapshot = this.buffer.read(cx).snapshot(cx);
 6966
 6967                for selection in selections.iter() {
 6968                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6969                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6970                    if selection_start.buffer_id != selection_end.buffer_id {
 6971                        continue;
 6972                    }
 6973                    if let Some(ranges) =
 6974                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6975                    {
 6976                        for (buffer, entries) in ranges {
 6977                            linked_ranges.entry(buffer).or_default().extend(entries);
 6978                        }
 6979                    }
 6980                }
 6981            }
 6982
 6983            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6984            if !this.selections.line_mode {
 6985                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6986                for selection in &mut selections {
 6987                    if selection.is_empty() {
 6988                        let old_head = selection.head();
 6989                        let mut new_head =
 6990                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6991                                .to_point(&display_map);
 6992                        if let Some((buffer, line_buffer_range)) = display_map
 6993                            .buffer_snapshot
 6994                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6995                        {
 6996                            let indent_size =
 6997                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6998                            let indent_len = match indent_size.kind {
 6999                                IndentKind::Space => {
 7000                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 7001                                }
 7002                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 7003                            };
 7004                            if old_head.column <= indent_size.len && old_head.column > 0 {
 7005                                let indent_len = indent_len.get();
 7006                                new_head = cmp::min(
 7007                                    new_head,
 7008                                    MultiBufferPoint::new(
 7009                                        old_head.row,
 7010                                        ((old_head.column - 1) / indent_len) * indent_len,
 7011                                    ),
 7012                                );
 7013                            }
 7014                        }
 7015
 7016                        selection.set_head(new_head, SelectionGoal::None);
 7017                    }
 7018                }
 7019            }
 7020
 7021            this.signature_help_state.set_backspace_pressed(true);
 7022            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7023                s.select(selections)
 7024            });
 7025            this.insert("", window, cx);
 7026            let empty_str: Arc<str> = Arc::from("");
 7027            for (buffer, edits) in linked_ranges {
 7028                let snapshot = buffer.read(cx).snapshot();
 7029                use text::ToPoint as TP;
 7030
 7031                let edits = edits
 7032                    .into_iter()
 7033                    .map(|range| {
 7034                        let end_point = TP::to_point(&range.end, &snapshot);
 7035                        let mut start_point = TP::to_point(&range.start, &snapshot);
 7036
 7037                        if end_point == start_point {
 7038                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 7039                                .saturating_sub(1);
 7040                            start_point =
 7041                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 7042                        };
 7043
 7044                        (start_point..end_point, empty_str.clone())
 7045                    })
 7046                    .sorted_by_key(|(range, _)| range.start)
 7047                    .collect::<Vec<_>>();
 7048                buffer.update(cx, |this, cx| {
 7049                    this.edit(edits, None, cx);
 7050                })
 7051            }
 7052            this.refresh_inline_completion(true, false, window, cx);
 7053            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 7054        });
 7055    }
 7056
 7057    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 7058        self.transact(window, cx, |this, window, cx| {
 7059            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7060                let line_mode = s.line_mode;
 7061                s.move_with(|map, selection| {
 7062                    if selection.is_empty() && !line_mode {
 7063                        let cursor = movement::right(map, selection.head());
 7064                        selection.end = cursor;
 7065                        selection.reversed = true;
 7066                        selection.goal = SelectionGoal::None;
 7067                    }
 7068                })
 7069            });
 7070            this.insert("", window, cx);
 7071            this.refresh_inline_completion(true, false, window, cx);
 7072        });
 7073    }
 7074
 7075    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 7076        if self.move_to_prev_snippet_tabstop(window, cx) {
 7077            return;
 7078        }
 7079
 7080        self.outdent(&Outdent, window, cx);
 7081    }
 7082
 7083    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 7084        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 7085            return;
 7086        }
 7087
 7088        let mut selections = self.selections.all_adjusted(cx);
 7089        let buffer = self.buffer.read(cx);
 7090        let snapshot = buffer.snapshot(cx);
 7091        let rows_iter = selections.iter().map(|s| s.head().row);
 7092        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 7093
 7094        let mut edits = Vec::new();
 7095        let mut prev_edited_row = 0;
 7096        let mut row_delta = 0;
 7097        for selection in &mut selections {
 7098            if selection.start.row != prev_edited_row {
 7099                row_delta = 0;
 7100            }
 7101            prev_edited_row = selection.end.row;
 7102
 7103            // If the selection is non-empty, then increase the indentation of the selected lines.
 7104            if !selection.is_empty() {
 7105                row_delta =
 7106                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7107                continue;
 7108            }
 7109
 7110            // If the selection is empty and the cursor is in the leading whitespace before the
 7111            // suggested indentation, then auto-indent the line.
 7112            let cursor = selection.head();
 7113            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 7114            if let Some(suggested_indent) =
 7115                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 7116            {
 7117                if cursor.column < suggested_indent.len
 7118                    && cursor.column <= current_indent.len
 7119                    && current_indent.len <= suggested_indent.len
 7120                {
 7121                    selection.start = Point::new(cursor.row, suggested_indent.len);
 7122                    selection.end = selection.start;
 7123                    if row_delta == 0 {
 7124                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 7125                            cursor.row,
 7126                            current_indent,
 7127                            suggested_indent,
 7128                        ));
 7129                        row_delta = suggested_indent.len - current_indent.len;
 7130                    }
 7131                    continue;
 7132                }
 7133            }
 7134
 7135            // Otherwise, insert a hard or soft tab.
 7136            let settings = buffer.settings_at(cursor, cx);
 7137            let tab_size = if settings.hard_tabs {
 7138                IndentSize::tab()
 7139            } else {
 7140                let tab_size = settings.tab_size.get();
 7141                let char_column = snapshot
 7142                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 7143                    .flat_map(str::chars)
 7144                    .count()
 7145                    + row_delta as usize;
 7146                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 7147                IndentSize::spaces(chars_to_next_tab_stop)
 7148            };
 7149            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 7150            selection.end = selection.start;
 7151            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 7152            row_delta += tab_size.len;
 7153        }
 7154
 7155        self.transact(window, cx, |this, window, cx| {
 7156            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7157            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7158                s.select(selections)
 7159            });
 7160            this.refresh_inline_completion(true, false, window, cx);
 7161        });
 7162    }
 7163
 7164    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 7165        if self.read_only(cx) {
 7166            return;
 7167        }
 7168        let mut selections = self.selections.all::<Point>(cx);
 7169        let mut prev_edited_row = 0;
 7170        let mut row_delta = 0;
 7171        let mut edits = Vec::new();
 7172        let buffer = self.buffer.read(cx);
 7173        let snapshot = buffer.snapshot(cx);
 7174        for selection in &mut selections {
 7175            if selection.start.row != prev_edited_row {
 7176                row_delta = 0;
 7177            }
 7178            prev_edited_row = selection.end.row;
 7179
 7180            row_delta =
 7181                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 7182        }
 7183
 7184        self.transact(window, cx, |this, window, cx| {
 7185            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 7186            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7187                s.select(selections)
 7188            });
 7189        });
 7190    }
 7191
 7192    fn indent_selection(
 7193        buffer: &MultiBuffer,
 7194        snapshot: &MultiBufferSnapshot,
 7195        selection: &mut Selection<Point>,
 7196        edits: &mut Vec<(Range<Point>, String)>,
 7197        delta_for_start_row: u32,
 7198        cx: &App,
 7199    ) -> u32 {
 7200        let settings = buffer.settings_at(selection.start, cx);
 7201        let tab_size = settings.tab_size.get();
 7202        let indent_kind = if settings.hard_tabs {
 7203            IndentKind::Tab
 7204        } else {
 7205            IndentKind::Space
 7206        };
 7207        let mut start_row = selection.start.row;
 7208        let mut end_row = selection.end.row + 1;
 7209
 7210        // If a selection ends at the beginning of a line, don't indent
 7211        // that last line.
 7212        if selection.end.column == 0 && selection.end.row > selection.start.row {
 7213            end_row -= 1;
 7214        }
 7215
 7216        // Avoid re-indenting a row that has already been indented by a
 7217        // previous selection, but still update this selection's column
 7218        // to reflect that indentation.
 7219        if delta_for_start_row > 0 {
 7220            start_row += 1;
 7221            selection.start.column += delta_for_start_row;
 7222            if selection.end.row == selection.start.row {
 7223                selection.end.column += delta_for_start_row;
 7224            }
 7225        }
 7226
 7227        let mut delta_for_end_row = 0;
 7228        let has_multiple_rows = start_row + 1 != end_row;
 7229        for row in start_row..end_row {
 7230            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 7231            let indent_delta = match (current_indent.kind, indent_kind) {
 7232                (IndentKind::Space, IndentKind::Space) => {
 7233                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 7234                    IndentSize::spaces(columns_to_next_tab_stop)
 7235                }
 7236                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 7237                (_, IndentKind::Tab) => IndentSize::tab(),
 7238            };
 7239
 7240            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 7241                0
 7242            } else {
 7243                selection.start.column
 7244            };
 7245            let row_start = Point::new(row, start);
 7246            edits.push((
 7247                row_start..row_start,
 7248                indent_delta.chars().collect::<String>(),
 7249            ));
 7250
 7251            // Update this selection's endpoints to reflect the indentation.
 7252            if row == selection.start.row {
 7253                selection.start.column += indent_delta.len;
 7254            }
 7255            if row == selection.end.row {
 7256                selection.end.column += indent_delta.len;
 7257                delta_for_end_row = indent_delta.len;
 7258            }
 7259        }
 7260
 7261        if selection.start.row == selection.end.row {
 7262            delta_for_start_row + delta_for_end_row
 7263        } else {
 7264            delta_for_end_row
 7265        }
 7266    }
 7267
 7268    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 7269        if self.read_only(cx) {
 7270            return;
 7271        }
 7272        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7273        let selections = self.selections.all::<Point>(cx);
 7274        let mut deletion_ranges = Vec::new();
 7275        let mut last_outdent = None;
 7276        {
 7277            let buffer = self.buffer.read(cx);
 7278            let snapshot = buffer.snapshot(cx);
 7279            for selection in &selections {
 7280                let settings = buffer.settings_at(selection.start, cx);
 7281                let tab_size = settings.tab_size.get();
 7282                let mut rows = selection.spanned_rows(false, &display_map);
 7283
 7284                // Avoid re-outdenting a row that has already been outdented by a
 7285                // previous selection.
 7286                if let Some(last_row) = last_outdent {
 7287                    if last_row == rows.start {
 7288                        rows.start = rows.start.next_row();
 7289                    }
 7290                }
 7291                let has_multiple_rows = rows.len() > 1;
 7292                for row in rows.iter_rows() {
 7293                    let indent_size = snapshot.indent_size_for_line(row);
 7294                    if indent_size.len > 0 {
 7295                        let deletion_len = match indent_size.kind {
 7296                            IndentKind::Space => {
 7297                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 7298                                if columns_to_prev_tab_stop == 0 {
 7299                                    tab_size
 7300                                } else {
 7301                                    columns_to_prev_tab_stop
 7302                                }
 7303                            }
 7304                            IndentKind::Tab => 1,
 7305                        };
 7306                        let start = if has_multiple_rows
 7307                            || deletion_len > selection.start.column
 7308                            || indent_size.len < selection.start.column
 7309                        {
 7310                            0
 7311                        } else {
 7312                            selection.start.column - deletion_len
 7313                        };
 7314                        deletion_ranges.push(
 7315                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 7316                        );
 7317                        last_outdent = Some(row);
 7318                    }
 7319                }
 7320            }
 7321        }
 7322
 7323        self.transact(window, cx, |this, window, cx| {
 7324            this.buffer.update(cx, |buffer, cx| {
 7325                let empty_str: Arc<str> = Arc::default();
 7326                buffer.edit(
 7327                    deletion_ranges
 7328                        .into_iter()
 7329                        .map(|range| (range, empty_str.clone())),
 7330                    None,
 7331                    cx,
 7332                );
 7333            });
 7334            let selections = this.selections.all::<usize>(cx);
 7335            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7336                s.select(selections)
 7337            });
 7338        });
 7339    }
 7340
 7341    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 7342        if self.read_only(cx) {
 7343            return;
 7344        }
 7345        let selections = self
 7346            .selections
 7347            .all::<usize>(cx)
 7348            .into_iter()
 7349            .map(|s| s.range());
 7350
 7351        self.transact(window, cx, |this, window, cx| {
 7352            this.buffer.update(cx, |buffer, cx| {
 7353                buffer.autoindent_ranges(selections, cx);
 7354            });
 7355            let selections = this.selections.all::<usize>(cx);
 7356            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7357                s.select(selections)
 7358            });
 7359        });
 7360    }
 7361
 7362    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 7363        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7364        let selections = self.selections.all::<Point>(cx);
 7365
 7366        let mut new_cursors = Vec::new();
 7367        let mut edit_ranges = Vec::new();
 7368        let mut selections = selections.iter().peekable();
 7369        while let Some(selection) = selections.next() {
 7370            let mut rows = selection.spanned_rows(false, &display_map);
 7371            let goal_display_column = selection.head().to_display_point(&display_map).column();
 7372
 7373            // Accumulate contiguous regions of rows that we want to delete.
 7374            while let Some(next_selection) = selections.peek() {
 7375                let next_rows = next_selection.spanned_rows(false, &display_map);
 7376                if next_rows.start <= rows.end {
 7377                    rows.end = next_rows.end;
 7378                    selections.next().unwrap();
 7379                } else {
 7380                    break;
 7381                }
 7382            }
 7383
 7384            let buffer = &display_map.buffer_snapshot;
 7385            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 7386            let edit_end;
 7387            let cursor_buffer_row;
 7388            if buffer.max_point().row >= rows.end.0 {
 7389                // If there's a line after the range, delete the \n from the end of the row range
 7390                // and position the cursor on the next line.
 7391                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 7392                cursor_buffer_row = rows.end;
 7393            } else {
 7394                // If there isn't a line after the range, delete the \n from the line before the
 7395                // start of the row range and position the cursor there.
 7396                edit_start = edit_start.saturating_sub(1);
 7397                edit_end = buffer.len();
 7398                cursor_buffer_row = rows.start.previous_row();
 7399            }
 7400
 7401            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 7402            *cursor.column_mut() =
 7403                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 7404
 7405            new_cursors.push((
 7406                selection.id,
 7407                buffer.anchor_after(cursor.to_point(&display_map)),
 7408            ));
 7409            edit_ranges.push(edit_start..edit_end);
 7410        }
 7411
 7412        self.transact(window, cx, |this, window, cx| {
 7413            let buffer = this.buffer.update(cx, |buffer, cx| {
 7414                let empty_str: Arc<str> = Arc::default();
 7415                buffer.edit(
 7416                    edit_ranges
 7417                        .into_iter()
 7418                        .map(|range| (range, empty_str.clone())),
 7419                    None,
 7420                    cx,
 7421                );
 7422                buffer.snapshot(cx)
 7423            });
 7424            let new_selections = new_cursors
 7425                .into_iter()
 7426                .map(|(id, cursor)| {
 7427                    let cursor = cursor.to_point(&buffer);
 7428                    Selection {
 7429                        id,
 7430                        start: cursor,
 7431                        end: cursor,
 7432                        reversed: false,
 7433                        goal: SelectionGoal::None,
 7434                    }
 7435                })
 7436                .collect();
 7437
 7438            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7439                s.select(new_selections);
 7440            });
 7441        });
 7442    }
 7443
 7444    pub fn join_lines_impl(
 7445        &mut self,
 7446        insert_whitespace: bool,
 7447        window: &mut Window,
 7448        cx: &mut Context<Self>,
 7449    ) {
 7450        if self.read_only(cx) {
 7451            return;
 7452        }
 7453        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 7454        for selection in self.selections.all::<Point>(cx) {
 7455            let start = MultiBufferRow(selection.start.row);
 7456            // Treat single line selections as if they include the next line. Otherwise this action
 7457            // would do nothing for single line selections individual cursors.
 7458            let end = if selection.start.row == selection.end.row {
 7459                MultiBufferRow(selection.start.row + 1)
 7460            } else {
 7461                MultiBufferRow(selection.end.row)
 7462            };
 7463
 7464            if let Some(last_row_range) = row_ranges.last_mut() {
 7465                if start <= last_row_range.end {
 7466                    last_row_range.end = end;
 7467                    continue;
 7468                }
 7469            }
 7470            row_ranges.push(start..end);
 7471        }
 7472
 7473        let snapshot = self.buffer.read(cx).snapshot(cx);
 7474        let mut cursor_positions = Vec::new();
 7475        for row_range in &row_ranges {
 7476            let anchor = snapshot.anchor_before(Point::new(
 7477                row_range.end.previous_row().0,
 7478                snapshot.line_len(row_range.end.previous_row()),
 7479            ));
 7480            cursor_positions.push(anchor..anchor);
 7481        }
 7482
 7483        self.transact(window, cx, |this, window, cx| {
 7484            for row_range in row_ranges.into_iter().rev() {
 7485                for row in row_range.iter_rows().rev() {
 7486                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7487                    let next_line_row = row.next_row();
 7488                    let indent = snapshot.indent_size_for_line(next_line_row);
 7489                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7490
 7491                    let replace =
 7492                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7493                            " "
 7494                        } else {
 7495                            ""
 7496                        };
 7497
 7498                    this.buffer.update(cx, |buffer, cx| {
 7499                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7500                    });
 7501                }
 7502            }
 7503
 7504            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7505                s.select_anchor_ranges(cursor_positions)
 7506            });
 7507        });
 7508    }
 7509
 7510    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7511        self.join_lines_impl(true, window, cx);
 7512    }
 7513
 7514    pub fn sort_lines_case_sensitive(
 7515        &mut self,
 7516        _: &SortLinesCaseSensitive,
 7517        window: &mut Window,
 7518        cx: &mut Context<Self>,
 7519    ) {
 7520        self.manipulate_lines(window, cx, |lines| lines.sort())
 7521    }
 7522
 7523    pub fn sort_lines_case_insensitive(
 7524        &mut self,
 7525        _: &SortLinesCaseInsensitive,
 7526        window: &mut Window,
 7527        cx: &mut Context<Self>,
 7528    ) {
 7529        self.manipulate_lines(window, cx, |lines| {
 7530            lines.sort_by_key(|line| line.to_lowercase())
 7531        })
 7532    }
 7533
 7534    pub fn unique_lines_case_insensitive(
 7535        &mut self,
 7536        _: &UniqueLinesCaseInsensitive,
 7537        window: &mut Window,
 7538        cx: &mut Context<Self>,
 7539    ) {
 7540        self.manipulate_lines(window, cx, |lines| {
 7541            let mut seen = HashSet::default();
 7542            lines.retain(|line| seen.insert(line.to_lowercase()));
 7543        })
 7544    }
 7545
 7546    pub fn unique_lines_case_sensitive(
 7547        &mut self,
 7548        _: &UniqueLinesCaseSensitive,
 7549        window: &mut Window,
 7550        cx: &mut Context<Self>,
 7551    ) {
 7552        self.manipulate_lines(window, cx, |lines| {
 7553            let mut seen = HashSet::default();
 7554            lines.retain(|line| seen.insert(*line));
 7555        })
 7556    }
 7557
 7558    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7559        let Some(project) = self.project.clone() else {
 7560            return;
 7561        };
 7562        self.reload(project, window, cx)
 7563            .detach_and_notify_err(window, cx);
 7564    }
 7565
 7566    pub fn restore_file(
 7567        &mut self,
 7568        _: &::git::RestoreFile,
 7569        window: &mut Window,
 7570        cx: &mut Context<Self>,
 7571    ) {
 7572        let mut buffer_ids = HashSet::default();
 7573        let snapshot = self.buffer().read(cx).snapshot(cx);
 7574        for selection in self.selections.all::<usize>(cx) {
 7575            buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
 7576        }
 7577
 7578        let buffer = self.buffer().read(cx);
 7579        let ranges = buffer_ids
 7580            .into_iter()
 7581            .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
 7582            .collect::<Vec<_>>();
 7583
 7584        self.restore_hunks_in_ranges(ranges, window, cx);
 7585    }
 7586
 7587    pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
 7588        let selections = self
 7589            .selections
 7590            .all(cx)
 7591            .into_iter()
 7592            .map(|s| s.range())
 7593            .collect();
 7594        self.restore_hunks_in_ranges(selections, window, cx);
 7595    }
 7596
 7597    fn restore_hunks_in_ranges(
 7598        &mut self,
 7599        ranges: Vec<Range<Point>>,
 7600        window: &mut Window,
 7601        cx: &mut Context<Editor>,
 7602    ) {
 7603        let mut revert_changes = HashMap::default();
 7604        let snapshot = self.buffer.read(cx).snapshot(cx);
 7605        let Some(project) = &self.project else {
 7606            return;
 7607        };
 7608
 7609        let chunk_by = self
 7610            .snapshot(window, cx)
 7611            .hunks_for_ranges(ranges.into_iter())
 7612            .into_iter()
 7613            .chunk_by(|hunk| hunk.buffer_id);
 7614        for (buffer_id, hunks) in &chunk_by {
 7615            let hunks = hunks.collect::<Vec<_>>();
 7616            for hunk in &hunks {
 7617                self.prepare_restore_change(&mut revert_changes, hunk, cx);
 7618            }
 7619            Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
 7620        }
 7621        drop(chunk_by);
 7622        if !revert_changes.is_empty() {
 7623            self.transact(window, cx, |editor, window, cx| {
 7624                editor.revert(revert_changes, window, cx);
 7625            });
 7626        }
 7627    }
 7628
 7629    pub fn open_active_item_in_terminal(
 7630        &mut self,
 7631        _: &OpenInTerminal,
 7632        window: &mut Window,
 7633        cx: &mut Context<Self>,
 7634    ) {
 7635        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7636            let project_path = buffer.read(cx).project_path(cx)?;
 7637            let project = self.project.as_ref()?.read(cx);
 7638            let entry = project.entry_for_path(&project_path, cx)?;
 7639            let parent = match &entry.canonical_path {
 7640                Some(canonical_path) => canonical_path.to_path_buf(),
 7641                None => project.absolute_path(&project_path, cx)?,
 7642            }
 7643            .parent()?
 7644            .to_path_buf();
 7645            Some(parent)
 7646        }) {
 7647            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7648        }
 7649    }
 7650
 7651    pub fn prepare_restore_change(
 7652        &self,
 7653        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7654        hunk: &MultiBufferDiffHunk,
 7655        cx: &mut App,
 7656    ) -> Option<()> {
 7657        let buffer = self.buffer.read(cx);
 7658        let diff = buffer.diff_for(hunk.buffer_id)?;
 7659        let buffer = buffer.buffer(hunk.buffer_id)?;
 7660        let buffer = buffer.read(cx);
 7661        let original_text = diff
 7662            .read(cx)
 7663            .base_text()
 7664            .as_ref()?
 7665            .as_rope()
 7666            .slice(hunk.diff_base_byte_range.clone());
 7667        let buffer_snapshot = buffer.snapshot();
 7668        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7669        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7670            probe
 7671                .0
 7672                .start
 7673                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7674                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7675        }) {
 7676            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7677            Some(())
 7678        } else {
 7679            None
 7680        }
 7681    }
 7682
 7683    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7684        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7685    }
 7686
 7687    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7688        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7689    }
 7690
 7691    fn manipulate_lines<Fn>(
 7692        &mut self,
 7693        window: &mut Window,
 7694        cx: &mut Context<Self>,
 7695        mut callback: Fn,
 7696    ) where
 7697        Fn: FnMut(&mut Vec<&str>),
 7698    {
 7699        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7700        let buffer = self.buffer.read(cx).snapshot(cx);
 7701
 7702        let mut edits = Vec::new();
 7703
 7704        let selections = self.selections.all::<Point>(cx);
 7705        let mut selections = selections.iter().peekable();
 7706        let mut contiguous_row_selections = Vec::new();
 7707        let mut new_selections = Vec::new();
 7708        let mut added_lines = 0;
 7709        let mut removed_lines = 0;
 7710
 7711        while let Some(selection) = selections.next() {
 7712            let (start_row, end_row) = consume_contiguous_rows(
 7713                &mut contiguous_row_selections,
 7714                selection,
 7715                &display_map,
 7716                &mut selections,
 7717            );
 7718
 7719            let start_point = Point::new(start_row.0, 0);
 7720            let end_point = Point::new(
 7721                end_row.previous_row().0,
 7722                buffer.line_len(end_row.previous_row()),
 7723            );
 7724            let text = buffer
 7725                .text_for_range(start_point..end_point)
 7726                .collect::<String>();
 7727
 7728            let mut lines = text.split('\n').collect_vec();
 7729
 7730            let lines_before = lines.len();
 7731            callback(&mut lines);
 7732            let lines_after = lines.len();
 7733
 7734            edits.push((start_point..end_point, lines.join("\n")));
 7735
 7736            // Selections must change based on added and removed line count
 7737            let start_row =
 7738                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7739            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7740            new_selections.push(Selection {
 7741                id: selection.id,
 7742                start: start_row,
 7743                end: end_row,
 7744                goal: SelectionGoal::None,
 7745                reversed: selection.reversed,
 7746            });
 7747
 7748            if lines_after > lines_before {
 7749                added_lines += lines_after - lines_before;
 7750            } else if lines_before > lines_after {
 7751                removed_lines += lines_before - lines_after;
 7752            }
 7753        }
 7754
 7755        self.transact(window, cx, |this, window, cx| {
 7756            let buffer = this.buffer.update(cx, |buffer, cx| {
 7757                buffer.edit(edits, None, cx);
 7758                buffer.snapshot(cx)
 7759            });
 7760
 7761            // Recalculate offsets on newly edited buffer
 7762            let new_selections = new_selections
 7763                .iter()
 7764                .map(|s| {
 7765                    let start_point = Point::new(s.start.0, 0);
 7766                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7767                    Selection {
 7768                        id: s.id,
 7769                        start: buffer.point_to_offset(start_point),
 7770                        end: buffer.point_to_offset(end_point),
 7771                        goal: s.goal,
 7772                        reversed: s.reversed,
 7773                    }
 7774                })
 7775                .collect();
 7776
 7777            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7778                s.select(new_selections);
 7779            });
 7780
 7781            this.request_autoscroll(Autoscroll::fit(), cx);
 7782        });
 7783    }
 7784
 7785    pub fn convert_to_upper_case(
 7786        &mut self,
 7787        _: &ConvertToUpperCase,
 7788        window: &mut Window,
 7789        cx: &mut Context<Self>,
 7790    ) {
 7791        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7792    }
 7793
 7794    pub fn convert_to_lower_case(
 7795        &mut self,
 7796        _: &ConvertToLowerCase,
 7797        window: &mut Window,
 7798        cx: &mut Context<Self>,
 7799    ) {
 7800        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7801    }
 7802
 7803    pub fn convert_to_title_case(
 7804        &mut self,
 7805        _: &ConvertToTitleCase,
 7806        window: &mut Window,
 7807        cx: &mut Context<Self>,
 7808    ) {
 7809        self.manipulate_text(window, cx, |text| {
 7810            text.split('\n')
 7811                .map(|line| line.to_case(Case::Title))
 7812                .join("\n")
 7813        })
 7814    }
 7815
 7816    pub fn convert_to_snake_case(
 7817        &mut self,
 7818        _: &ConvertToSnakeCase,
 7819        window: &mut Window,
 7820        cx: &mut Context<Self>,
 7821    ) {
 7822        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7823    }
 7824
 7825    pub fn convert_to_kebab_case(
 7826        &mut self,
 7827        _: &ConvertToKebabCase,
 7828        window: &mut Window,
 7829        cx: &mut Context<Self>,
 7830    ) {
 7831        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7832    }
 7833
 7834    pub fn convert_to_upper_camel_case(
 7835        &mut self,
 7836        _: &ConvertToUpperCamelCase,
 7837        window: &mut Window,
 7838        cx: &mut Context<Self>,
 7839    ) {
 7840        self.manipulate_text(window, cx, |text| {
 7841            text.split('\n')
 7842                .map(|line| line.to_case(Case::UpperCamel))
 7843                .join("\n")
 7844        })
 7845    }
 7846
 7847    pub fn convert_to_lower_camel_case(
 7848        &mut self,
 7849        _: &ConvertToLowerCamelCase,
 7850        window: &mut Window,
 7851        cx: &mut Context<Self>,
 7852    ) {
 7853        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7854    }
 7855
 7856    pub fn convert_to_opposite_case(
 7857        &mut self,
 7858        _: &ConvertToOppositeCase,
 7859        window: &mut Window,
 7860        cx: &mut Context<Self>,
 7861    ) {
 7862        self.manipulate_text(window, cx, |text| {
 7863            text.chars()
 7864                .fold(String::with_capacity(text.len()), |mut t, c| {
 7865                    if c.is_uppercase() {
 7866                        t.extend(c.to_lowercase());
 7867                    } else {
 7868                        t.extend(c.to_uppercase());
 7869                    }
 7870                    t
 7871                })
 7872        })
 7873    }
 7874
 7875    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7876    where
 7877        Fn: FnMut(&str) -> String,
 7878    {
 7879        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7880        let buffer = self.buffer.read(cx).snapshot(cx);
 7881
 7882        let mut new_selections = Vec::new();
 7883        let mut edits = Vec::new();
 7884        let mut selection_adjustment = 0i32;
 7885
 7886        for selection in self.selections.all::<usize>(cx) {
 7887            let selection_is_empty = selection.is_empty();
 7888
 7889            let (start, end) = if selection_is_empty {
 7890                let word_range = movement::surrounding_word(
 7891                    &display_map,
 7892                    selection.start.to_display_point(&display_map),
 7893                );
 7894                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7895                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7896                (start, end)
 7897            } else {
 7898                (selection.start, selection.end)
 7899            };
 7900
 7901            let text = buffer.text_for_range(start..end).collect::<String>();
 7902            let old_length = text.len() as i32;
 7903            let text = callback(&text);
 7904
 7905            new_selections.push(Selection {
 7906                start: (start as i32 - selection_adjustment) as usize,
 7907                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7908                goal: SelectionGoal::None,
 7909                ..selection
 7910            });
 7911
 7912            selection_adjustment += old_length - text.len() as i32;
 7913
 7914            edits.push((start..end, text));
 7915        }
 7916
 7917        self.transact(window, cx, |this, window, cx| {
 7918            this.buffer.update(cx, |buffer, cx| {
 7919                buffer.edit(edits, None, cx);
 7920            });
 7921
 7922            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7923                s.select(new_selections);
 7924            });
 7925
 7926            this.request_autoscroll(Autoscroll::fit(), cx);
 7927        });
 7928    }
 7929
 7930    pub fn duplicate(
 7931        &mut self,
 7932        upwards: bool,
 7933        whole_lines: bool,
 7934        window: &mut Window,
 7935        cx: &mut Context<Self>,
 7936    ) {
 7937        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7938        let buffer = &display_map.buffer_snapshot;
 7939        let selections = self.selections.all::<Point>(cx);
 7940
 7941        let mut edits = Vec::new();
 7942        let mut selections_iter = selections.iter().peekable();
 7943        while let Some(selection) = selections_iter.next() {
 7944            let mut rows = selection.spanned_rows(false, &display_map);
 7945            // duplicate line-wise
 7946            if whole_lines || selection.start == selection.end {
 7947                // Avoid duplicating the same lines twice.
 7948                while let Some(next_selection) = selections_iter.peek() {
 7949                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7950                    if next_rows.start < rows.end {
 7951                        rows.end = next_rows.end;
 7952                        selections_iter.next().unwrap();
 7953                    } else {
 7954                        break;
 7955                    }
 7956                }
 7957
 7958                // Copy the text from the selected row region and splice it either at the start
 7959                // or end of the region.
 7960                let start = Point::new(rows.start.0, 0);
 7961                let end = Point::new(
 7962                    rows.end.previous_row().0,
 7963                    buffer.line_len(rows.end.previous_row()),
 7964                );
 7965                let text = buffer
 7966                    .text_for_range(start..end)
 7967                    .chain(Some("\n"))
 7968                    .collect::<String>();
 7969                let insert_location = if upwards {
 7970                    Point::new(rows.end.0, 0)
 7971                } else {
 7972                    start
 7973                };
 7974                edits.push((insert_location..insert_location, text));
 7975            } else {
 7976                // duplicate character-wise
 7977                let start = selection.start;
 7978                let end = selection.end;
 7979                let text = buffer.text_for_range(start..end).collect::<String>();
 7980                edits.push((selection.end..selection.end, text));
 7981            }
 7982        }
 7983
 7984        self.transact(window, cx, |this, _, cx| {
 7985            this.buffer.update(cx, |buffer, cx| {
 7986                buffer.edit(edits, None, cx);
 7987            });
 7988
 7989            this.request_autoscroll(Autoscroll::fit(), cx);
 7990        });
 7991    }
 7992
 7993    pub fn duplicate_line_up(
 7994        &mut self,
 7995        _: &DuplicateLineUp,
 7996        window: &mut Window,
 7997        cx: &mut Context<Self>,
 7998    ) {
 7999        self.duplicate(true, true, window, cx);
 8000    }
 8001
 8002    pub fn duplicate_line_down(
 8003        &mut self,
 8004        _: &DuplicateLineDown,
 8005        window: &mut Window,
 8006        cx: &mut Context<Self>,
 8007    ) {
 8008        self.duplicate(false, true, window, cx);
 8009    }
 8010
 8011    pub fn duplicate_selection(
 8012        &mut self,
 8013        _: &DuplicateSelection,
 8014        window: &mut Window,
 8015        cx: &mut Context<Self>,
 8016    ) {
 8017        self.duplicate(false, false, window, cx);
 8018    }
 8019
 8020    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 8021        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8022        let buffer = self.buffer.read(cx).snapshot(cx);
 8023
 8024        let mut edits = Vec::new();
 8025        let mut unfold_ranges = Vec::new();
 8026        let mut refold_creases = Vec::new();
 8027
 8028        let selections = self.selections.all::<Point>(cx);
 8029        let mut selections = selections.iter().peekable();
 8030        let mut contiguous_row_selections = Vec::new();
 8031        let mut new_selections = Vec::new();
 8032
 8033        while let Some(selection) = selections.next() {
 8034            // Find all the selections that span a contiguous row range
 8035            let (start_row, end_row) = consume_contiguous_rows(
 8036                &mut contiguous_row_selections,
 8037                selection,
 8038                &display_map,
 8039                &mut selections,
 8040            );
 8041
 8042            // Move the text spanned by the row range to be before the line preceding the row range
 8043            if start_row.0 > 0 {
 8044                let range_to_move = Point::new(
 8045                    start_row.previous_row().0,
 8046                    buffer.line_len(start_row.previous_row()),
 8047                )
 8048                    ..Point::new(
 8049                        end_row.previous_row().0,
 8050                        buffer.line_len(end_row.previous_row()),
 8051                    );
 8052                let insertion_point = display_map
 8053                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 8054                    .0;
 8055
 8056                // Don't move lines across excerpts
 8057                if buffer
 8058                    .excerpt_containing(insertion_point..range_to_move.end)
 8059                    .is_some()
 8060                {
 8061                    let text = buffer
 8062                        .text_for_range(range_to_move.clone())
 8063                        .flat_map(|s| s.chars())
 8064                        .skip(1)
 8065                        .chain(['\n'])
 8066                        .collect::<String>();
 8067
 8068                    edits.push((
 8069                        buffer.anchor_after(range_to_move.start)
 8070                            ..buffer.anchor_before(range_to_move.end),
 8071                        String::new(),
 8072                    ));
 8073                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8074                    edits.push((insertion_anchor..insertion_anchor, text));
 8075
 8076                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 8077
 8078                    // Move selections up
 8079                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8080                        |mut selection| {
 8081                            selection.start.row -= row_delta;
 8082                            selection.end.row -= row_delta;
 8083                            selection
 8084                        },
 8085                    ));
 8086
 8087                    // Move folds up
 8088                    unfold_ranges.push(range_to_move.clone());
 8089                    for fold in display_map.folds_in_range(
 8090                        buffer.anchor_before(range_to_move.start)
 8091                            ..buffer.anchor_after(range_to_move.end),
 8092                    ) {
 8093                        let mut start = fold.range.start.to_point(&buffer);
 8094                        let mut end = fold.range.end.to_point(&buffer);
 8095                        start.row -= row_delta;
 8096                        end.row -= row_delta;
 8097                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8098                    }
 8099                }
 8100            }
 8101
 8102            // If we didn't move line(s), preserve the existing selections
 8103            new_selections.append(&mut contiguous_row_selections);
 8104        }
 8105
 8106        self.transact(window, cx, |this, window, cx| {
 8107            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8108            this.buffer.update(cx, |buffer, cx| {
 8109                for (range, text) in edits {
 8110                    buffer.edit([(range, text)], None, cx);
 8111                }
 8112            });
 8113            this.fold_creases(refold_creases, true, window, cx);
 8114            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8115                s.select(new_selections);
 8116            })
 8117        });
 8118    }
 8119
 8120    pub fn move_line_down(
 8121        &mut self,
 8122        _: &MoveLineDown,
 8123        window: &mut Window,
 8124        cx: &mut Context<Self>,
 8125    ) {
 8126        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8127        let buffer = self.buffer.read(cx).snapshot(cx);
 8128
 8129        let mut edits = Vec::new();
 8130        let mut unfold_ranges = Vec::new();
 8131        let mut refold_creases = Vec::new();
 8132
 8133        let selections = self.selections.all::<Point>(cx);
 8134        let mut selections = selections.iter().peekable();
 8135        let mut contiguous_row_selections = Vec::new();
 8136        let mut new_selections = Vec::new();
 8137
 8138        while let Some(selection) = selections.next() {
 8139            // Find all the selections that span a contiguous row range
 8140            let (start_row, end_row) = consume_contiguous_rows(
 8141                &mut contiguous_row_selections,
 8142                selection,
 8143                &display_map,
 8144                &mut selections,
 8145            );
 8146
 8147            // Move the text spanned by the row range to be after the last line of the row range
 8148            if end_row.0 <= buffer.max_point().row {
 8149                let range_to_move =
 8150                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 8151                let insertion_point = display_map
 8152                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 8153                    .0;
 8154
 8155                // Don't move lines across excerpt boundaries
 8156                if buffer
 8157                    .excerpt_containing(range_to_move.start..insertion_point)
 8158                    .is_some()
 8159                {
 8160                    let mut text = String::from("\n");
 8161                    text.extend(buffer.text_for_range(range_to_move.clone()));
 8162                    text.pop(); // Drop trailing newline
 8163                    edits.push((
 8164                        buffer.anchor_after(range_to_move.start)
 8165                            ..buffer.anchor_before(range_to_move.end),
 8166                        String::new(),
 8167                    ));
 8168                    let insertion_anchor = buffer.anchor_after(insertion_point);
 8169                    edits.push((insertion_anchor..insertion_anchor, text));
 8170
 8171                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 8172
 8173                    // Move selections down
 8174                    new_selections.extend(contiguous_row_selections.drain(..).map(
 8175                        |mut selection| {
 8176                            selection.start.row += row_delta;
 8177                            selection.end.row += row_delta;
 8178                            selection
 8179                        },
 8180                    ));
 8181
 8182                    // Move folds down
 8183                    unfold_ranges.push(range_to_move.clone());
 8184                    for fold in display_map.folds_in_range(
 8185                        buffer.anchor_before(range_to_move.start)
 8186                            ..buffer.anchor_after(range_to_move.end),
 8187                    ) {
 8188                        let mut start = fold.range.start.to_point(&buffer);
 8189                        let mut end = fold.range.end.to_point(&buffer);
 8190                        start.row += row_delta;
 8191                        end.row += row_delta;
 8192                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 8193                    }
 8194                }
 8195            }
 8196
 8197            // If we didn't move line(s), preserve the existing selections
 8198            new_selections.append(&mut contiguous_row_selections);
 8199        }
 8200
 8201        self.transact(window, cx, |this, window, cx| {
 8202            this.unfold_ranges(&unfold_ranges, true, true, cx);
 8203            this.buffer.update(cx, |buffer, cx| {
 8204                for (range, text) in edits {
 8205                    buffer.edit([(range, text)], None, cx);
 8206                }
 8207            });
 8208            this.fold_creases(refold_creases, true, window, cx);
 8209            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8210                s.select(new_selections)
 8211            });
 8212        });
 8213    }
 8214
 8215    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 8216        let text_layout_details = &self.text_layout_details(window);
 8217        self.transact(window, cx, |this, window, cx| {
 8218            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8219                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 8220                let line_mode = s.line_mode;
 8221                s.move_with(|display_map, selection| {
 8222                    if !selection.is_empty() || line_mode {
 8223                        return;
 8224                    }
 8225
 8226                    let mut head = selection.head();
 8227                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 8228                    if head.column() == display_map.line_len(head.row()) {
 8229                        transpose_offset = display_map
 8230                            .buffer_snapshot
 8231                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8232                    }
 8233
 8234                    if transpose_offset == 0 {
 8235                        return;
 8236                    }
 8237
 8238                    *head.column_mut() += 1;
 8239                    head = display_map.clip_point(head, Bias::Right);
 8240                    let goal = SelectionGoal::HorizontalPosition(
 8241                        display_map
 8242                            .x_for_display_point(head, text_layout_details)
 8243                            .into(),
 8244                    );
 8245                    selection.collapse_to(head, goal);
 8246
 8247                    let transpose_start = display_map
 8248                        .buffer_snapshot
 8249                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 8250                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 8251                        let transpose_end = display_map
 8252                            .buffer_snapshot
 8253                            .clip_offset(transpose_offset + 1, Bias::Right);
 8254                        if let Some(ch) =
 8255                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 8256                        {
 8257                            edits.push((transpose_start..transpose_offset, String::new()));
 8258                            edits.push((transpose_end..transpose_end, ch.to_string()));
 8259                        }
 8260                    }
 8261                });
 8262                edits
 8263            });
 8264            this.buffer
 8265                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8266            let selections = this.selections.all::<usize>(cx);
 8267            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8268                s.select(selections);
 8269            });
 8270        });
 8271    }
 8272
 8273    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 8274        self.rewrap_impl(IsVimMode::No, cx)
 8275    }
 8276
 8277    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 8278        let buffer = self.buffer.read(cx).snapshot(cx);
 8279        let selections = self.selections.all::<Point>(cx);
 8280        let mut selections = selections.iter().peekable();
 8281
 8282        let mut edits = Vec::new();
 8283        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 8284
 8285        while let Some(selection) = selections.next() {
 8286            let mut start_row = selection.start.row;
 8287            let mut end_row = selection.end.row;
 8288
 8289            // Skip selections that overlap with a range that has already been rewrapped.
 8290            let selection_range = start_row..end_row;
 8291            if rewrapped_row_ranges
 8292                .iter()
 8293                .any(|range| range.overlaps(&selection_range))
 8294            {
 8295                continue;
 8296            }
 8297
 8298            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 8299
 8300            // Since not all lines in the selection may be at the same indent
 8301            // level, choose the indent size that is the most common between all
 8302            // of the lines.
 8303            //
 8304            // If there is a tie, we use the deepest indent.
 8305            let (indent_size, indent_end) = {
 8306                let mut indent_size_occurrences = HashMap::default();
 8307                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 8308
 8309                for row in start_row..=end_row {
 8310                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 8311                    rows_by_indent_size.entry(indent).or_default().push(row);
 8312                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 8313                }
 8314
 8315                let indent_size = indent_size_occurrences
 8316                    .into_iter()
 8317                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 8318                    .map(|(indent, _)| indent)
 8319                    .unwrap_or_default();
 8320                let row = rows_by_indent_size[&indent_size][0];
 8321                let indent_end = Point::new(row, indent_size.len);
 8322
 8323                (indent_size, indent_end)
 8324            };
 8325
 8326            let mut line_prefix = indent_size.chars().collect::<String>();
 8327
 8328            let mut inside_comment = false;
 8329            if let Some(comment_prefix) =
 8330                buffer
 8331                    .language_scope_at(selection.head())
 8332                    .and_then(|language| {
 8333                        language
 8334                            .line_comment_prefixes()
 8335                            .iter()
 8336                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 8337                            .cloned()
 8338                    })
 8339            {
 8340                line_prefix.push_str(&comment_prefix);
 8341                inside_comment = true;
 8342            }
 8343
 8344            let language_settings = buffer.settings_at(selection.head(), cx);
 8345            let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
 8346                RewrapBehavior::InComments => inside_comment,
 8347                RewrapBehavior::InSelections => !selection.is_empty(),
 8348                RewrapBehavior::Anywhere => true,
 8349            };
 8350
 8351            let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
 8352            if !should_rewrap {
 8353                continue;
 8354            }
 8355
 8356            if selection.is_empty() {
 8357                'expand_upwards: while start_row > 0 {
 8358                    let prev_row = start_row - 1;
 8359                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 8360                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 8361                    {
 8362                        start_row = prev_row;
 8363                    } else {
 8364                        break 'expand_upwards;
 8365                    }
 8366                }
 8367
 8368                'expand_downwards: while end_row < buffer.max_point().row {
 8369                    let next_row = end_row + 1;
 8370                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 8371                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 8372                    {
 8373                        end_row = next_row;
 8374                    } else {
 8375                        break 'expand_downwards;
 8376                    }
 8377                }
 8378            }
 8379
 8380            let start = Point::new(start_row, 0);
 8381            let start_offset = start.to_offset(&buffer);
 8382            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 8383            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 8384            let Some(lines_without_prefixes) = selection_text
 8385                .lines()
 8386                .map(|line| {
 8387                    line.strip_prefix(&line_prefix)
 8388                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 8389                        .ok_or_else(|| {
 8390                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 8391                        })
 8392                })
 8393                .collect::<Result<Vec<_>, _>>()
 8394                .log_err()
 8395            else {
 8396                continue;
 8397            };
 8398
 8399            let wrap_column = buffer
 8400                .settings_at(Point::new(start_row, 0), cx)
 8401                .preferred_line_length as usize;
 8402            let wrapped_text = wrap_with_prefix(
 8403                line_prefix,
 8404                lines_without_prefixes.join(" "),
 8405                wrap_column,
 8406                tab_size,
 8407            );
 8408
 8409            // TODO: should always use char-based diff while still supporting cursor behavior that
 8410            // matches vim.
 8411            let mut diff_options = DiffOptions::default();
 8412            if is_vim_mode == IsVimMode::Yes {
 8413                diff_options.max_word_diff_len = 0;
 8414                diff_options.max_word_diff_line_count = 0;
 8415            } else {
 8416                diff_options.max_word_diff_len = usize::MAX;
 8417                diff_options.max_word_diff_line_count = usize::MAX;
 8418            }
 8419
 8420            for (old_range, new_text) in
 8421                text_diff_with_options(&selection_text, &wrapped_text, diff_options)
 8422            {
 8423                let edit_start = buffer.anchor_after(start_offset + old_range.start);
 8424                let edit_end = buffer.anchor_after(start_offset + old_range.end);
 8425                edits.push((edit_start..edit_end, new_text));
 8426            }
 8427
 8428            rewrapped_row_ranges.push(start_row..=end_row);
 8429        }
 8430
 8431        self.buffer
 8432            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 8433    }
 8434
 8435    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 8436        let mut text = String::new();
 8437        let buffer = self.buffer.read(cx).snapshot(cx);
 8438        let mut selections = self.selections.all::<Point>(cx);
 8439        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8440        {
 8441            let max_point = buffer.max_point();
 8442            let mut is_first = true;
 8443            for selection in &mut selections {
 8444                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8445                if is_entire_line {
 8446                    selection.start = Point::new(selection.start.row, 0);
 8447                    if !selection.is_empty() && selection.end.column == 0 {
 8448                        selection.end = cmp::min(max_point, selection.end);
 8449                    } else {
 8450                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 8451                    }
 8452                    selection.goal = SelectionGoal::None;
 8453                }
 8454                if is_first {
 8455                    is_first = false;
 8456                } else {
 8457                    text += "\n";
 8458                }
 8459                let mut len = 0;
 8460                for chunk in buffer.text_for_range(selection.start..selection.end) {
 8461                    text.push_str(chunk);
 8462                    len += chunk.len();
 8463                }
 8464                clipboard_selections.push(ClipboardSelection {
 8465                    len,
 8466                    is_entire_line,
 8467                    start_column: selection.start.column,
 8468                });
 8469            }
 8470        }
 8471
 8472        self.transact(window, cx, |this, window, cx| {
 8473            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8474                s.select(selections);
 8475            });
 8476            this.insert("", window, cx);
 8477        });
 8478        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8479    }
 8480
 8481    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8482        let item = self.cut_common(window, cx);
 8483        cx.write_to_clipboard(item);
 8484    }
 8485
 8486    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8487        self.change_selections(None, window, cx, |s| {
 8488            s.move_with(|snapshot, sel| {
 8489                if sel.is_empty() {
 8490                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8491                }
 8492            });
 8493        });
 8494        let item = self.cut_common(window, cx);
 8495        cx.set_global(KillRing(item))
 8496    }
 8497
 8498    pub fn kill_ring_yank(
 8499        &mut self,
 8500        _: &KillRingYank,
 8501        window: &mut Window,
 8502        cx: &mut Context<Self>,
 8503    ) {
 8504        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8505            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8506                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8507            } else {
 8508                return;
 8509            }
 8510        } else {
 8511            return;
 8512        };
 8513        self.do_paste(&text, metadata, false, window, cx);
 8514    }
 8515
 8516    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8517        let selections = self.selections.all::<Point>(cx);
 8518        let buffer = self.buffer.read(cx).read(cx);
 8519        let mut text = String::new();
 8520
 8521        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8522        {
 8523            let max_point = buffer.max_point();
 8524            let mut is_first = true;
 8525            for selection in selections.iter() {
 8526                let mut start = selection.start;
 8527                let mut end = selection.end;
 8528                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8529                if is_entire_line {
 8530                    start = Point::new(start.row, 0);
 8531                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8532                }
 8533                if is_first {
 8534                    is_first = false;
 8535                } else {
 8536                    text += "\n";
 8537                }
 8538                let mut len = 0;
 8539                for chunk in buffer.text_for_range(start..end) {
 8540                    text.push_str(chunk);
 8541                    len += chunk.len();
 8542                }
 8543                clipboard_selections.push(ClipboardSelection {
 8544                    len,
 8545                    is_entire_line,
 8546                    start_column: start.column,
 8547                });
 8548            }
 8549        }
 8550
 8551        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8552            text,
 8553            clipboard_selections,
 8554        ));
 8555    }
 8556
 8557    pub fn do_paste(
 8558        &mut self,
 8559        text: &String,
 8560        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8561        handle_entire_lines: bool,
 8562        window: &mut Window,
 8563        cx: &mut Context<Self>,
 8564    ) {
 8565        if self.read_only(cx) {
 8566            return;
 8567        }
 8568
 8569        let clipboard_text = Cow::Borrowed(text);
 8570
 8571        self.transact(window, cx, |this, window, cx| {
 8572            if let Some(mut clipboard_selections) = clipboard_selections {
 8573                let old_selections = this.selections.all::<usize>(cx);
 8574                let all_selections_were_entire_line =
 8575                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8576                let first_selection_start_column =
 8577                    clipboard_selections.first().map(|s| s.start_column);
 8578                if clipboard_selections.len() != old_selections.len() {
 8579                    clipboard_selections.drain(..);
 8580                }
 8581                let cursor_offset = this.selections.last::<usize>(cx).head();
 8582                let mut auto_indent_on_paste = true;
 8583
 8584                this.buffer.update(cx, |buffer, cx| {
 8585                    let snapshot = buffer.read(cx);
 8586                    auto_indent_on_paste =
 8587                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8588
 8589                    let mut start_offset = 0;
 8590                    let mut edits = Vec::new();
 8591                    let mut original_start_columns = Vec::new();
 8592                    for (ix, selection) in old_selections.iter().enumerate() {
 8593                        let to_insert;
 8594                        let entire_line;
 8595                        let original_start_column;
 8596                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8597                            let end_offset = start_offset + clipboard_selection.len;
 8598                            to_insert = &clipboard_text[start_offset..end_offset];
 8599                            entire_line = clipboard_selection.is_entire_line;
 8600                            start_offset = end_offset + 1;
 8601                            original_start_column = Some(clipboard_selection.start_column);
 8602                        } else {
 8603                            to_insert = clipboard_text.as_str();
 8604                            entire_line = all_selections_were_entire_line;
 8605                            original_start_column = first_selection_start_column
 8606                        }
 8607
 8608                        // If the corresponding selection was empty when this slice of the
 8609                        // clipboard text was written, then the entire line containing the
 8610                        // selection was copied. If this selection is also currently empty,
 8611                        // then paste the line before the current line of the buffer.
 8612                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8613                            let column = selection.start.to_point(&snapshot).column as usize;
 8614                            let line_start = selection.start - column;
 8615                            line_start..line_start
 8616                        } else {
 8617                            selection.range()
 8618                        };
 8619
 8620                        edits.push((range, to_insert));
 8621                        original_start_columns.extend(original_start_column);
 8622                    }
 8623                    drop(snapshot);
 8624
 8625                    buffer.edit(
 8626                        edits,
 8627                        if auto_indent_on_paste {
 8628                            Some(AutoindentMode::Block {
 8629                                original_start_columns,
 8630                            })
 8631                        } else {
 8632                            None
 8633                        },
 8634                        cx,
 8635                    );
 8636                });
 8637
 8638                let selections = this.selections.all::<usize>(cx);
 8639                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8640                    s.select(selections)
 8641                });
 8642            } else {
 8643                this.insert(&clipboard_text, window, cx);
 8644            }
 8645        });
 8646    }
 8647
 8648    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8649        if let Some(item) = cx.read_from_clipboard() {
 8650            let entries = item.entries();
 8651
 8652            match entries.first() {
 8653                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8654                // of all the pasted entries.
 8655                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8656                    .do_paste(
 8657                        clipboard_string.text(),
 8658                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8659                        true,
 8660                        window,
 8661                        cx,
 8662                    ),
 8663                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8664            }
 8665        }
 8666    }
 8667
 8668    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8669        if self.read_only(cx) {
 8670            return;
 8671        }
 8672
 8673        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8674            if let Some((selections, _)) =
 8675                self.selection_history.transaction(transaction_id).cloned()
 8676            {
 8677                self.change_selections(None, window, cx, |s| {
 8678                    s.select_anchors(selections.to_vec());
 8679                });
 8680            }
 8681            self.request_autoscroll(Autoscroll::fit(), cx);
 8682            self.unmark_text(window, cx);
 8683            self.refresh_inline_completion(true, false, window, cx);
 8684            cx.emit(EditorEvent::Edited { transaction_id });
 8685            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8686        }
 8687    }
 8688
 8689    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8690        if self.read_only(cx) {
 8691            return;
 8692        }
 8693
 8694        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8695            if let Some((_, Some(selections))) =
 8696                self.selection_history.transaction(transaction_id).cloned()
 8697            {
 8698                self.change_selections(None, window, cx, |s| {
 8699                    s.select_anchors(selections.to_vec());
 8700                });
 8701            }
 8702            self.request_autoscroll(Autoscroll::fit(), cx);
 8703            self.unmark_text(window, cx);
 8704            self.refresh_inline_completion(true, false, window, cx);
 8705            cx.emit(EditorEvent::Edited { transaction_id });
 8706        }
 8707    }
 8708
 8709    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8710        self.buffer
 8711            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8712    }
 8713
 8714    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8715        self.buffer
 8716            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8717    }
 8718
 8719    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8720        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8721            let line_mode = s.line_mode;
 8722            s.move_with(|map, selection| {
 8723                let cursor = if selection.is_empty() && !line_mode {
 8724                    movement::left(map, selection.start)
 8725                } else {
 8726                    selection.start
 8727                };
 8728                selection.collapse_to(cursor, SelectionGoal::None);
 8729            });
 8730        })
 8731    }
 8732
 8733    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8734        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8735            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8736        })
 8737    }
 8738
 8739    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8740        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8741            let line_mode = s.line_mode;
 8742            s.move_with(|map, selection| {
 8743                let cursor = if selection.is_empty() && !line_mode {
 8744                    movement::right(map, selection.end)
 8745                } else {
 8746                    selection.end
 8747                };
 8748                selection.collapse_to(cursor, SelectionGoal::None)
 8749            });
 8750        })
 8751    }
 8752
 8753    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8754        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8755            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8756        })
 8757    }
 8758
 8759    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8760        if self.take_rename(true, window, cx).is_some() {
 8761            return;
 8762        }
 8763
 8764        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8765            cx.propagate();
 8766            return;
 8767        }
 8768
 8769        let text_layout_details = &self.text_layout_details(window);
 8770        let selection_count = self.selections.count();
 8771        let first_selection = self.selections.first_anchor();
 8772
 8773        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8774            let line_mode = s.line_mode;
 8775            s.move_with(|map, selection| {
 8776                if !selection.is_empty() && !line_mode {
 8777                    selection.goal = SelectionGoal::None;
 8778                }
 8779                let (cursor, goal) = movement::up(
 8780                    map,
 8781                    selection.start,
 8782                    selection.goal,
 8783                    false,
 8784                    text_layout_details,
 8785                );
 8786                selection.collapse_to(cursor, goal);
 8787            });
 8788        });
 8789
 8790        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8791        {
 8792            cx.propagate();
 8793        }
 8794    }
 8795
 8796    pub fn move_up_by_lines(
 8797        &mut self,
 8798        action: &MoveUpByLines,
 8799        window: &mut Window,
 8800        cx: &mut Context<Self>,
 8801    ) {
 8802        if self.take_rename(true, window, cx).is_some() {
 8803            return;
 8804        }
 8805
 8806        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8807            cx.propagate();
 8808            return;
 8809        }
 8810
 8811        let text_layout_details = &self.text_layout_details(window);
 8812
 8813        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8814            let line_mode = s.line_mode;
 8815            s.move_with(|map, selection| {
 8816                if !selection.is_empty() && !line_mode {
 8817                    selection.goal = SelectionGoal::None;
 8818                }
 8819                let (cursor, goal) = movement::up_by_rows(
 8820                    map,
 8821                    selection.start,
 8822                    action.lines,
 8823                    selection.goal,
 8824                    false,
 8825                    text_layout_details,
 8826                );
 8827                selection.collapse_to(cursor, goal);
 8828            });
 8829        })
 8830    }
 8831
 8832    pub fn move_down_by_lines(
 8833        &mut self,
 8834        action: &MoveDownByLines,
 8835        window: &mut Window,
 8836        cx: &mut Context<Self>,
 8837    ) {
 8838        if self.take_rename(true, window, cx).is_some() {
 8839            return;
 8840        }
 8841
 8842        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8843            cx.propagate();
 8844            return;
 8845        }
 8846
 8847        let text_layout_details = &self.text_layout_details(window);
 8848
 8849        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8850            let line_mode = s.line_mode;
 8851            s.move_with(|map, selection| {
 8852                if !selection.is_empty() && !line_mode {
 8853                    selection.goal = SelectionGoal::None;
 8854                }
 8855                let (cursor, goal) = movement::down_by_rows(
 8856                    map,
 8857                    selection.start,
 8858                    action.lines,
 8859                    selection.goal,
 8860                    false,
 8861                    text_layout_details,
 8862                );
 8863                selection.collapse_to(cursor, goal);
 8864            });
 8865        })
 8866    }
 8867
 8868    pub fn select_down_by_lines(
 8869        &mut self,
 8870        action: &SelectDownByLines,
 8871        window: &mut Window,
 8872        cx: &mut Context<Self>,
 8873    ) {
 8874        let text_layout_details = &self.text_layout_details(window);
 8875        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8876            s.move_heads_with(|map, head, goal| {
 8877                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8878            })
 8879        })
 8880    }
 8881
 8882    pub fn select_up_by_lines(
 8883        &mut self,
 8884        action: &SelectUpByLines,
 8885        window: &mut Window,
 8886        cx: &mut Context<Self>,
 8887    ) {
 8888        let text_layout_details = &self.text_layout_details(window);
 8889        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8890            s.move_heads_with(|map, head, goal| {
 8891                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8892            })
 8893        })
 8894    }
 8895
 8896    pub fn select_page_up(
 8897        &mut self,
 8898        _: &SelectPageUp,
 8899        window: &mut Window,
 8900        cx: &mut Context<Self>,
 8901    ) {
 8902        let Some(row_count) = self.visible_row_count() else {
 8903            return;
 8904        };
 8905
 8906        let text_layout_details = &self.text_layout_details(window);
 8907
 8908        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8909            s.move_heads_with(|map, head, goal| {
 8910                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8911            })
 8912        })
 8913    }
 8914
 8915    pub fn move_page_up(
 8916        &mut self,
 8917        action: &MovePageUp,
 8918        window: &mut Window,
 8919        cx: &mut Context<Self>,
 8920    ) {
 8921        if self.take_rename(true, window, cx).is_some() {
 8922            return;
 8923        }
 8924
 8925        if self
 8926            .context_menu
 8927            .borrow_mut()
 8928            .as_mut()
 8929            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8930            .unwrap_or(false)
 8931        {
 8932            return;
 8933        }
 8934
 8935        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8936            cx.propagate();
 8937            return;
 8938        }
 8939
 8940        let Some(row_count) = self.visible_row_count() else {
 8941            return;
 8942        };
 8943
 8944        let autoscroll = if action.center_cursor {
 8945            Autoscroll::center()
 8946        } else {
 8947            Autoscroll::fit()
 8948        };
 8949
 8950        let text_layout_details = &self.text_layout_details(window);
 8951
 8952        self.change_selections(Some(autoscroll), window, cx, |s| {
 8953            let line_mode = s.line_mode;
 8954            s.move_with(|map, selection| {
 8955                if !selection.is_empty() && !line_mode {
 8956                    selection.goal = SelectionGoal::None;
 8957                }
 8958                let (cursor, goal) = movement::up_by_rows(
 8959                    map,
 8960                    selection.end,
 8961                    row_count,
 8962                    selection.goal,
 8963                    false,
 8964                    text_layout_details,
 8965                );
 8966                selection.collapse_to(cursor, goal);
 8967            });
 8968        });
 8969    }
 8970
 8971    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8972        let text_layout_details = &self.text_layout_details(window);
 8973        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8974            s.move_heads_with(|map, head, goal| {
 8975                movement::up(map, head, goal, false, text_layout_details)
 8976            })
 8977        })
 8978    }
 8979
 8980    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8981        self.take_rename(true, window, cx);
 8982
 8983        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8984            cx.propagate();
 8985            return;
 8986        }
 8987
 8988        let text_layout_details = &self.text_layout_details(window);
 8989        let selection_count = self.selections.count();
 8990        let first_selection = self.selections.first_anchor();
 8991
 8992        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8993            let line_mode = s.line_mode;
 8994            s.move_with(|map, selection| {
 8995                if !selection.is_empty() && !line_mode {
 8996                    selection.goal = SelectionGoal::None;
 8997                }
 8998                let (cursor, goal) = movement::down(
 8999                    map,
 9000                    selection.end,
 9001                    selection.goal,
 9002                    false,
 9003                    text_layout_details,
 9004                );
 9005                selection.collapse_to(cursor, goal);
 9006            });
 9007        });
 9008
 9009        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 9010        {
 9011            cx.propagate();
 9012        }
 9013    }
 9014
 9015    pub fn select_page_down(
 9016        &mut self,
 9017        _: &SelectPageDown,
 9018        window: &mut Window,
 9019        cx: &mut Context<Self>,
 9020    ) {
 9021        let Some(row_count) = self.visible_row_count() else {
 9022            return;
 9023        };
 9024
 9025        let text_layout_details = &self.text_layout_details(window);
 9026
 9027        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9028            s.move_heads_with(|map, head, goal| {
 9029                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 9030            })
 9031        })
 9032    }
 9033
 9034    pub fn move_page_down(
 9035        &mut self,
 9036        action: &MovePageDown,
 9037        window: &mut Window,
 9038        cx: &mut Context<Self>,
 9039    ) {
 9040        if self.take_rename(true, window, cx).is_some() {
 9041            return;
 9042        }
 9043
 9044        if self
 9045            .context_menu
 9046            .borrow_mut()
 9047            .as_mut()
 9048            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 9049            .unwrap_or(false)
 9050        {
 9051            return;
 9052        }
 9053
 9054        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9055            cx.propagate();
 9056            return;
 9057        }
 9058
 9059        let Some(row_count) = self.visible_row_count() else {
 9060            return;
 9061        };
 9062
 9063        let autoscroll = if action.center_cursor {
 9064            Autoscroll::center()
 9065        } else {
 9066            Autoscroll::fit()
 9067        };
 9068
 9069        let text_layout_details = &self.text_layout_details(window);
 9070        self.change_selections(Some(autoscroll), window, cx, |s| {
 9071            let line_mode = s.line_mode;
 9072            s.move_with(|map, selection| {
 9073                if !selection.is_empty() && !line_mode {
 9074                    selection.goal = SelectionGoal::None;
 9075                }
 9076                let (cursor, goal) = movement::down_by_rows(
 9077                    map,
 9078                    selection.end,
 9079                    row_count,
 9080                    selection.goal,
 9081                    false,
 9082                    text_layout_details,
 9083                );
 9084                selection.collapse_to(cursor, goal);
 9085            });
 9086        });
 9087    }
 9088
 9089    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 9090        let text_layout_details = &self.text_layout_details(window);
 9091        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9092            s.move_heads_with(|map, head, goal| {
 9093                movement::down(map, head, goal, false, text_layout_details)
 9094            })
 9095        });
 9096    }
 9097
 9098    pub fn context_menu_first(
 9099        &mut self,
 9100        _: &ContextMenuFirst,
 9101        _window: &mut Window,
 9102        cx: &mut Context<Self>,
 9103    ) {
 9104        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9105            context_menu.select_first(self.completion_provider.as_deref(), cx);
 9106        }
 9107    }
 9108
 9109    pub fn context_menu_prev(
 9110        &mut self,
 9111        _: &ContextMenuPrev,
 9112        _window: &mut Window,
 9113        cx: &mut Context<Self>,
 9114    ) {
 9115        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9116            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 9117        }
 9118    }
 9119
 9120    pub fn context_menu_next(
 9121        &mut self,
 9122        _: &ContextMenuNext,
 9123        _window: &mut Window,
 9124        cx: &mut Context<Self>,
 9125    ) {
 9126        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9127            context_menu.select_next(self.completion_provider.as_deref(), cx);
 9128        }
 9129    }
 9130
 9131    pub fn context_menu_last(
 9132        &mut self,
 9133        _: &ContextMenuLast,
 9134        _window: &mut Window,
 9135        cx: &mut Context<Self>,
 9136    ) {
 9137        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 9138            context_menu.select_last(self.completion_provider.as_deref(), cx);
 9139        }
 9140    }
 9141
 9142    pub fn move_to_previous_word_start(
 9143        &mut self,
 9144        _: &MoveToPreviousWordStart,
 9145        window: &mut Window,
 9146        cx: &mut Context<Self>,
 9147    ) {
 9148        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9149            s.move_cursors_with(|map, head, _| {
 9150                (
 9151                    movement::previous_word_start(map, head),
 9152                    SelectionGoal::None,
 9153                )
 9154            });
 9155        })
 9156    }
 9157
 9158    pub fn move_to_previous_subword_start(
 9159        &mut self,
 9160        _: &MoveToPreviousSubwordStart,
 9161        window: &mut Window,
 9162        cx: &mut Context<Self>,
 9163    ) {
 9164        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9165            s.move_cursors_with(|map, head, _| {
 9166                (
 9167                    movement::previous_subword_start(map, head),
 9168                    SelectionGoal::None,
 9169                )
 9170            });
 9171        })
 9172    }
 9173
 9174    pub fn select_to_previous_word_start(
 9175        &mut self,
 9176        _: &SelectToPreviousWordStart,
 9177        window: &mut Window,
 9178        cx: &mut Context<Self>,
 9179    ) {
 9180        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9181            s.move_heads_with(|map, head, _| {
 9182                (
 9183                    movement::previous_word_start(map, head),
 9184                    SelectionGoal::None,
 9185                )
 9186            });
 9187        })
 9188    }
 9189
 9190    pub fn select_to_previous_subword_start(
 9191        &mut self,
 9192        _: &SelectToPreviousSubwordStart,
 9193        window: &mut Window,
 9194        cx: &mut Context<Self>,
 9195    ) {
 9196        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9197            s.move_heads_with(|map, head, _| {
 9198                (
 9199                    movement::previous_subword_start(map, head),
 9200                    SelectionGoal::None,
 9201                )
 9202            });
 9203        })
 9204    }
 9205
 9206    pub fn delete_to_previous_word_start(
 9207        &mut self,
 9208        action: &DeleteToPreviousWordStart,
 9209        window: &mut Window,
 9210        cx: &mut Context<Self>,
 9211    ) {
 9212        self.transact(window, cx, |this, window, cx| {
 9213            this.select_autoclose_pair(window, cx);
 9214            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9215                let line_mode = s.line_mode;
 9216                s.move_with(|map, selection| {
 9217                    if selection.is_empty() && !line_mode {
 9218                        let cursor = if action.ignore_newlines {
 9219                            movement::previous_word_start(map, selection.head())
 9220                        } else {
 9221                            movement::previous_word_start_or_newline(map, selection.head())
 9222                        };
 9223                        selection.set_head(cursor, SelectionGoal::None);
 9224                    }
 9225                });
 9226            });
 9227            this.insert("", window, cx);
 9228        });
 9229    }
 9230
 9231    pub fn delete_to_previous_subword_start(
 9232        &mut self,
 9233        _: &DeleteToPreviousSubwordStart,
 9234        window: &mut Window,
 9235        cx: &mut Context<Self>,
 9236    ) {
 9237        self.transact(window, cx, |this, window, cx| {
 9238            this.select_autoclose_pair(window, cx);
 9239            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9240                let line_mode = s.line_mode;
 9241                s.move_with(|map, selection| {
 9242                    if selection.is_empty() && !line_mode {
 9243                        let cursor = movement::previous_subword_start(map, selection.head());
 9244                        selection.set_head(cursor, SelectionGoal::None);
 9245                    }
 9246                });
 9247            });
 9248            this.insert("", window, cx);
 9249        });
 9250    }
 9251
 9252    pub fn move_to_next_word_end(
 9253        &mut self,
 9254        _: &MoveToNextWordEnd,
 9255        window: &mut Window,
 9256        cx: &mut Context<Self>,
 9257    ) {
 9258        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9259            s.move_cursors_with(|map, head, _| {
 9260                (movement::next_word_end(map, head), SelectionGoal::None)
 9261            });
 9262        })
 9263    }
 9264
 9265    pub fn move_to_next_subword_end(
 9266        &mut self,
 9267        _: &MoveToNextSubwordEnd,
 9268        window: &mut Window,
 9269        cx: &mut Context<Self>,
 9270    ) {
 9271        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9272            s.move_cursors_with(|map, head, _| {
 9273                (movement::next_subword_end(map, head), SelectionGoal::None)
 9274            });
 9275        })
 9276    }
 9277
 9278    pub fn select_to_next_word_end(
 9279        &mut self,
 9280        _: &SelectToNextWordEnd,
 9281        window: &mut Window,
 9282        cx: &mut Context<Self>,
 9283    ) {
 9284        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9285            s.move_heads_with(|map, head, _| {
 9286                (movement::next_word_end(map, head), SelectionGoal::None)
 9287            });
 9288        })
 9289    }
 9290
 9291    pub fn select_to_next_subword_end(
 9292        &mut self,
 9293        _: &SelectToNextSubwordEnd,
 9294        window: &mut Window,
 9295        cx: &mut Context<Self>,
 9296    ) {
 9297        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9298            s.move_heads_with(|map, head, _| {
 9299                (movement::next_subword_end(map, head), SelectionGoal::None)
 9300            });
 9301        })
 9302    }
 9303
 9304    pub fn delete_to_next_word_end(
 9305        &mut self,
 9306        action: &DeleteToNextWordEnd,
 9307        window: &mut Window,
 9308        cx: &mut Context<Self>,
 9309    ) {
 9310        self.transact(window, cx, |this, window, cx| {
 9311            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9312                let line_mode = s.line_mode;
 9313                s.move_with(|map, selection| {
 9314                    if selection.is_empty() && !line_mode {
 9315                        let cursor = if action.ignore_newlines {
 9316                            movement::next_word_end(map, selection.head())
 9317                        } else {
 9318                            movement::next_word_end_or_newline(map, selection.head())
 9319                        };
 9320                        selection.set_head(cursor, SelectionGoal::None);
 9321                    }
 9322                });
 9323            });
 9324            this.insert("", window, cx);
 9325        });
 9326    }
 9327
 9328    pub fn delete_to_next_subword_end(
 9329        &mut self,
 9330        _: &DeleteToNextSubwordEnd,
 9331        window: &mut Window,
 9332        cx: &mut Context<Self>,
 9333    ) {
 9334        self.transact(window, cx, |this, window, cx| {
 9335            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9336                s.move_with(|map, selection| {
 9337                    if selection.is_empty() {
 9338                        let cursor = movement::next_subword_end(map, selection.head());
 9339                        selection.set_head(cursor, SelectionGoal::None);
 9340                    }
 9341                });
 9342            });
 9343            this.insert("", window, cx);
 9344        });
 9345    }
 9346
 9347    pub fn move_to_beginning_of_line(
 9348        &mut self,
 9349        action: &MoveToBeginningOfLine,
 9350        window: &mut Window,
 9351        cx: &mut Context<Self>,
 9352    ) {
 9353        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9354            s.move_cursors_with(|map, head, _| {
 9355                (
 9356                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 9357                    SelectionGoal::None,
 9358                )
 9359            });
 9360        })
 9361    }
 9362
 9363    pub fn select_to_beginning_of_line(
 9364        &mut self,
 9365        action: &SelectToBeginningOfLine,
 9366        window: &mut Window,
 9367        cx: &mut Context<Self>,
 9368    ) {
 9369        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9370            s.move_heads_with(|map, head, _| {
 9371                (
 9372                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 9373                    SelectionGoal::None,
 9374                )
 9375            });
 9376        });
 9377    }
 9378
 9379    pub fn delete_to_beginning_of_line(
 9380        &mut self,
 9381        _: &DeleteToBeginningOfLine,
 9382        window: &mut Window,
 9383        cx: &mut Context<Self>,
 9384    ) {
 9385        self.transact(window, cx, |this, window, cx| {
 9386            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9387                s.move_with(|_, selection| {
 9388                    selection.reversed = true;
 9389                });
 9390            });
 9391
 9392            this.select_to_beginning_of_line(
 9393                &SelectToBeginningOfLine {
 9394                    stop_at_soft_wraps: false,
 9395                },
 9396                window,
 9397                cx,
 9398            );
 9399            this.backspace(&Backspace, window, cx);
 9400        });
 9401    }
 9402
 9403    pub fn move_to_end_of_line(
 9404        &mut self,
 9405        action: &MoveToEndOfLine,
 9406        window: &mut Window,
 9407        cx: &mut Context<Self>,
 9408    ) {
 9409        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9410            s.move_cursors_with(|map, head, _| {
 9411                (
 9412                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9413                    SelectionGoal::None,
 9414                )
 9415            });
 9416        })
 9417    }
 9418
 9419    pub fn select_to_end_of_line(
 9420        &mut self,
 9421        action: &SelectToEndOfLine,
 9422        window: &mut Window,
 9423        cx: &mut Context<Self>,
 9424    ) {
 9425        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9426            s.move_heads_with(|map, head, _| {
 9427                (
 9428                    movement::line_end(map, head, action.stop_at_soft_wraps),
 9429                    SelectionGoal::None,
 9430                )
 9431            });
 9432        })
 9433    }
 9434
 9435    pub fn delete_to_end_of_line(
 9436        &mut self,
 9437        _: &DeleteToEndOfLine,
 9438        window: &mut Window,
 9439        cx: &mut Context<Self>,
 9440    ) {
 9441        self.transact(window, cx, |this, window, cx| {
 9442            this.select_to_end_of_line(
 9443                &SelectToEndOfLine {
 9444                    stop_at_soft_wraps: false,
 9445                },
 9446                window,
 9447                cx,
 9448            );
 9449            this.delete(&Delete, window, cx);
 9450        });
 9451    }
 9452
 9453    pub fn cut_to_end_of_line(
 9454        &mut self,
 9455        _: &CutToEndOfLine,
 9456        window: &mut Window,
 9457        cx: &mut Context<Self>,
 9458    ) {
 9459        self.transact(window, cx, |this, window, cx| {
 9460            this.select_to_end_of_line(
 9461                &SelectToEndOfLine {
 9462                    stop_at_soft_wraps: false,
 9463                },
 9464                window,
 9465                cx,
 9466            );
 9467            this.cut(&Cut, window, cx);
 9468        });
 9469    }
 9470
 9471    pub fn move_to_start_of_paragraph(
 9472        &mut self,
 9473        _: &MoveToStartOfParagraph,
 9474        window: &mut Window,
 9475        cx: &mut Context<Self>,
 9476    ) {
 9477        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9478            cx.propagate();
 9479            return;
 9480        }
 9481
 9482        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9483            s.move_with(|map, selection| {
 9484                selection.collapse_to(
 9485                    movement::start_of_paragraph(map, selection.head(), 1),
 9486                    SelectionGoal::None,
 9487                )
 9488            });
 9489        })
 9490    }
 9491
 9492    pub fn move_to_end_of_paragraph(
 9493        &mut self,
 9494        _: &MoveToEndOfParagraph,
 9495        window: &mut Window,
 9496        cx: &mut Context<Self>,
 9497    ) {
 9498        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9499            cx.propagate();
 9500            return;
 9501        }
 9502
 9503        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9504            s.move_with(|map, selection| {
 9505                selection.collapse_to(
 9506                    movement::end_of_paragraph(map, selection.head(), 1),
 9507                    SelectionGoal::None,
 9508                )
 9509            });
 9510        })
 9511    }
 9512
 9513    pub fn select_to_start_of_paragraph(
 9514        &mut self,
 9515        _: &SelectToStartOfParagraph,
 9516        window: &mut Window,
 9517        cx: &mut Context<Self>,
 9518    ) {
 9519        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9520            cx.propagate();
 9521            return;
 9522        }
 9523
 9524        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9525            s.move_heads_with(|map, head, _| {
 9526                (
 9527                    movement::start_of_paragraph(map, head, 1),
 9528                    SelectionGoal::None,
 9529                )
 9530            });
 9531        })
 9532    }
 9533
 9534    pub fn select_to_end_of_paragraph(
 9535        &mut self,
 9536        _: &SelectToEndOfParagraph,
 9537        window: &mut Window,
 9538        cx: &mut Context<Self>,
 9539    ) {
 9540        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9541            cx.propagate();
 9542            return;
 9543        }
 9544
 9545        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9546            s.move_heads_with(|map, head, _| {
 9547                (
 9548                    movement::end_of_paragraph(map, head, 1),
 9549                    SelectionGoal::None,
 9550                )
 9551            });
 9552        })
 9553    }
 9554
 9555    pub fn move_to_start_of_excerpt(
 9556        &mut self,
 9557        _: &MoveToStartOfExcerpt,
 9558        window: &mut Window,
 9559        cx: &mut Context<Self>,
 9560    ) {
 9561        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9562            cx.propagate();
 9563            return;
 9564        }
 9565
 9566        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9567            s.move_with(|map, selection| {
 9568                selection.collapse_to(
 9569                    movement::start_of_excerpt(
 9570                        map,
 9571                        selection.head(),
 9572                        workspace::searchable::Direction::Prev,
 9573                    ),
 9574                    SelectionGoal::None,
 9575                )
 9576            });
 9577        })
 9578    }
 9579
 9580    pub fn move_to_end_of_excerpt(
 9581        &mut self,
 9582        _: &MoveToEndOfExcerpt,
 9583        window: &mut Window,
 9584        cx: &mut Context<Self>,
 9585    ) {
 9586        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9587            cx.propagate();
 9588            return;
 9589        }
 9590
 9591        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9592            s.move_with(|map, selection| {
 9593                selection.collapse_to(
 9594                    movement::end_of_excerpt(
 9595                        map,
 9596                        selection.head(),
 9597                        workspace::searchable::Direction::Next,
 9598                    ),
 9599                    SelectionGoal::None,
 9600                )
 9601            });
 9602        })
 9603    }
 9604
 9605    pub fn select_to_start_of_excerpt(
 9606        &mut self,
 9607        _: &SelectToStartOfExcerpt,
 9608        window: &mut Window,
 9609        cx: &mut Context<Self>,
 9610    ) {
 9611        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9612            cx.propagate();
 9613            return;
 9614        }
 9615
 9616        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9617            s.move_heads_with(|map, head, _| {
 9618                (
 9619                    movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
 9620                    SelectionGoal::None,
 9621                )
 9622            });
 9623        })
 9624    }
 9625
 9626    pub fn select_to_end_of_excerpt(
 9627        &mut self,
 9628        _: &SelectToEndOfExcerpt,
 9629        window: &mut Window,
 9630        cx: &mut Context<Self>,
 9631    ) {
 9632        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9633            cx.propagate();
 9634            return;
 9635        }
 9636
 9637        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9638            s.move_heads_with(|map, head, _| {
 9639                (
 9640                    movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
 9641                    SelectionGoal::None,
 9642                )
 9643            });
 9644        })
 9645    }
 9646
 9647    pub fn move_to_beginning(
 9648        &mut self,
 9649        _: &MoveToBeginning,
 9650        window: &mut Window,
 9651        cx: &mut Context<Self>,
 9652    ) {
 9653        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9654            cx.propagate();
 9655            return;
 9656        }
 9657
 9658        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9659            s.select_ranges(vec![0..0]);
 9660        });
 9661    }
 9662
 9663    pub fn select_to_beginning(
 9664        &mut self,
 9665        _: &SelectToBeginning,
 9666        window: &mut Window,
 9667        cx: &mut Context<Self>,
 9668    ) {
 9669        let mut selection = self.selections.last::<Point>(cx);
 9670        selection.set_head(Point::zero(), SelectionGoal::None);
 9671
 9672        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9673            s.select(vec![selection]);
 9674        });
 9675    }
 9676
 9677    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9678        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9679            cx.propagate();
 9680            return;
 9681        }
 9682
 9683        let cursor = self.buffer.read(cx).read(cx).len();
 9684        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9685            s.select_ranges(vec![cursor..cursor])
 9686        });
 9687    }
 9688
 9689    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9690        self.nav_history = nav_history;
 9691    }
 9692
 9693    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9694        self.nav_history.as_ref()
 9695    }
 9696
 9697    fn push_to_nav_history(
 9698        &mut self,
 9699        cursor_anchor: Anchor,
 9700        new_position: Option<Point>,
 9701        cx: &mut Context<Self>,
 9702    ) {
 9703        if let Some(nav_history) = self.nav_history.as_mut() {
 9704            let buffer = self.buffer.read(cx).read(cx);
 9705            let cursor_position = cursor_anchor.to_point(&buffer);
 9706            let scroll_state = self.scroll_manager.anchor();
 9707            let scroll_top_row = scroll_state.top_row(&buffer);
 9708            drop(buffer);
 9709
 9710            if let Some(new_position) = new_position {
 9711                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9712                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9713                    return;
 9714                }
 9715            }
 9716
 9717            nav_history.push(
 9718                Some(NavigationData {
 9719                    cursor_anchor,
 9720                    cursor_position,
 9721                    scroll_anchor: scroll_state,
 9722                    scroll_top_row,
 9723                }),
 9724                cx,
 9725            );
 9726        }
 9727    }
 9728
 9729    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9730        let buffer = self.buffer.read(cx).snapshot(cx);
 9731        let mut selection = self.selections.first::<usize>(cx);
 9732        selection.set_head(buffer.len(), SelectionGoal::None);
 9733        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9734            s.select(vec![selection]);
 9735        });
 9736    }
 9737
 9738    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9739        let end = self.buffer.read(cx).read(cx).len();
 9740        self.change_selections(None, window, cx, |s| {
 9741            s.select_ranges(vec![0..end]);
 9742        });
 9743    }
 9744
 9745    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9746        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9747        let mut selections = self.selections.all::<Point>(cx);
 9748        let max_point = display_map.buffer_snapshot.max_point();
 9749        for selection in &mut selections {
 9750            let rows = selection.spanned_rows(true, &display_map);
 9751            selection.start = Point::new(rows.start.0, 0);
 9752            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9753            selection.reversed = false;
 9754        }
 9755        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9756            s.select(selections);
 9757        });
 9758    }
 9759
 9760    pub fn split_selection_into_lines(
 9761        &mut self,
 9762        _: &SplitSelectionIntoLines,
 9763        window: &mut Window,
 9764        cx: &mut Context<Self>,
 9765    ) {
 9766        let selections = self
 9767            .selections
 9768            .all::<Point>(cx)
 9769            .into_iter()
 9770            .map(|selection| selection.start..selection.end)
 9771            .collect::<Vec<_>>();
 9772        self.unfold_ranges(&selections, true, true, cx);
 9773
 9774        let mut new_selection_ranges = Vec::new();
 9775        {
 9776            let buffer = self.buffer.read(cx).read(cx);
 9777            for selection in selections {
 9778                for row in selection.start.row..selection.end.row {
 9779                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9780                    new_selection_ranges.push(cursor..cursor);
 9781                }
 9782
 9783                let is_multiline_selection = selection.start.row != selection.end.row;
 9784                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9785                // so this action feels more ergonomic when paired with other selection operations
 9786                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9787                if !should_skip_last {
 9788                    new_selection_ranges.push(selection.end..selection.end);
 9789                }
 9790            }
 9791        }
 9792        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9793            s.select_ranges(new_selection_ranges);
 9794        });
 9795    }
 9796
 9797    pub fn add_selection_above(
 9798        &mut self,
 9799        _: &AddSelectionAbove,
 9800        window: &mut Window,
 9801        cx: &mut Context<Self>,
 9802    ) {
 9803        self.add_selection(true, window, cx);
 9804    }
 9805
 9806    pub fn add_selection_below(
 9807        &mut self,
 9808        _: &AddSelectionBelow,
 9809        window: &mut Window,
 9810        cx: &mut Context<Self>,
 9811    ) {
 9812        self.add_selection(false, window, cx);
 9813    }
 9814
 9815    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9816        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9817        let mut selections = self.selections.all::<Point>(cx);
 9818        let text_layout_details = self.text_layout_details(window);
 9819        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9820            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9821            let range = oldest_selection.display_range(&display_map).sorted();
 9822
 9823            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9824            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9825            let positions = start_x.min(end_x)..start_x.max(end_x);
 9826
 9827            selections.clear();
 9828            let mut stack = Vec::new();
 9829            for row in range.start.row().0..=range.end.row().0 {
 9830                if let Some(selection) = self.selections.build_columnar_selection(
 9831                    &display_map,
 9832                    DisplayRow(row),
 9833                    &positions,
 9834                    oldest_selection.reversed,
 9835                    &text_layout_details,
 9836                ) {
 9837                    stack.push(selection.id);
 9838                    selections.push(selection);
 9839                }
 9840            }
 9841
 9842            if above {
 9843                stack.reverse();
 9844            }
 9845
 9846            AddSelectionsState { above, stack }
 9847        });
 9848
 9849        let last_added_selection = *state.stack.last().unwrap();
 9850        let mut new_selections = Vec::new();
 9851        if above == state.above {
 9852            let end_row = if above {
 9853                DisplayRow(0)
 9854            } else {
 9855                display_map.max_point().row()
 9856            };
 9857
 9858            'outer: for selection in selections {
 9859                if selection.id == last_added_selection {
 9860                    let range = selection.display_range(&display_map).sorted();
 9861                    debug_assert_eq!(range.start.row(), range.end.row());
 9862                    let mut row = range.start.row();
 9863                    let positions =
 9864                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9865                            px(start)..px(end)
 9866                        } else {
 9867                            let start_x =
 9868                                display_map.x_for_display_point(range.start, &text_layout_details);
 9869                            let end_x =
 9870                                display_map.x_for_display_point(range.end, &text_layout_details);
 9871                            start_x.min(end_x)..start_x.max(end_x)
 9872                        };
 9873
 9874                    while row != end_row {
 9875                        if above {
 9876                            row.0 -= 1;
 9877                        } else {
 9878                            row.0 += 1;
 9879                        }
 9880
 9881                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9882                            &display_map,
 9883                            row,
 9884                            &positions,
 9885                            selection.reversed,
 9886                            &text_layout_details,
 9887                        ) {
 9888                            state.stack.push(new_selection.id);
 9889                            if above {
 9890                                new_selections.push(new_selection);
 9891                                new_selections.push(selection);
 9892                            } else {
 9893                                new_selections.push(selection);
 9894                                new_selections.push(new_selection);
 9895                            }
 9896
 9897                            continue 'outer;
 9898                        }
 9899                    }
 9900                }
 9901
 9902                new_selections.push(selection);
 9903            }
 9904        } else {
 9905            new_selections = selections;
 9906            new_selections.retain(|s| s.id != last_added_selection);
 9907            state.stack.pop();
 9908        }
 9909
 9910        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9911            s.select(new_selections);
 9912        });
 9913        if state.stack.len() > 1 {
 9914            self.add_selections_state = Some(state);
 9915        }
 9916    }
 9917
 9918    pub fn select_next_match_internal(
 9919        &mut self,
 9920        display_map: &DisplaySnapshot,
 9921        replace_newest: bool,
 9922        autoscroll: Option<Autoscroll>,
 9923        window: &mut Window,
 9924        cx: &mut Context<Self>,
 9925    ) -> Result<()> {
 9926        fn select_next_match_ranges(
 9927            this: &mut Editor,
 9928            range: Range<usize>,
 9929            replace_newest: bool,
 9930            auto_scroll: Option<Autoscroll>,
 9931            window: &mut Window,
 9932            cx: &mut Context<Editor>,
 9933        ) {
 9934            this.unfold_ranges(&[range.clone()], false, true, cx);
 9935            this.change_selections(auto_scroll, window, cx, |s| {
 9936                if replace_newest {
 9937                    s.delete(s.newest_anchor().id);
 9938                }
 9939                s.insert_range(range.clone());
 9940            });
 9941        }
 9942
 9943        let buffer = &display_map.buffer_snapshot;
 9944        let mut selections = self.selections.all::<usize>(cx);
 9945        if let Some(mut select_next_state) = self.select_next_state.take() {
 9946            let query = &select_next_state.query;
 9947            if !select_next_state.done {
 9948                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9949                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9950                let mut next_selected_range = None;
 9951
 9952                let bytes_after_last_selection =
 9953                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9954                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9955                let query_matches = query
 9956                    .stream_find_iter(bytes_after_last_selection)
 9957                    .map(|result| (last_selection.end, result))
 9958                    .chain(
 9959                        query
 9960                            .stream_find_iter(bytes_before_first_selection)
 9961                            .map(|result| (0, result)),
 9962                    );
 9963
 9964                for (start_offset, query_match) in query_matches {
 9965                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9966                    let offset_range =
 9967                        start_offset + query_match.start()..start_offset + query_match.end();
 9968                    let display_range = offset_range.start.to_display_point(display_map)
 9969                        ..offset_range.end.to_display_point(display_map);
 9970
 9971                    if !select_next_state.wordwise
 9972                        || (!movement::is_inside_word(display_map, display_range.start)
 9973                            && !movement::is_inside_word(display_map, display_range.end))
 9974                    {
 9975                        // TODO: This is n^2, because we might check all the selections
 9976                        if !selections
 9977                            .iter()
 9978                            .any(|selection| selection.range().overlaps(&offset_range))
 9979                        {
 9980                            next_selected_range = Some(offset_range);
 9981                            break;
 9982                        }
 9983                    }
 9984                }
 9985
 9986                if let Some(next_selected_range) = next_selected_range {
 9987                    select_next_match_ranges(
 9988                        self,
 9989                        next_selected_range,
 9990                        replace_newest,
 9991                        autoscroll,
 9992                        window,
 9993                        cx,
 9994                    );
 9995                } else {
 9996                    select_next_state.done = true;
 9997                }
 9998            }
 9999
10000            self.select_next_state = Some(select_next_state);
10001        } else {
10002            let mut only_carets = true;
10003            let mut same_text_selected = true;
10004            let mut selected_text = None;
10005
10006            let mut selections_iter = selections.iter().peekable();
10007            while let Some(selection) = selections_iter.next() {
10008                if selection.start != selection.end {
10009                    only_carets = false;
10010                }
10011
10012                if same_text_selected {
10013                    if selected_text.is_none() {
10014                        selected_text =
10015                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10016                    }
10017
10018                    if let Some(next_selection) = selections_iter.peek() {
10019                        if next_selection.range().len() == selection.range().len() {
10020                            let next_selected_text = buffer
10021                                .text_for_range(next_selection.range())
10022                                .collect::<String>();
10023                            if Some(next_selected_text) != selected_text {
10024                                same_text_selected = false;
10025                                selected_text = None;
10026                            }
10027                        } else {
10028                            same_text_selected = false;
10029                            selected_text = None;
10030                        }
10031                    }
10032                }
10033            }
10034
10035            if only_carets {
10036                for selection in &mut selections {
10037                    let word_range = movement::surrounding_word(
10038                        display_map,
10039                        selection.start.to_display_point(display_map),
10040                    );
10041                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
10042                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
10043                    selection.goal = SelectionGoal::None;
10044                    selection.reversed = false;
10045                    select_next_match_ranges(
10046                        self,
10047                        selection.start..selection.end,
10048                        replace_newest,
10049                        autoscroll,
10050                        window,
10051                        cx,
10052                    );
10053                }
10054
10055                if selections.len() == 1 {
10056                    let selection = selections
10057                        .last()
10058                        .expect("ensured that there's only one selection");
10059                    let query = buffer
10060                        .text_for_range(selection.start..selection.end)
10061                        .collect::<String>();
10062                    let is_empty = query.is_empty();
10063                    let select_state = SelectNextState {
10064                        query: AhoCorasick::new(&[query])?,
10065                        wordwise: true,
10066                        done: is_empty,
10067                    };
10068                    self.select_next_state = Some(select_state);
10069                } else {
10070                    self.select_next_state = None;
10071                }
10072            } else if let Some(selected_text) = selected_text {
10073                self.select_next_state = Some(SelectNextState {
10074                    query: AhoCorasick::new(&[selected_text])?,
10075                    wordwise: false,
10076                    done: false,
10077                });
10078                self.select_next_match_internal(
10079                    display_map,
10080                    replace_newest,
10081                    autoscroll,
10082                    window,
10083                    cx,
10084                )?;
10085            }
10086        }
10087        Ok(())
10088    }
10089
10090    pub fn select_all_matches(
10091        &mut self,
10092        _action: &SelectAllMatches,
10093        window: &mut Window,
10094        cx: &mut Context<Self>,
10095    ) -> Result<()> {
10096        self.push_to_selection_history();
10097        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10098
10099        self.select_next_match_internal(&display_map, false, None, window, cx)?;
10100        let Some(select_next_state) = self.select_next_state.as_mut() else {
10101            return Ok(());
10102        };
10103        if select_next_state.done {
10104            return Ok(());
10105        }
10106
10107        let mut new_selections = self.selections.all::<usize>(cx);
10108
10109        let buffer = &display_map.buffer_snapshot;
10110        let query_matches = select_next_state
10111            .query
10112            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10113
10114        for query_match in query_matches {
10115            let query_match = query_match.unwrap(); // can only fail due to I/O
10116            let offset_range = query_match.start()..query_match.end();
10117            let display_range = offset_range.start.to_display_point(&display_map)
10118                ..offset_range.end.to_display_point(&display_map);
10119
10120            if !select_next_state.wordwise
10121                || (!movement::is_inside_word(&display_map, display_range.start)
10122                    && !movement::is_inside_word(&display_map, display_range.end))
10123            {
10124                self.selections.change_with(cx, |selections| {
10125                    new_selections.push(Selection {
10126                        id: selections.new_selection_id(),
10127                        start: offset_range.start,
10128                        end: offset_range.end,
10129                        reversed: false,
10130                        goal: SelectionGoal::None,
10131                    });
10132                });
10133            }
10134        }
10135
10136        new_selections.sort_by_key(|selection| selection.start);
10137        let mut ix = 0;
10138        while ix + 1 < new_selections.len() {
10139            let current_selection = &new_selections[ix];
10140            let next_selection = &new_selections[ix + 1];
10141            if current_selection.range().overlaps(&next_selection.range()) {
10142                if current_selection.id < next_selection.id {
10143                    new_selections.remove(ix + 1);
10144                } else {
10145                    new_selections.remove(ix);
10146                }
10147            } else {
10148                ix += 1;
10149            }
10150        }
10151
10152        let reversed = self.selections.oldest::<usize>(cx).reversed;
10153
10154        for selection in new_selections.iter_mut() {
10155            selection.reversed = reversed;
10156        }
10157
10158        select_next_state.done = true;
10159        self.unfold_ranges(
10160            &new_selections
10161                .iter()
10162                .map(|selection| selection.range())
10163                .collect::<Vec<_>>(),
10164            false,
10165            false,
10166            cx,
10167        );
10168        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10169            selections.select(new_selections)
10170        });
10171
10172        Ok(())
10173    }
10174
10175    pub fn select_next(
10176        &mut self,
10177        action: &SelectNext,
10178        window: &mut Window,
10179        cx: &mut Context<Self>,
10180    ) -> Result<()> {
10181        self.push_to_selection_history();
10182        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10183        self.select_next_match_internal(
10184            &display_map,
10185            action.replace_newest,
10186            Some(Autoscroll::newest()),
10187            window,
10188            cx,
10189        )?;
10190        Ok(())
10191    }
10192
10193    pub fn select_previous(
10194        &mut self,
10195        action: &SelectPrevious,
10196        window: &mut Window,
10197        cx: &mut Context<Self>,
10198    ) -> Result<()> {
10199        self.push_to_selection_history();
10200        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10201        let buffer = &display_map.buffer_snapshot;
10202        let mut selections = self.selections.all::<usize>(cx);
10203        if let Some(mut select_prev_state) = self.select_prev_state.take() {
10204            let query = &select_prev_state.query;
10205            if !select_prev_state.done {
10206                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10207                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10208                let mut next_selected_range = None;
10209                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10210                let bytes_before_last_selection =
10211                    buffer.reversed_bytes_in_range(0..last_selection.start);
10212                let bytes_after_first_selection =
10213                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10214                let query_matches = query
10215                    .stream_find_iter(bytes_before_last_selection)
10216                    .map(|result| (last_selection.start, result))
10217                    .chain(
10218                        query
10219                            .stream_find_iter(bytes_after_first_selection)
10220                            .map(|result| (buffer.len(), result)),
10221                    );
10222                for (end_offset, query_match) in query_matches {
10223                    let query_match = query_match.unwrap(); // can only fail due to I/O
10224                    let offset_range =
10225                        end_offset - query_match.end()..end_offset - query_match.start();
10226                    let display_range = offset_range.start.to_display_point(&display_map)
10227                        ..offset_range.end.to_display_point(&display_map);
10228
10229                    if !select_prev_state.wordwise
10230                        || (!movement::is_inside_word(&display_map, display_range.start)
10231                            && !movement::is_inside_word(&display_map, display_range.end))
10232                    {
10233                        next_selected_range = Some(offset_range);
10234                        break;
10235                    }
10236                }
10237
10238                if let Some(next_selected_range) = next_selected_range {
10239                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10240                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10241                        if action.replace_newest {
10242                            s.delete(s.newest_anchor().id);
10243                        }
10244                        s.insert_range(next_selected_range);
10245                    });
10246                } else {
10247                    select_prev_state.done = true;
10248                }
10249            }
10250
10251            self.select_prev_state = Some(select_prev_state);
10252        } else {
10253            let mut only_carets = true;
10254            let mut same_text_selected = true;
10255            let mut selected_text = None;
10256
10257            let mut selections_iter = selections.iter().peekable();
10258            while let Some(selection) = selections_iter.next() {
10259                if selection.start != selection.end {
10260                    only_carets = false;
10261                }
10262
10263                if same_text_selected {
10264                    if selected_text.is_none() {
10265                        selected_text =
10266                            Some(buffer.text_for_range(selection.range()).collect::<String>());
10267                    }
10268
10269                    if let Some(next_selection) = selections_iter.peek() {
10270                        if next_selection.range().len() == selection.range().len() {
10271                            let next_selected_text = buffer
10272                                .text_for_range(next_selection.range())
10273                                .collect::<String>();
10274                            if Some(next_selected_text) != selected_text {
10275                                same_text_selected = false;
10276                                selected_text = None;
10277                            }
10278                        } else {
10279                            same_text_selected = false;
10280                            selected_text = None;
10281                        }
10282                    }
10283                }
10284            }
10285
10286            if only_carets {
10287                for selection in &mut selections {
10288                    let word_range = movement::surrounding_word(
10289                        &display_map,
10290                        selection.start.to_display_point(&display_map),
10291                    );
10292                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10293                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10294                    selection.goal = SelectionGoal::None;
10295                    selection.reversed = false;
10296                }
10297                if selections.len() == 1 {
10298                    let selection = selections
10299                        .last()
10300                        .expect("ensured that there's only one selection");
10301                    let query = buffer
10302                        .text_for_range(selection.start..selection.end)
10303                        .collect::<String>();
10304                    let is_empty = query.is_empty();
10305                    let select_state = SelectNextState {
10306                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10307                        wordwise: true,
10308                        done: is_empty,
10309                    };
10310                    self.select_prev_state = Some(select_state);
10311                } else {
10312                    self.select_prev_state = None;
10313                }
10314
10315                self.unfold_ranges(
10316                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10317                    false,
10318                    true,
10319                    cx,
10320                );
10321                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10322                    s.select(selections);
10323                });
10324            } else if let Some(selected_text) = selected_text {
10325                self.select_prev_state = Some(SelectNextState {
10326                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10327                    wordwise: false,
10328                    done: false,
10329                });
10330                self.select_previous(action, window, cx)?;
10331            }
10332        }
10333        Ok(())
10334    }
10335
10336    pub fn toggle_comments(
10337        &mut self,
10338        action: &ToggleComments,
10339        window: &mut Window,
10340        cx: &mut Context<Self>,
10341    ) {
10342        if self.read_only(cx) {
10343            return;
10344        }
10345        let text_layout_details = &self.text_layout_details(window);
10346        self.transact(window, cx, |this, window, cx| {
10347            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10348            let mut edits = Vec::new();
10349            let mut selection_edit_ranges = Vec::new();
10350            let mut last_toggled_row = None;
10351            let snapshot = this.buffer.read(cx).read(cx);
10352            let empty_str: Arc<str> = Arc::default();
10353            let mut suffixes_inserted = Vec::new();
10354            let ignore_indent = action.ignore_indent;
10355
10356            fn comment_prefix_range(
10357                snapshot: &MultiBufferSnapshot,
10358                row: MultiBufferRow,
10359                comment_prefix: &str,
10360                comment_prefix_whitespace: &str,
10361                ignore_indent: bool,
10362            ) -> Range<Point> {
10363                let indent_size = if ignore_indent {
10364                    0
10365                } else {
10366                    snapshot.indent_size_for_line(row).len
10367                };
10368
10369                let start = Point::new(row.0, indent_size);
10370
10371                let mut line_bytes = snapshot
10372                    .bytes_in_range(start..snapshot.max_point())
10373                    .flatten()
10374                    .copied();
10375
10376                // If this line currently begins with the line comment prefix, then record
10377                // the range containing the prefix.
10378                if line_bytes
10379                    .by_ref()
10380                    .take(comment_prefix.len())
10381                    .eq(comment_prefix.bytes())
10382                {
10383                    // Include any whitespace that matches the comment prefix.
10384                    let matching_whitespace_len = line_bytes
10385                        .zip(comment_prefix_whitespace.bytes())
10386                        .take_while(|(a, b)| a == b)
10387                        .count() as u32;
10388                    let end = Point::new(
10389                        start.row,
10390                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10391                    );
10392                    start..end
10393                } else {
10394                    start..start
10395                }
10396            }
10397
10398            fn comment_suffix_range(
10399                snapshot: &MultiBufferSnapshot,
10400                row: MultiBufferRow,
10401                comment_suffix: &str,
10402                comment_suffix_has_leading_space: bool,
10403            ) -> Range<Point> {
10404                let end = Point::new(row.0, snapshot.line_len(row));
10405                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10406
10407                let mut line_end_bytes = snapshot
10408                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10409                    .flatten()
10410                    .copied();
10411
10412                let leading_space_len = if suffix_start_column > 0
10413                    && line_end_bytes.next() == Some(b' ')
10414                    && comment_suffix_has_leading_space
10415                {
10416                    1
10417                } else {
10418                    0
10419                };
10420
10421                // If this line currently begins with the line comment prefix, then record
10422                // the range containing the prefix.
10423                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10424                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
10425                    start..end
10426                } else {
10427                    end..end
10428                }
10429            }
10430
10431            // TODO: Handle selections that cross excerpts
10432            for selection in &mut selections {
10433                let start_column = snapshot
10434                    .indent_size_for_line(MultiBufferRow(selection.start.row))
10435                    .len;
10436                let language = if let Some(language) =
10437                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10438                {
10439                    language
10440                } else {
10441                    continue;
10442                };
10443
10444                selection_edit_ranges.clear();
10445
10446                // If multiple selections contain a given row, avoid processing that
10447                // row more than once.
10448                let mut start_row = MultiBufferRow(selection.start.row);
10449                if last_toggled_row == Some(start_row) {
10450                    start_row = start_row.next_row();
10451                }
10452                let end_row =
10453                    if selection.end.row > selection.start.row && selection.end.column == 0 {
10454                        MultiBufferRow(selection.end.row - 1)
10455                    } else {
10456                        MultiBufferRow(selection.end.row)
10457                    };
10458                last_toggled_row = Some(end_row);
10459
10460                if start_row > end_row {
10461                    continue;
10462                }
10463
10464                // If the language has line comments, toggle those.
10465                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10466
10467                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10468                if ignore_indent {
10469                    full_comment_prefixes = full_comment_prefixes
10470                        .into_iter()
10471                        .map(|s| Arc::from(s.trim_end()))
10472                        .collect();
10473                }
10474
10475                if !full_comment_prefixes.is_empty() {
10476                    let first_prefix = full_comment_prefixes
10477                        .first()
10478                        .expect("prefixes is non-empty");
10479                    let prefix_trimmed_lengths = full_comment_prefixes
10480                        .iter()
10481                        .map(|p| p.trim_end_matches(' ').len())
10482                        .collect::<SmallVec<[usize; 4]>>();
10483
10484                    let mut all_selection_lines_are_comments = true;
10485
10486                    for row in start_row.0..=end_row.0 {
10487                        let row = MultiBufferRow(row);
10488                        if start_row < end_row && snapshot.is_line_blank(row) {
10489                            continue;
10490                        }
10491
10492                        let prefix_range = full_comment_prefixes
10493                            .iter()
10494                            .zip(prefix_trimmed_lengths.iter().copied())
10495                            .map(|(prefix, trimmed_prefix_len)| {
10496                                comment_prefix_range(
10497                                    snapshot.deref(),
10498                                    row,
10499                                    &prefix[..trimmed_prefix_len],
10500                                    &prefix[trimmed_prefix_len..],
10501                                    ignore_indent,
10502                                )
10503                            })
10504                            .max_by_key(|range| range.end.column - range.start.column)
10505                            .expect("prefixes is non-empty");
10506
10507                        if prefix_range.is_empty() {
10508                            all_selection_lines_are_comments = false;
10509                        }
10510
10511                        selection_edit_ranges.push(prefix_range);
10512                    }
10513
10514                    if all_selection_lines_are_comments {
10515                        edits.extend(
10516                            selection_edit_ranges
10517                                .iter()
10518                                .cloned()
10519                                .map(|range| (range, empty_str.clone())),
10520                        );
10521                    } else {
10522                        let min_column = selection_edit_ranges
10523                            .iter()
10524                            .map(|range| range.start.column)
10525                            .min()
10526                            .unwrap_or(0);
10527                        edits.extend(selection_edit_ranges.iter().map(|range| {
10528                            let position = Point::new(range.start.row, min_column);
10529                            (position..position, first_prefix.clone())
10530                        }));
10531                    }
10532                } else if let Some((full_comment_prefix, comment_suffix)) =
10533                    language.block_comment_delimiters()
10534                {
10535                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10536                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10537                    let prefix_range = comment_prefix_range(
10538                        snapshot.deref(),
10539                        start_row,
10540                        comment_prefix,
10541                        comment_prefix_whitespace,
10542                        ignore_indent,
10543                    );
10544                    let suffix_range = comment_suffix_range(
10545                        snapshot.deref(),
10546                        end_row,
10547                        comment_suffix.trim_start_matches(' '),
10548                        comment_suffix.starts_with(' '),
10549                    );
10550
10551                    if prefix_range.is_empty() || suffix_range.is_empty() {
10552                        edits.push((
10553                            prefix_range.start..prefix_range.start,
10554                            full_comment_prefix.clone(),
10555                        ));
10556                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10557                        suffixes_inserted.push((end_row, comment_suffix.len()));
10558                    } else {
10559                        edits.push((prefix_range, empty_str.clone()));
10560                        edits.push((suffix_range, empty_str.clone()));
10561                    }
10562                } else {
10563                    continue;
10564                }
10565            }
10566
10567            drop(snapshot);
10568            this.buffer.update(cx, |buffer, cx| {
10569                buffer.edit(edits, None, cx);
10570            });
10571
10572            // Adjust selections so that they end before any comment suffixes that
10573            // were inserted.
10574            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10575            let mut selections = this.selections.all::<Point>(cx);
10576            let snapshot = this.buffer.read(cx).read(cx);
10577            for selection in &mut selections {
10578                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10579                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10580                        Ordering::Less => {
10581                            suffixes_inserted.next();
10582                            continue;
10583                        }
10584                        Ordering::Greater => break,
10585                        Ordering::Equal => {
10586                            if selection.end.column == snapshot.line_len(row) {
10587                                if selection.is_empty() {
10588                                    selection.start.column -= suffix_len as u32;
10589                                }
10590                                selection.end.column -= suffix_len as u32;
10591                            }
10592                            break;
10593                        }
10594                    }
10595                }
10596            }
10597
10598            drop(snapshot);
10599            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10600                s.select(selections)
10601            });
10602
10603            let selections = this.selections.all::<Point>(cx);
10604            let selections_on_single_row = selections.windows(2).all(|selections| {
10605                selections[0].start.row == selections[1].start.row
10606                    && selections[0].end.row == selections[1].end.row
10607                    && selections[0].start.row == selections[0].end.row
10608            });
10609            let selections_selecting = selections
10610                .iter()
10611                .any(|selection| selection.start != selection.end);
10612            let advance_downwards = action.advance_downwards
10613                && selections_on_single_row
10614                && !selections_selecting
10615                && !matches!(this.mode, EditorMode::SingleLine { .. });
10616
10617            if advance_downwards {
10618                let snapshot = this.buffer.read(cx).snapshot(cx);
10619
10620                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10621                    s.move_cursors_with(|display_snapshot, display_point, _| {
10622                        let mut point = display_point.to_point(display_snapshot);
10623                        point.row += 1;
10624                        point = snapshot.clip_point(point, Bias::Left);
10625                        let display_point = point.to_display_point(display_snapshot);
10626                        let goal = SelectionGoal::HorizontalPosition(
10627                            display_snapshot
10628                                .x_for_display_point(display_point, text_layout_details)
10629                                .into(),
10630                        );
10631                        (display_point, goal)
10632                    })
10633                });
10634            }
10635        });
10636    }
10637
10638    pub fn select_enclosing_symbol(
10639        &mut self,
10640        _: &SelectEnclosingSymbol,
10641        window: &mut Window,
10642        cx: &mut Context<Self>,
10643    ) {
10644        let buffer = self.buffer.read(cx).snapshot(cx);
10645        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10646
10647        fn update_selection(
10648            selection: &Selection<usize>,
10649            buffer_snap: &MultiBufferSnapshot,
10650        ) -> Option<Selection<usize>> {
10651            let cursor = selection.head();
10652            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10653            for symbol in symbols.iter().rev() {
10654                let start = symbol.range.start.to_offset(buffer_snap);
10655                let end = symbol.range.end.to_offset(buffer_snap);
10656                let new_range = start..end;
10657                if start < selection.start || end > selection.end {
10658                    return Some(Selection {
10659                        id: selection.id,
10660                        start: new_range.start,
10661                        end: new_range.end,
10662                        goal: SelectionGoal::None,
10663                        reversed: selection.reversed,
10664                    });
10665                }
10666            }
10667            None
10668        }
10669
10670        let mut selected_larger_symbol = false;
10671        let new_selections = old_selections
10672            .iter()
10673            .map(|selection| match update_selection(selection, &buffer) {
10674                Some(new_selection) => {
10675                    if new_selection.range() != selection.range() {
10676                        selected_larger_symbol = true;
10677                    }
10678                    new_selection
10679                }
10680                None => selection.clone(),
10681            })
10682            .collect::<Vec<_>>();
10683
10684        if selected_larger_symbol {
10685            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10686                s.select(new_selections);
10687            });
10688        }
10689    }
10690
10691    pub fn select_larger_syntax_node(
10692        &mut self,
10693        _: &SelectLargerSyntaxNode,
10694        window: &mut Window,
10695        cx: &mut Context<Self>,
10696    ) {
10697        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10698        let buffer = self.buffer.read(cx).snapshot(cx);
10699        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10700
10701        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10702        let mut selected_larger_node = false;
10703        let new_selections = old_selections
10704            .iter()
10705            .map(|selection| {
10706                let old_range = selection.start..selection.end;
10707                let mut new_range = old_range.clone();
10708                let mut new_node = None;
10709                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10710                {
10711                    new_node = Some(node);
10712                    new_range = containing_range;
10713                    if !display_map.intersects_fold(new_range.start)
10714                        && !display_map.intersects_fold(new_range.end)
10715                    {
10716                        break;
10717                    }
10718                }
10719
10720                if let Some(node) = new_node {
10721                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10722                    // nodes. Parent and grandparent are also logged because this operation will not
10723                    // visit nodes that have the same range as their parent.
10724                    log::info!("Node: {node:?}");
10725                    let parent = node.parent();
10726                    log::info!("Parent: {parent:?}");
10727                    let grandparent = parent.and_then(|x| x.parent());
10728                    log::info!("Grandparent: {grandparent:?}");
10729                }
10730
10731                selected_larger_node |= new_range != old_range;
10732                Selection {
10733                    id: selection.id,
10734                    start: new_range.start,
10735                    end: new_range.end,
10736                    goal: SelectionGoal::None,
10737                    reversed: selection.reversed,
10738                }
10739            })
10740            .collect::<Vec<_>>();
10741
10742        if selected_larger_node {
10743            stack.push(old_selections);
10744            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10745                s.select(new_selections);
10746            });
10747        }
10748        self.select_larger_syntax_node_stack = stack;
10749    }
10750
10751    pub fn select_smaller_syntax_node(
10752        &mut self,
10753        _: &SelectSmallerSyntaxNode,
10754        window: &mut Window,
10755        cx: &mut Context<Self>,
10756    ) {
10757        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10758        if let Some(selections) = stack.pop() {
10759            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10760                s.select(selections.to_vec());
10761            });
10762        }
10763        self.select_larger_syntax_node_stack = stack;
10764    }
10765
10766    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10767        if !EditorSettings::get_global(cx).gutter.runnables {
10768            self.clear_tasks();
10769            return Task::ready(());
10770        }
10771        let project = self.project.as_ref().map(Entity::downgrade);
10772        cx.spawn_in(window, |this, mut cx| async move {
10773            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10774            let Some(project) = project.and_then(|p| p.upgrade()) else {
10775                return;
10776            };
10777            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10778                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10779            }) else {
10780                return;
10781            };
10782
10783            let hide_runnables = project
10784                .update(&mut cx, |project, cx| {
10785                    // Do not display any test indicators in non-dev server remote projects.
10786                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10787                })
10788                .unwrap_or(true);
10789            if hide_runnables {
10790                return;
10791            }
10792            let new_rows =
10793                cx.background_spawn({
10794                    let snapshot = display_snapshot.clone();
10795                    async move {
10796                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10797                    }
10798                })
10799                    .await;
10800
10801            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10802            this.update(&mut cx, |this, _| {
10803                this.clear_tasks();
10804                for (key, value) in rows {
10805                    this.insert_tasks(key, value);
10806                }
10807            })
10808            .ok();
10809        })
10810    }
10811    fn fetch_runnable_ranges(
10812        snapshot: &DisplaySnapshot,
10813        range: Range<Anchor>,
10814    ) -> Vec<language::RunnableRange> {
10815        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10816    }
10817
10818    fn runnable_rows(
10819        project: Entity<Project>,
10820        snapshot: DisplaySnapshot,
10821        runnable_ranges: Vec<RunnableRange>,
10822        mut cx: AsyncWindowContext,
10823    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10824        runnable_ranges
10825            .into_iter()
10826            .filter_map(|mut runnable| {
10827                let tasks = cx
10828                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10829                    .ok()?;
10830                if tasks.is_empty() {
10831                    return None;
10832                }
10833
10834                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10835
10836                let row = snapshot
10837                    .buffer_snapshot
10838                    .buffer_line_for_row(MultiBufferRow(point.row))?
10839                    .1
10840                    .start
10841                    .row;
10842
10843                let context_range =
10844                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10845                Some((
10846                    (runnable.buffer_id, row),
10847                    RunnableTasks {
10848                        templates: tasks,
10849                        offset: snapshot
10850                            .buffer_snapshot
10851                            .anchor_before(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 !split
11604                        && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11605                    {
11606                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11607                    } else {
11608                        window.defer(cx, move |window, cx| {
11609                            let target_editor: Entity<Self> =
11610                                workspace.update(cx, |workspace, cx| {
11611                                    let pane = if split {
11612                                        workspace.adjacent_pane(window, cx)
11613                                    } else {
11614                                        workspace.active_pane().clone()
11615                                    };
11616
11617                                    workspace.open_project_item(
11618                                        pane,
11619                                        target.buffer.clone(),
11620                                        true,
11621                                        true,
11622                                        window,
11623                                        cx,
11624                                    )
11625                                });
11626                            target_editor.update(cx, |target_editor, cx| {
11627                                // When selecting a definition in a different buffer, disable the nav history
11628                                // to avoid creating a history entry at the previous cursor location.
11629                                pane.update(cx, |pane, _| pane.disable_history());
11630                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11631                                pane.update(cx, |pane, _| pane.enable_history());
11632                            });
11633                        });
11634                    }
11635                    Navigated::Yes
11636                })
11637            })
11638        } else if !definitions.is_empty() {
11639            cx.spawn_in(window, |editor, mut cx| async move {
11640                let (title, location_tasks, workspace) = editor
11641                    .update_in(&mut cx, |editor, window, cx| {
11642                        let tab_kind = match kind {
11643                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11644                            _ => "Definitions",
11645                        };
11646                        let title = definitions
11647                            .iter()
11648                            .find_map(|definition| match definition {
11649                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11650                                    let buffer = origin.buffer.read(cx);
11651                                    format!(
11652                                        "{} for {}",
11653                                        tab_kind,
11654                                        buffer
11655                                            .text_for_range(origin.range.clone())
11656                                            .collect::<String>()
11657                                    )
11658                                }),
11659                                HoverLink::InlayHint(_, _) => None,
11660                                HoverLink::Url(_) => None,
11661                                HoverLink::File(_) => None,
11662                            })
11663                            .unwrap_or(tab_kind.to_string());
11664                        let location_tasks = definitions
11665                            .into_iter()
11666                            .map(|definition| match definition {
11667                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11668                                HoverLink::InlayHint(lsp_location, server_id) => editor
11669                                    .compute_target_location(lsp_location, server_id, window, cx),
11670                                HoverLink::Url(_) => Task::ready(Ok(None)),
11671                                HoverLink::File(_) => Task::ready(Ok(None)),
11672                            })
11673                            .collect::<Vec<_>>();
11674                        (title, location_tasks, editor.workspace().clone())
11675                    })
11676                    .context("location tasks preparation")?;
11677
11678                let locations = future::join_all(location_tasks)
11679                    .await
11680                    .into_iter()
11681                    .filter_map(|location| location.transpose())
11682                    .collect::<Result<_>>()
11683                    .context("location tasks")?;
11684
11685                let Some(workspace) = workspace else {
11686                    return Ok(Navigated::No);
11687                };
11688                let opened = workspace
11689                    .update_in(&mut cx, |workspace, window, cx| {
11690                        Self::open_locations_in_multibuffer(
11691                            workspace,
11692                            locations,
11693                            title,
11694                            split,
11695                            MultibufferSelectionMode::First,
11696                            window,
11697                            cx,
11698                        )
11699                    })
11700                    .ok();
11701
11702                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11703            })
11704        } else {
11705            Task::ready(Ok(Navigated::No))
11706        }
11707    }
11708
11709    fn compute_target_location(
11710        &self,
11711        lsp_location: lsp::Location,
11712        server_id: LanguageServerId,
11713        window: &mut Window,
11714        cx: &mut Context<Self>,
11715    ) -> Task<anyhow::Result<Option<Location>>> {
11716        let Some(project) = self.project.clone() else {
11717            return Task::ready(Ok(None));
11718        };
11719
11720        cx.spawn_in(window, move |editor, mut cx| async move {
11721            let location_task = editor.update(&mut cx, |_, cx| {
11722                project.update(cx, |project, cx| {
11723                    let language_server_name = project
11724                        .language_server_statuses(cx)
11725                        .find(|(id, _)| server_id == *id)
11726                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11727                    language_server_name.map(|language_server_name| {
11728                        project.open_local_buffer_via_lsp(
11729                            lsp_location.uri.clone(),
11730                            server_id,
11731                            language_server_name,
11732                            cx,
11733                        )
11734                    })
11735                })
11736            })?;
11737            let location = match location_task {
11738                Some(task) => Some({
11739                    let target_buffer_handle = task.await.context("open local buffer")?;
11740                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11741                        let target_start = target_buffer
11742                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11743                        let target_end = target_buffer
11744                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11745                        target_buffer.anchor_after(target_start)
11746                            ..target_buffer.anchor_before(target_end)
11747                    })?;
11748                    Location {
11749                        buffer: target_buffer_handle,
11750                        range,
11751                    }
11752                }),
11753                None => None,
11754            };
11755            Ok(location)
11756        })
11757    }
11758
11759    pub fn find_all_references(
11760        &mut self,
11761        _: &FindAllReferences,
11762        window: &mut Window,
11763        cx: &mut Context<Self>,
11764    ) -> Option<Task<Result<Navigated>>> {
11765        let selection = self.selections.newest::<usize>(cx);
11766        let multi_buffer = self.buffer.read(cx);
11767        let head = selection.head();
11768
11769        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11770        let head_anchor = multi_buffer_snapshot.anchor_at(
11771            head,
11772            if head < selection.tail() {
11773                Bias::Right
11774            } else {
11775                Bias::Left
11776            },
11777        );
11778
11779        match self
11780            .find_all_references_task_sources
11781            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11782        {
11783            Ok(_) => {
11784                log::info!(
11785                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11786                );
11787                return None;
11788            }
11789            Err(i) => {
11790                self.find_all_references_task_sources.insert(i, head_anchor);
11791            }
11792        }
11793
11794        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11795        let workspace = self.workspace()?;
11796        let project = workspace.read(cx).project().clone();
11797        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11798        Some(cx.spawn_in(window, |editor, mut cx| async move {
11799            let _cleanup = defer({
11800                let mut cx = cx.clone();
11801                move || {
11802                    let _ = editor.update(&mut cx, |editor, _| {
11803                        if let Ok(i) =
11804                            editor
11805                                .find_all_references_task_sources
11806                                .binary_search_by(|anchor| {
11807                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11808                                })
11809                        {
11810                            editor.find_all_references_task_sources.remove(i);
11811                        }
11812                    });
11813                }
11814            });
11815
11816            let locations = references.await?;
11817            if locations.is_empty() {
11818                return anyhow::Ok(Navigated::No);
11819            }
11820
11821            workspace.update_in(&mut cx, |workspace, window, cx| {
11822                let title = locations
11823                    .first()
11824                    .as_ref()
11825                    .map(|location| {
11826                        let buffer = location.buffer.read(cx);
11827                        format!(
11828                            "References to `{}`",
11829                            buffer
11830                                .text_for_range(location.range.clone())
11831                                .collect::<String>()
11832                        )
11833                    })
11834                    .unwrap();
11835                Self::open_locations_in_multibuffer(
11836                    workspace,
11837                    locations,
11838                    title,
11839                    false,
11840                    MultibufferSelectionMode::First,
11841                    window,
11842                    cx,
11843                );
11844                Navigated::Yes
11845            })
11846        }))
11847    }
11848
11849    /// Opens a multibuffer with the given project locations in it
11850    pub fn open_locations_in_multibuffer(
11851        workspace: &mut Workspace,
11852        mut locations: Vec<Location>,
11853        title: String,
11854        split: bool,
11855        multibuffer_selection_mode: MultibufferSelectionMode,
11856        window: &mut Window,
11857        cx: &mut Context<Workspace>,
11858    ) {
11859        // If there are multiple definitions, open them in a multibuffer
11860        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11861        let mut locations = locations.into_iter().peekable();
11862        let mut ranges = Vec::new();
11863        let capability = workspace.project().read(cx).capability();
11864
11865        let excerpt_buffer = cx.new(|cx| {
11866            let mut multibuffer = MultiBuffer::new(capability);
11867            while let Some(location) = locations.next() {
11868                let buffer = location.buffer.read(cx);
11869                let mut ranges_for_buffer = Vec::new();
11870                let range = location.range.to_offset(buffer);
11871                ranges_for_buffer.push(range.clone());
11872
11873                while let Some(next_location) = locations.peek() {
11874                    if next_location.buffer == location.buffer {
11875                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11876                        locations.next();
11877                    } else {
11878                        break;
11879                    }
11880                }
11881
11882                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11883                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11884                    location.buffer.clone(),
11885                    ranges_for_buffer,
11886                    DEFAULT_MULTIBUFFER_CONTEXT,
11887                    cx,
11888                ))
11889            }
11890
11891            multibuffer.with_title(title)
11892        });
11893
11894        let editor = cx.new(|cx| {
11895            Editor::for_multibuffer(
11896                excerpt_buffer,
11897                Some(workspace.project().clone()),
11898                true,
11899                window,
11900                cx,
11901            )
11902        });
11903        editor.update(cx, |editor, cx| {
11904            match multibuffer_selection_mode {
11905                MultibufferSelectionMode::First => {
11906                    if let Some(first_range) = ranges.first() {
11907                        editor.change_selections(None, window, cx, |selections| {
11908                            selections.clear_disjoint();
11909                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11910                        });
11911                    }
11912                    editor.highlight_background::<Self>(
11913                        &ranges,
11914                        |theme| theme.editor_highlighted_line_background,
11915                        cx,
11916                    );
11917                }
11918                MultibufferSelectionMode::All => {
11919                    editor.change_selections(None, window, cx, |selections| {
11920                        selections.clear_disjoint();
11921                        selections.select_anchor_ranges(ranges);
11922                    });
11923                }
11924            }
11925            editor.register_buffers_with_language_servers(cx);
11926        });
11927
11928        let item = Box::new(editor);
11929        let item_id = item.item_id();
11930
11931        if split {
11932            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11933        } else {
11934            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11935                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11936                    pane.close_current_preview_item(window, cx)
11937                } else {
11938                    None
11939                }
11940            });
11941            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11942        }
11943        workspace.active_pane().update(cx, |pane, cx| {
11944            pane.set_preview_item_id(Some(item_id), cx);
11945        });
11946    }
11947
11948    pub fn rename(
11949        &mut self,
11950        _: &Rename,
11951        window: &mut Window,
11952        cx: &mut Context<Self>,
11953    ) -> Option<Task<Result<()>>> {
11954        use language::ToOffset as _;
11955
11956        let provider = self.semantics_provider.clone()?;
11957        let selection = self.selections.newest_anchor().clone();
11958        let (cursor_buffer, cursor_buffer_position) = self
11959            .buffer
11960            .read(cx)
11961            .text_anchor_for_position(selection.head(), cx)?;
11962        let (tail_buffer, cursor_buffer_position_end) = self
11963            .buffer
11964            .read(cx)
11965            .text_anchor_for_position(selection.tail(), cx)?;
11966        if tail_buffer != cursor_buffer {
11967            return None;
11968        }
11969
11970        let snapshot = cursor_buffer.read(cx).snapshot();
11971        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11972        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11973        let prepare_rename = provider
11974            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11975            .unwrap_or_else(|| Task::ready(Ok(None)));
11976        drop(snapshot);
11977
11978        Some(cx.spawn_in(window, |this, mut cx| async move {
11979            let rename_range = if let Some(range) = prepare_rename.await? {
11980                Some(range)
11981            } else {
11982                this.update(&mut cx, |this, cx| {
11983                    let buffer = this.buffer.read(cx).snapshot(cx);
11984                    let mut buffer_highlights = this
11985                        .document_highlights_for_position(selection.head(), &buffer)
11986                        .filter(|highlight| {
11987                            highlight.start.excerpt_id == selection.head().excerpt_id
11988                                && highlight.end.excerpt_id == selection.head().excerpt_id
11989                        });
11990                    buffer_highlights
11991                        .next()
11992                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11993                })?
11994            };
11995            if let Some(rename_range) = rename_range {
11996                this.update_in(&mut cx, |this, window, cx| {
11997                    let snapshot = cursor_buffer.read(cx).snapshot();
11998                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11999                    let cursor_offset_in_rename_range =
12000                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12001                    let cursor_offset_in_rename_range_end =
12002                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12003
12004                    this.take_rename(false, window, cx);
12005                    let buffer = this.buffer.read(cx).read(cx);
12006                    let cursor_offset = selection.head().to_offset(&buffer);
12007                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12008                    let rename_end = rename_start + rename_buffer_range.len();
12009                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12010                    let mut old_highlight_id = None;
12011                    let old_name: Arc<str> = buffer
12012                        .chunks(rename_start..rename_end, true)
12013                        .map(|chunk| {
12014                            if old_highlight_id.is_none() {
12015                                old_highlight_id = chunk.syntax_highlight_id;
12016                            }
12017                            chunk.text
12018                        })
12019                        .collect::<String>()
12020                        .into();
12021
12022                    drop(buffer);
12023
12024                    // Position the selection in the rename editor so that it matches the current selection.
12025                    this.show_local_selections = false;
12026                    let rename_editor = cx.new(|cx| {
12027                        let mut editor = Editor::single_line(window, cx);
12028                        editor.buffer.update(cx, |buffer, cx| {
12029                            buffer.edit([(0..0, old_name.clone())], None, cx)
12030                        });
12031                        let rename_selection_range = match cursor_offset_in_rename_range
12032                            .cmp(&cursor_offset_in_rename_range_end)
12033                        {
12034                            Ordering::Equal => {
12035                                editor.select_all(&SelectAll, window, cx);
12036                                return editor;
12037                            }
12038                            Ordering::Less => {
12039                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12040                            }
12041                            Ordering::Greater => {
12042                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12043                            }
12044                        };
12045                        if rename_selection_range.end > old_name.len() {
12046                            editor.select_all(&SelectAll, window, cx);
12047                        } else {
12048                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12049                                s.select_ranges([rename_selection_range]);
12050                            });
12051                        }
12052                        editor
12053                    });
12054                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12055                        if e == &EditorEvent::Focused {
12056                            cx.emit(EditorEvent::FocusedIn)
12057                        }
12058                    })
12059                    .detach();
12060
12061                    let write_highlights =
12062                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12063                    let read_highlights =
12064                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
12065                    let ranges = write_highlights
12066                        .iter()
12067                        .flat_map(|(_, ranges)| ranges.iter())
12068                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12069                        .cloned()
12070                        .collect();
12071
12072                    this.highlight_text::<Rename>(
12073                        ranges,
12074                        HighlightStyle {
12075                            fade_out: Some(0.6),
12076                            ..Default::default()
12077                        },
12078                        cx,
12079                    );
12080                    let rename_focus_handle = rename_editor.focus_handle(cx);
12081                    window.focus(&rename_focus_handle);
12082                    let block_id = this.insert_blocks(
12083                        [BlockProperties {
12084                            style: BlockStyle::Flex,
12085                            placement: BlockPlacement::Below(range.start),
12086                            height: 1,
12087                            render: Arc::new({
12088                                let rename_editor = rename_editor.clone();
12089                                move |cx: &mut BlockContext| {
12090                                    let mut text_style = cx.editor_style.text.clone();
12091                                    if let Some(highlight_style) = old_highlight_id
12092                                        .and_then(|h| h.style(&cx.editor_style.syntax))
12093                                    {
12094                                        text_style = text_style.highlight(highlight_style);
12095                                    }
12096                                    div()
12097                                        .block_mouse_down()
12098                                        .pl(cx.anchor_x)
12099                                        .child(EditorElement::new(
12100                                            &rename_editor,
12101                                            EditorStyle {
12102                                                background: cx.theme().system().transparent,
12103                                                local_player: cx.editor_style.local_player,
12104                                                text: text_style,
12105                                                scrollbar_width: cx.editor_style.scrollbar_width,
12106                                                syntax: cx.editor_style.syntax.clone(),
12107                                                status: cx.editor_style.status.clone(),
12108                                                inlay_hints_style: HighlightStyle {
12109                                                    font_weight: Some(FontWeight::BOLD),
12110                                                    ..make_inlay_hints_style(cx.app)
12111                                                },
12112                                                inline_completion_styles: make_suggestion_styles(
12113                                                    cx.app,
12114                                                ),
12115                                                ..EditorStyle::default()
12116                                            },
12117                                        ))
12118                                        .into_any_element()
12119                                }
12120                            }),
12121                            priority: 0,
12122                        }],
12123                        Some(Autoscroll::fit()),
12124                        cx,
12125                    )[0];
12126                    this.pending_rename = Some(RenameState {
12127                        range,
12128                        old_name,
12129                        editor: rename_editor,
12130                        block_id,
12131                    });
12132                })?;
12133            }
12134
12135            Ok(())
12136        }))
12137    }
12138
12139    pub fn confirm_rename(
12140        &mut self,
12141        _: &ConfirmRename,
12142        window: &mut Window,
12143        cx: &mut Context<Self>,
12144    ) -> Option<Task<Result<()>>> {
12145        let rename = self.take_rename(false, window, cx)?;
12146        let workspace = self.workspace()?.downgrade();
12147        let (buffer, start) = self
12148            .buffer
12149            .read(cx)
12150            .text_anchor_for_position(rename.range.start, cx)?;
12151        let (end_buffer, _) = self
12152            .buffer
12153            .read(cx)
12154            .text_anchor_for_position(rename.range.end, cx)?;
12155        if buffer != end_buffer {
12156            return None;
12157        }
12158
12159        let old_name = rename.old_name;
12160        let new_name = rename.editor.read(cx).text(cx);
12161
12162        let rename = self.semantics_provider.as_ref()?.perform_rename(
12163            &buffer,
12164            start,
12165            new_name.clone(),
12166            cx,
12167        )?;
12168
12169        Some(cx.spawn_in(window, |editor, mut cx| async move {
12170            let project_transaction = rename.await?;
12171            Self::open_project_transaction(
12172                &editor,
12173                workspace,
12174                project_transaction,
12175                format!("Rename: {}{}", old_name, new_name),
12176                cx.clone(),
12177            )
12178            .await?;
12179
12180            editor.update(&mut cx, |editor, cx| {
12181                editor.refresh_document_highlights(cx);
12182            })?;
12183            Ok(())
12184        }))
12185    }
12186
12187    fn take_rename(
12188        &mut self,
12189        moving_cursor: bool,
12190        window: &mut Window,
12191        cx: &mut Context<Self>,
12192    ) -> Option<RenameState> {
12193        let rename = self.pending_rename.take()?;
12194        if rename.editor.focus_handle(cx).is_focused(window) {
12195            window.focus(&self.focus_handle);
12196        }
12197
12198        self.remove_blocks(
12199            [rename.block_id].into_iter().collect(),
12200            Some(Autoscroll::fit()),
12201            cx,
12202        );
12203        self.clear_highlights::<Rename>(cx);
12204        self.show_local_selections = true;
12205
12206        if moving_cursor {
12207            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12208                editor.selections.newest::<usize>(cx).head()
12209            });
12210
12211            // Update the selection to match the position of the selection inside
12212            // the rename editor.
12213            let snapshot = self.buffer.read(cx).read(cx);
12214            let rename_range = rename.range.to_offset(&snapshot);
12215            let cursor_in_editor = snapshot
12216                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12217                .min(rename_range.end);
12218            drop(snapshot);
12219
12220            self.change_selections(None, window, cx, |s| {
12221                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12222            });
12223        } else {
12224            self.refresh_document_highlights(cx);
12225        }
12226
12227        Some(rename)
12228    }
12229
12230    pub fn pending_rename(&self) -> Option<&RenameState> {
12231        self.pending_rename.as_ref()
12232    }
12233
12234    fn format(
12235        &mut self,
12236        _: &Format,
12237        window: &mut Window,
12238        cx: &mut Context<Self>,
12239    ) -> Option<Task<Result<()>>> {
12240        let project = match &self.project {
12241            Some(project) => project.clone(),
12242            None => return None,
12243        };
12244
12245        Some(self.perform_format(
12246            project,
12247            FormatTrigger::Manual,
12248            FormatTarget::Buffers,
12249            window,
12250            cx,
12251        ))
12252    }
12253
12254    fn format_selections(
12255        &mut self,
12256        _: &FormatSelections,
12257        window: &mut Window,
12258        cx: &mut Context<Self>,
12259    ) -> Option<Task<Result<()>>> {
12260        let project = match &self.project {
12261            Some(project) => project.clone(),
12262            None => return None,
12263        };
12264
12265        let ranges = self
12266            .selections
12267            .all_adjusted(cx)
12268            .into_iter()
12269            .map(|selection| selection.range())
12270            .collect_vec();
12271
12272        Some(self.perform_format(
12273            project,
12274            FormatTrigger::Manual,
12275            FormatTarget::Ranges(ranges),
12276            window,
12277            cx,
12278        ))
12279    }
12280
12281    fn perform_format(
12282        &mut self,
12283        project: Entity<Project>,
12284        trigger: FormatTrigger,
12285        target: FormatTarget,
12286        window: &mut Window,
12287        cx: &mut Context<Self>,
12288    ) -> Task<Result<()>> {
12289        let buffer = self.buffer.clone();
12290        let (buffers, target) = match target {
12291            FormatTarget::Buffers => {
12292                let mut buffers = buffer.read(cx).all_buffers();
12293                if trigger == FormatTrigger::Save {
12294                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
12295                }
12296                (buffers, LspFormatTarget::Buffers)
12297            }
12298            FormatTarget::Ranges(selection_ranges) => {
12299                let multi_buffer = buffer.read(cx);
12300                let snapshot = multi_buffer.read(cx);
12301                let mut buffers = HashSet::default();
12302                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12303                    BTreeMap::new();
12304                for selection_range in selection_ranges {
12305                    for (buffer, buffer_range, _) in
12306                        snapshot.range_to_buffer_ranges(selection_range)
12307                    {
12308                        let buffer_id = buffer.remote_id();
12309                        let start = buffer.anchor_before(buffer_range.start);
12310                        let end = buffer.anchor_after(buffer_range.end);
12311                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12312                        buffer_id_to_ranges
12313                            .entry(buffer_id)
12314                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12315                            .or_insert_with(|| vec![start..end]);
12316                    }
12317                }
12318                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12319            }
12320        };
12321
12322        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12323        let format = project.update(cx, |project, cx| {
12324            project.format(buffers, target, true, trigger, cx)
12325        });
12326
12327        cx.spawn_in(window, |_, mut cx| async move {
12328            let transaction = futures::select_biased! {
12329                () = timeout => {
12330                    log::warn!("timed out waiting for formatting");
12331                    None
12332                }
12333                transaction = format.log_err().fuse() => transaction,
12334            };
12335
12336            buffer
12337                .update(&mut cx, |buffer, cx| {
12338                    if let Some(transaction) = transaction {
12339                        if !buffer.is_singleton() {
12340                            buffer.push_transaction(&transaction.0, cx);
12341                        }
12342                    }
12343
12344                    cx.notify();
12345                })
12346                .ok();
12347
12348            Ok(())
12349        })
12350    }
12351
12352    fn restart_language_server(
12353        &mut self,
12354        _: &RestartLanguageServer,
12355        _: &mut Window,
12356        cx: &mut Context<Self>,
12357    ) {
12358        if let Some(project) = self.project.clone() {
12359            self.buffer.update(cx, |multi_buffer, cx| {
12360                project.update(cx, |project, cx| {
12361                    project.restart_language_servers_for_buffers(
12362                        multi_buffer.all_buffers().into_iter().collect(),
12363                        cx,
12364                    );
12365                });
12366            })
12367        }
12368    }
12369
12370    fn cancel_language_server_work(
12371        workspace: &mut Workspace,
12372        _: &actions::CancelLanguageServerWork,
12373        _: &mut Window,
12374        cx: &mut Context<Workspace>,
12375    ) {
12376        let project = workspace.project();
12377        let buffers = workspace
12378            .active_item(cx)
12379            .and_then(|item| item.act_as::<Editor>(cx))
12380            .map_or(HashSet::default(), |editor| {
12381                editor.read(cx).buffer.read(cx).all_buffers()
12382            });
12383        project.update(cx, |project, cx| {
12384            project.cancel_language_server_work_for_buffers(buffers, cx);
12385        });
12386    }
12387
12388    fn show_character_palette(
12389        &mut self,
12390        _: &ShowCharacterPalette,
12391        window: &mut Window,
12392        _: &mut Context<Self>,
12393    ) {
12394        window.show_character_palette();
12395    }
12396
12397    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12398        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12399            let buffer = self.buffer.read(cx).snapshot(cx);
12400            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12401            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12402            let is_valid = buffer
12403                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12404                .any(|entry| {
12405                    entry.diagnostic.is_primary
12406                        && !entry.range.is_empty()
12407                        && entry.range.start == primary_range_start
12408                        && entry.diagnostic.message == active_diagnostics.primary_message
12409                });
12410
12411            if is_valid != active_diagnostics.is_valid {
12412                active_diagnostics.is_valid = is_valid;
12413                let mut new_styles = HashMap::default();
12414                for (block_id, diagnostic) in &active_diagnostics.blocks {
12415                    new_styles.insert(
12416                        *block_id,
12417                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
12418                    );
12419                }
12420                self.display_map.update(cx, |display_map, _cx| {
12421                    display_map.replace_blocks(new_styles)
12422                });
12423            }
12424        }
12425    }
12426
12427    fn activate_diagnostics(
12428        &mut self,
12429        buffer_id: BufferId,
12430        group_id: usize,
12431        window: &mut Window,
12432        cx: &mut Context<Self>,
12433    ) {
12434        self.dismiss_diagnostics(cx);
12435        let snapshot = self.snapshot(window, cx);
12436        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12437            let buffer = self.buffer.read(cx).snapshot(cx);
12438
12439            let mut primary_range = None;
12440            let mut primary_message = None;
12441            let diagnostic_group = buffer
12442                .diagnostic_group(buffer_id, group_id)
12443                .filter_map(|entry| {
12444                    let start = entry.range.start;
12445                    let end = entry.range.end;
12446                    if snapshot.is_line_folded(MultiBufferRow(start.row))
12447                        && (start.row == end.row
12448                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
12449                    {
12450                        return None;
12451                    }
12452                    if entry.diagnostic.is_primary {
12453                        primary_range = Some(entry.range.clone());
12454                        primary_message = Some(entry.diagnostic.message.clone());
12455                    }
12456                    Some(entry)
12457                })
12458                .collect::<Vec<_>>();
12459            let primary_range = primary_range?;
12460            let primary_message = primary_message?;
12461
12462            let blocks = display_map
12463                .insert_blocks(
12464                    diagnostic_group.iter().map(|entry| {
12465                        let diagnostic = entry.diagnostic.clone();
12466                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12467                        BlockProperties {
12468                            style: BlockStyle::Fixed,
12469                            placement: BlockPlacement::Below(
12470                                buffer.anchor_after(entry.range.start),
12471                            ),
12472                            height: message_height,
12473                            render: diagnostic_block_renderer(diagnostic, None, true, true),
12474                            priority: 0,
12475                        }
12476                    }),
12477                    cx,
12478                )
12479                .into_iter()
12480                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12481                .collect();
12482
12483            Some(ActiveDiagnosticGroup {
12484                primary_range: buffer.anchor_before(primary_range.start)
12485                    ..buffer.anchor_after(primary_range.end),
12486                primary_message,
12487                group_id,
12488                blocks,
12489                is_valid: true,
12490            })
12491        });
12492    }
12493
12494    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12495        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12496            self.display_map.update(cx, |display_map, cx| {
12497                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12498            });
12499            cx.notify();
12500        }
12501    }
12502
12503    /// Disable inline diagnostics rendering for this editor.
12504    pub fn disable_inline_diagnostics(&mut self) {
12505        self.inline_diagnostics_enabled = false;
12506        self.inline_diagnostics_update = Task::ready(());
12507        self.inline_diagnostics.clear();
12508    }
12509
12510    pub fn inline_diagnostics_enabled(&self) -> bool {
12511        self.inline_diagnostics_enabled
12512    }
12513
12514    pub fn show_inline_diagnostics(&self) -> bool {
12515        self.show_inline_diagnostics
12516    }
12517
12518    pub fn toggle_inline_diagnostics(
12519        &mut self,
12520        _: &ToggleInlineDiagnostics,
12521        window: &mut Window,
12522        cx: &mut Context<'_, Editor>,
12523    ) {
12524        self.show_inline_diagnostics = !self.show_inline_diagnostics;
12525        self.refresh_inline_diagnostics(false, window, cx);
12526    }
12527
12528    fn refresh_inline_diagnostics(
12529        &mut self,
12530        debounce: bool,
12531        window: &mut Window,
12532        cx: &mut Context<Self>,
12533    ) {
12534        if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12535            self.inline_diagnostics_update = Task::ready(());
12536            self.inline_diagnostics.clear();
12537            return;
12538        }
12539
12540        let debounce_ms = ProjectSettings::get_global(cx)
12541            .diagnostics
12542            .inline
12543            .update_debounce_ms;
12544        let debounce = if debounce && debounce_ms > 0 {
12545            Some(Duration::from_millis(debounce_ms))
12546        } else {
12547            None
12548        };
12549        self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12550            if let Some(debounce) = debounce {
12551                cx.background_executor().timer(debounce).await;
12552            }
12553            let Some(snapshot) = editor
12554                .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12555                .ok()
12556            else {
12557                return;
12558            };
12559
12560            let new_inline_diagnostics = cx
12561                .background_spawn(async move {
12562                    let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12563                    for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12564                        let message = diagnostic_entry
12565                            .diagnostic
12566                            .message
12567                            .split_once('\n')
12568                            .map(|(line, _)| line)
12569                            .map(SharedString::new)
12570                            .unwrap_or_else(|| {
12571                                SharedString::from(diagnostic_entry.diagnostic.message)
12572                            });
12573                        let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12574                        let (Ok(i) | Err(i)) = inline_diagnostics
12575                            .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12576                        inline_diagnostics.insert(
12577                            i,
12578                            (
12579                                start_anchor,
12580                                InlineDiagnostic {
12581                                    message,
12582                                    group_id: diagnostic_entry.diagnostic.group_id,
12583                                    start: diagnostic_entry.range.start.to_point(&snapshot),
12584                                    is_primary: diagnostic_entry.diagnostic.is_primary,
12585                                    severity: diagnostic_entry.diagnostic.severity,
12586                                },
12587                            ),
12588                        );
12589                    }
12590                    inline_diagnostics
12591                })
12592                .await;
12593
12594            editor
12595                .update(&mut cx, |editor, cx| {
12596                    editor.inline_diagnostics = new_inline_diagnostics;
12597                    cx.notify();
12598                })
12599                .ok();
12600        });
12601    }
12602
12603    pub fn set_selections_from_remote(
12604        &mut self,
12605        selections: Vec<Selection<Anchor>>,
12606        pending_selection: Option<Selection<Anchor>>,
12607        window: &mut Window,
12608        cx: &mut Context<Self>,
12609    ) {
12610        let old_cursor_position = self.selections.newest_anchor().head();
12611        self.selections.change_with(cx, |s| {
12612            s.select_anchors(selections);
12613            if let Some(pending_selection) = pending_selection {
12614                s.set_pending(pending_selection, SelectMode::Character);
12615            } else {
12616                s.clear_pending();
12617            }
12618        });
12619        self.selections_did_change(false, &old_cursor_position, true, window, cx);
12620    }
12621
12622    fn push_to_selection_history(&mut self) {
12623        self.selection_history.push(SelectionHistoryEntry {
12624            selections: self.selections.disjoint_anchors(),
12625            select_next_state: self.select_next_state.clone(),
12626            select_prev_state: self.select_prev_state.clone(),
12627            add_selections_state: self.add_selections_state.clone(),
12628        });
12629    }
12630
12631    pub fn transact(
12632        &mut self,
12633        window: &mut Window,
12634        cx: &mut Context<Self>,
12635        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12636    ) -> Option<TransactionId> {
12637        self.start_transaction_at(Instant::now(), window, cx);
12638        update(self, window, cx);
12639        self.end_transaction_at(Instant::now(), cx)
12640    }
12641
12642    pub fn start_transaction_at(
12643        &mut self,
12644        now: Instant,
12645        window: &mut Window,
12646        cx: &mut Context<Self>,
12647    ) {
12648        self.end_selection(window, cx);
12649        if let Some(tx_id) = self
12650            .buffer
12651            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12652        {
12653            self.selection_history
12654                .insert_transaction(tx_id, self.selections.disjoint_anchors());
12655            cx.emit(EditorEvent::TransactionBegun {
12656                transaction_id: tx_id,
12657            })
12658        }
12659    }
12660
12661    pub fn end_transaction_at(
12662        &mut self,
12663        now: Instant,
12664        cx: &mut Context<Self>,
12665    ) -> Option<TransactionId> {
12666        if let Some(transaction_id) = self
12667            .buffer
12668            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12669        {
12670            if let Some((_, end_selections)) =
12671                self.selection_history.transaction_mut(transaction_id)
12672            {
12673                *end_selections = Some(self.selections.disjoint_anchors());
12674            } else {
12675                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12676            }
12677
12678            cx.emit(EditorEvent::Edited { transaction_id });
12679            Some(transaction_id)
12680        } else {
12681            None
12682        }
12683    }
12684
12685    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12686        if self.selection_mark_mode {
12687            self.change_selections(None, window, cx, |s| {
12688                s.move_with(|_, sel| {
12689                    sel.collapse_to(sel.head(), SelectionGoal::None);
12690                });
12691            })
12692        }
12693        self.selection_mark_mode = true;
12694        cx.notify();
12695    }
12696
12697    pub fn swap_selection_ends(
12698        &mut self,
12699        _: &actions::SwapSelectionEnds,
12700        window: &mut Window,
12701        cx: &mut Context<Self>,
12702    ) {
12703        self.change_selections(None, window, cx, |s| {
12704            s.move_with(|_, sel| {
12705                if sel.start != sel.end {
12706                    sel.reversed = !sel.reversed
12707                }
12708            });
12709        });
12710        self.request_autoscroll(Autoscroll::newest(), cx);
12711        cx.notify();
12712    }
12713
12714    pub fn toggle_fold(
12715        &mut self,
12716        _: &actions::ToggleFold,
12717        window: &mut Window,
12718        cx: &mut Context<Self>,
12719    ) {
12720        if self.is_singleton(cx) {
12721            let selection = self.selections.newest::<Point>(cx);
12722
12723            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12724            let range = if selection.is_empty() {
12725                let point = selection.head().to_display_point(&display_map);
12726                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12727                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12728                    .to_point(&display_map);
12729                start..end
12730            } else {
12731                selection.range()
12732            };
12733            if display_map.folds_in_range(range).next().is_some() {
12734                self.unfold_lines(&Default::default(), window, cx)
12735            } else {
12736                self.fold(&Default::default(), window, cx)
12737            }
12738        } else {
12739            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12740            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12741                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12742                .map(|(snapshot, _, _)| snapshot.remote_id())
12743                .collect();
12744
12745            for buffer_id in buffer_ids {
12746                if self.is_buffer_folded(buffer_id, cx) {
12747                    self.unfold_buffer(buffer_id, cx);
12748                } else {
12749                    self.fold_buffer(buffer_id, cx);
12750                }
12751            }
12752        }
12753    }
12754
12755    pub fn toggle_fold_recursive(
12756        &mut self,
12757        _: &actions::ToggleFoldRecursive,
12758        window: &mut Window,
12759        cx: &mut Context<Self>,
12760    ) {
12761        let selection = self.selections.newest::<Point>(cx);
12762
12763        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12764        let range = if selection.is_empty() {
12765            let point = selection.head().to_display_point(&display_map);
12766            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12767            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12768                .to_point(&display_map);
12769            start..end
12770        } else {
12771            selection.range()
12772        };
12773        if display_map.folds_in_range(range).next().is_some() {
12774            self.unfold_recursive(&Default::default(), window, cx)
12775        } else {
12776            self.fold_recursive(&Default::default(), window, cx)
12777        }
12778    }
12779
12780    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12781        if self.is_singleton(cx) {
12782            let mut to_fold = Vec::new();
12783            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12784            let selections = self.selections.all_adjusted(cx);
12785
12786            for selection in selections {
12787                let range = selection.range().sorted();
12788                let buffer_start_row = range.start.row;
12789
12790                if range.start.row != range.end.row {
12791                    let mut found = false;
12792                    let mut row = range.start.row;
12793                    while row <= range.end.row {
12794                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12795                        {
12796                            found = true;
12797                            row = crease.range().end.row + 1;
12798                            to_fold.push(crease);
12799                        } else {
12800                            row += 1
12801                        }
12802                    }
12803                    if found {
12804                        continue;
12805                    }
12806                }
12807
12808                for row in (0..=range.start.row).rev() {
12809                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12810                        if crease.range().end.row >= buffer_start_row {
12811                            to_fold.push(crease);
12812                            if row <= range.start.row {
12813                                break;
12814                            }
12815                        }
12816                    }
12817                }
12818            }
12819
12820            self.fold_creases(to_fold, true, window, cx);
12821        } else {
12822            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12823
12824            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12825                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12826                .map(|(snapshot, _, _)| snapshot.remote_id())
12827                .collect();
12828            for buffer_id in buffer_ids {
12829                self.fold_buffer(buffer_id, cx);
12830            }
12831        }
12832    }
12833
12834    fn fold_at_level(
12835        &mut self,
12836        fold_at: &FoldAtLevel,
12837        window: &mut Window,
12838        cx: &mut Context<Self>,
12839    ) {
12840        if !self.buffer.read(cx).is_singleton() {
12841            return;
12842        }
12843
12844        let fold_at_level = fold_at.0;
12845        let snapshot = self.buffer.read(cx).snapshot(cx);
12846        let mut to_fold = Vec::new();
12847        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12848
12849        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12850            while start_row < end_row {
12851                match self
12852                    .snapshot(window, cx)
12853                    .crease_for_buffer_row(MultiBufferRow(start_row))
12854                {
12855                    Some(crease) => {
12856                        let nested_start_row = crease.range().start.row + 1;
12857                        let nested_end_row = crease.range().end.row;
12858
12859                        if current_level < fold_at_level {
12860                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12861                        } else if current_level == fold_at_level {
12862                            to_fold.push(crease);
12863                        }
12864
12865                        start_row = nested_end_row + 1;
12866                    }
12867                    None => start_row += 1,
12868                }
12869            }
12870        }
12871
12872        self.fold_creases(to_fold, true, window, cx);
12873    }
12874
12875    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12876        if self.buffer.read(cx).is_singleton() {
12877            let mut fold_ranges = Vec::new();
12878            let snapshot = self.buffer.read(cx).snapshot(cx);
12879
12880            for row in 0..snapshot.max_row().0 {
12881                if let Some(foldable_range) = self
12882                    .snapshot(window, cx)
12883                    .crease_for_buffer_row(MultiBufferRow(row))
12884                {
12885                    fold_ranges.push(foldable_range);
12886                }
12887            }
12888
12889            self.fold_creases(fold_ranges, true, window, cx);
12890        } else {
12891            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12892                editor
12893                    .update_in(&mut cx, |editor, _, cx| {
12894                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12895                            editor.fold_buffer(buffer_id, cx);
12896                        }
12897                    })
12898                    .ok();
12899            });
12900        }
12901    }
12902
12903    pub fn fold_function_bodies(
12904        &mut self,
12905        _: &actions::FoldFunctionBodies,
12906        window: &mut Window,
12907        cx: &mut Context<Self>,
12908    ) {
12909        let snapshot = self.buffer.read(cx).snapshot(cx);
12910
12911        let ranges = snapshot
12912            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12913            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12914            .collect::<Vec<_>>();
12915
12916        let creases = ranges
12917            .into_iter()
12918            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12919            .collect();
12920
12921        self.fold_creases(creases, true, window, cx);
12922    }
12923
12924    pub fn fold_recursive(
12925        &mut self,
12926        _: &actions::FoldRecursive,
12927        window: &mut Window,
12928        cx: &mut Context<Self>,
12929    ) {
12930        let mut to_fold = Vec::new();
12931        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12932        let selections = self.selections.all_adjusted(cx);
12933
12934        for selection in selections {
12935            let range = selection.range().sorted();
12936            let buffer_start_row = range.start.row;
12937
12938            if range.start.row != range.end.row {
12939                let mut found = false;
12940                for row in range.start.row..=range.end.row {
12941                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12942                        found = true;
12943                        to_fold.push(crease);
12944                    }
12945                }
12946                if found {
12947                    continue;
12948                }
12949            }
12950
12951            for row in (0..=range.start.row).rev() {
12952                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12953                    if crease.range().end.row >= buffer_start_row {
12954                        to_fold.push(crease);
12955                    } else {
12956                        break;
12957                    }
12958                }
12959            }
12960        }
12961
12962        self.fold_creases(to_fold, true, window, cx);
12963    }
12964
12965    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12966        let buffer_row = fold_at.buffer_row;
12967        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12968
12969        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12970            let autoscroll = self
12971                .selections
12972                .all::<Point>(cx)
12973                .iter()
12974                .any(|selection| crease.range().overlaps(&selection.range()));
12975
12976            self.fold_creases(vec![crease], autoscroll, window, cx);
12977        }
12978    }
12979
12980    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12981        if self.is_singleton(cx) {
12982            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12983            let buffer = &display_map.buffer_snapshot;
12984            let selections = self.selections.all::<Point>(cx);
12985            let ranges = selections
12986                .iter()
12987                .map(|s| {
12988                    let range = s.display_range(&display_map).sorted();
12989                    let mut start = range.start.to_point(&display_map);
12990                    let mut end = range.end.to_point(&display_map);
12991                    start.column = 0;
12992                    end.column = buffer.line_len(MultiBufferRow(end.row));
12993                    start..end
12994                })
12995                .collect::<Vec<_>>();
12996
12997            self.unfold_ranges(&ranges, true, true, cx);
12998        } else {
12999            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13000            let buffer_ids: HashSet<_> = multi_buffer_snapshot
13001                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
13002                .map(|(snapshot, _, _)| snapshot.remote_id())
13003                .collect();
13004            for buffer_id in buffer_ids {
13005                self.unfold_buffer(buffer_id, cx);
13006            }
13007        }
13008    }
13009
13010    pub fn unfold_recursive(
13011        &mut self,
13012        _: &UnfoldRecursive,
13013        _window: &mut Window,
13014        cx: &mut Context<Self>,
13015    ) {
13016        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13017        let selections = self.selections.all::<Point>(cx);
13018        let ranges = selections
13019            .iter()
13020            .map(|s| {
13021                let mut range = s.display_range(&display_map).sorted();
13022                *range.start.column_mut() = 0;
13023                *range.end.column_mut() = display_map.line_len(range.end.row());
13024                let start = range.start.to_point(&display_map);
13025                let end = range.end.to_point(&display_map);
13026                start..end
13027            })
13028            .collect::<Vec<_>>();
13029
13030        self.unfold_ranges(&ranges, true, true, cx);
13031    }
13032
13033    pub fn unfold_at(
13034        &mut self,
13035        unfold_at: &UnfoldAt,
13036        _window: &mut Window,
13037        cx: &mut Context<Self>,
13038    ) {
13039        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13040
13041        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13042            ..Point::new(
13043                unfold_at.buffer_row.0,
13044                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13045            );
13046
13047        let autoscroll = self
13048            .selections
13049            .all::<Point>(cx)
13050            .iter()
13051            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13052
13053        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13054    }
13055
13056    pub fn unfold_all(
13057        &mut self,
13058        _: &actions::UnfoldAll,
13059        _window: &mut Window,
13060        cx: &mut Context<Self>,
13061    ) {
13062        if self.buffer.read(cx).is_singleton() {
13063            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13064            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13065        } else {
13066            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13067                editor
13068                    .update(&mut cx, |editor, cx| {
13069                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13070                            editor.unfold_buffer(buffer_id, cx);
13071                        }
13072                    })
13073                    .ok();
13074            });
13075        }
13076    }
13077
13078    pub fn fold_selected_ranges(
13079        &mut self,
13080        _: &FoldSelectedRanges,
13081        window: &mut Window,
13082        cx: &mut Context<Self>,
13083    ) {
13084        let selections = self.selections.all::<Point>(cx);
13085        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13086        let line_mode = self.selections.line_mode;
13087        let ranges = selections
13088            .into_iter()
13089            .map(|s| {
13090                if line_mode {
13091                    let start = Point::new(s.start.row, 0);
13092                    let end = Point::new(
13093                        s.end.row,
13094                        display_map
13095                            .buffer_snapshot
13096                            .line_len(MultiBufferRow(s.end.row)),
13097                    );
13098                    Crease::simple(start..end, display_map.fold_placeholder.clone())
13099                } else {
13100                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13101                }
13102            })
13103            .collect::<Vec<_>>();
13104        self.fold_creases(ranges, true, window, cx);
13105    }
13106
13107    pub fn fold_ranges<T: ToOffset + Clone>(
13108        &mut self,
13109        ranges: Vec<Range<T>>,
13110        auto_scroll: bool,
13111        window: &mut Window,
13112        cx: &mut Context<Self>,
13113    ) {
13114        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13115        let ranges = ranges
13116            .into_iter()
13117            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13118            .collect::<Vec<_>>();
13119        self.fold_creases(ranges, auto_scroll, window, cx);
13120    }
13121
13122    pub fn fold_creases<T: ToOffset + Clone>(
13123        &mut self,
13124        creases: Vec<Crease<T>>,
13125        auto_scroll: bool,
13126        window: &mut Window,
13127        cx: &mut Context<Self>,
13128    ) {
13129        if creases.is_empty() {
13130            return;
13131        }
13132
13133        let mut buffers_affected = HashSet::default();
13134        let multi_buffer = self.buffer().read(cx);
13135        for crease in &creases {
13136            if let Some((_, buffer, _)) =
13137                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13138            {
13139                buffers_affected.insert(buffer.read(cx).remote_id());
13140            };
13141        }
13142
13143        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13144
13145        if auto_scroll {
13146            self.request_autoscroll(Autoscroll::fit(), cx);
13147        }
13148
13149        cx.notify();
13150
13151        if let Some(active_diagnostics) = self.active_diagnostics.take() {
13152            // Clear diagnostics block when folding a range that contains it.
13153            let snapshot = self.snapshot(window, cx);
13154            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13155                drop(snapshot);
13156                self.active_diagnostics = Some(active_diagnostics);
13157                self.dismiss_diagnostics(cx);
13158            } else {
13159                self.active_diagnostics = Some(active_diagnostics);
13160            }
13161        }
13162
13163        self.scrollbar_marker_state.dirty = true;
13164    }
13165
13166    /// Removes any folds whose ranges intersect any of the given ranges.
13167    pub fn unfold_ranges<T: ToOffset + Clone>(
13168        &mut self,
13169        ranges: &[Range<T>],
13170        inclusive: bool,
13171        auto_scroll: bool,
13172        cx: &mut Context<Self>,
13173    ) {
13174        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13175            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13176        });
13177    }
13178
13179    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13180        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13181            return;
13182        }
13183        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13184        self.display_map
13185            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13186        cx.emit(EditorEvent::BufferFoldToggled {
13187            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13188            folded: true,
13189        });
13190        cx.notify();
13191    }
13192
13193    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13194        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13195            return;
13196        }
13197        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13198        self.display_map.update(cx, |display_map, cx| {
13199            display_map.unfold_buffer(buffer_id, cx);
13200        });
13201        cx.emit(EditorEvent::BufferFoldToggled {
13202            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13203            folded: false,
13204        });
13205        cx.notify();
13206    }
13207
13208    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13209        self.display_map.read(cx).is_buffer_folded(buffer)
13210    }
13211
13212    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13213        self.display_map.read(cx).folded_buffers()
13214    }
13215
13216    /// Removes any folds with the given ranges.
13217    pub fn remove_folds_with_type<T: ToOffset + Clone>(
13218        &mut self,
13219        ranges: &[Range<T>],
13220        type_id: TypeId,
13221        auto_scroll: bool,
13222        cx: &mut Context<Self>,
13223    ) {
13224        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13225            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13226        });
13227    }
13228
13229    fn remove_folds_with<T: ToOffset + Clone>(
13230        &mut self,
13231        ranges: &[Range<T>],
13232        auto_scroll: bool,
13233        cx: &mut Context<Self>,
13234        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13235    ) {
13236        if ranges.is_empty() {
13237            return;
13238        }
13239
13240        let mut buffers_affected = HashSet::default();
13241        let multi_buffer = self.buffer().read(cx);
13242        for range in ranges {
13243            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13244                buffers_affected.insert(buffer.read(cx).remote_id());
13245            };
13246        }
13247
13248        self.display_map.update(cx, update);
13249
13250        if auto_scroll {
13251            self.request_autoscroll(Autoscroll::fit(), cx);
13252        }
13253
13254        cx.notify();
13255        self.scrollbar_marker_state.dirty = true;
13256        self.active_indent_guides_state.dirty = true;
13257    }
13258
13259    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13260        self.display_map.read(cx).fold_placeholder.clone()
13261    }
13262
13263    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13264        self.buffer.update(cx, |buffer, cx| {
13265            buffer.set_all_diff_hunks_expanded(cx);
13266        });
13267    }
13268
13269    pub fn expand_all_diff_hunks(
13270        &mut self,
13271        _: &ExpandAllDiffHunks,
13272        _window: &mut Window,
13273        cx: &mut Context<Self>,
13274    ) {
13275        self.buffer.update(cx, |buffer, cx| {
13276            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13277        });
13278    }
13279
13280    pub fn toggle_selected_diff_hunks(
13281        &mut self,
13282        _: &ToggleSelectedDiffHunks,
13283        _window: &mut Window,
13284        cx: &mut Context<Self>,
13285    ) {
13286        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13287        self.toggle_diff_hunks_in_ranges(ranges, cx);
13288    }
13289
13290    pub fn diff_hunks_in_ranges<'a>(
13291        &'a self,
13292        ranges: &'a [Range<Anchor>],
13293        buffer: &'a MultiBufferSnapshot,
13294    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13295        ranges.iter().flat_map(move |range| {
13296            let end_excerpt_id = range.end.excerpt_id;
13297            let range = range.to_point(buffer);
13298            let mut peek_end = range.end;
13299            if range.end.row < buffer.max_row().0 {
13300                peek_end = Point::new(range.end.row + 1, 0);
13301            }
13302            buffer
13303                .diff_hunks_in_range(range.start..peek_end)
13304                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13305        })
13306    }
13307
13308    pub fn has_stageable_diff_hunks_in_ranges(
13309        &self,
13310        ranges: &[Range<Anchor>],
13311        snapshot: &MultiBufferSnapshot,
13312    ) -> bool {
13313        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13314        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
13315    }
13316
13317    pub fn toggle_staged_selected_diff_hunks(
13318        &mut self,
13319        _: &::git::ToggleStaged,
13320        _window: &mut Window,
13321        cx: &mut Context<Self>,
13322    ) {
13323        let snapshot = self.buffer.read(cx).snapshot(cx);
13324        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13325        let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13326        self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
13327    }
13328
13329    pub fn stage_and_next(
13330        &mut self,
13331        _: &::git::StageAndNext,
13332        window: &mut Window,
13333        cx: &mut Context<Self>,
13334    ) {
13335        self.do_stage_or_unstage_and_next(true, window, cx);
13336    }
13337
13338    pub fn unstage_and_next(
13339        &mut self,
13340        _: &::git::UnstageAndNext,
13341        window: &mut Window,
13342        cx: &mut Context<Self>,
13343    ) {
13344        self.do_stage_or_unstage_and_next(false, window, cx);
13345    }
13346
13347    pub fn stage_or_unstage_diff_hunks(
13348        &mut self,
13349        stage: bool,
13350        ranges: &[Range<Anchor>],
13351        cx: &mut Context<Self>,
13352    ) {
13353        let snapshot = self.buffer.read(cx).snapshot(cx);
13354        let Some(project) = &self.project else {
13355            return;
13356        };
13357
13358        let chunk_by = self
13359            .diff_hunks_in_ranges(&ranges, &snapshot)
13360            .chunk_by(|hunk| hunk.buffer_id);
13361        for (buffer_id, hunks) in &chunk_by {
13362            Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
13363        }
13364    }
13365
13366    fn do_stage_or_unstage_and_next(
13367        &mut self,
13368        stage: bool,
13369        window: &mut Window,
13370        cx: &mut Context<Self>,
13371    ) {
13372        let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13373        if ranges.iter().any(|range| range.start != range.end) {
13374            self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13375            return;
13376        }
13377
13378        if !self.buffer().read(cx).is_singleton() {
13379            if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13380                if buffer.read(cx).is_empty() {
13381                    let buffer = buffer.read(cx);
13382                    let Some(file) = buffer.file() else {
13383                        return;
13384                    };
13385                    let project_path = project::ProjectPath {
13386                        worktree_id: file.worktree_id(cx),
13387                        path: file.path().clone(),
13388                    };
13389                    let Some(project) = self.project.as_ref() else {
13390                        return;
13391                    };
13392                    let project = project.read(cx);
13393
13394                    let Some(repo) = project.git_store().read(cx).active_repository() else {
13395                        return;
13396                    };
13397
13398                    repo.update(cx, |repo, cx| {
13399                        let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13400                            return;
13401                        };
13402                        let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13403                            return;
13404                        };
13405                        if stage && status.status == FileStatus::Untracked {
13406                            repo.stage_entries(vec![repo_path], cx)
13407                                .detach_and_log_err(cx);
13408                            return;
13409                        }
13410                    })
13411                }
13412                ranges = vec![multi_buffer::Anchor::range_in_buffer(
13413                    excerpt_id,
13414                    buffer.read(cx).remote_id(),
13415                    range,
13416                )];
13417                self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13418                let snapshot = self.buffer().read(cx).snapshot(cx);
13419                let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13420                if point.row < snapshot.max_row().0 {
13421                    point.row += 1;
13422                    point.column = 0;
13423                    point = snapshot.clip_point(point, Bias::Right);
13424                    self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13425                        s.select_ranges([point..point]);
13426                    })
13427                }
13428                return;
13429            }
13430        }
13431        self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13432        self.go_to_next_hunk(&Default::default(), window, cx);
13433    }
13434
13435    fn do_stage_or_unstage(
13436        project: &Entity<Project>,
13437        stage: bool,
13438        buffer_id: BufferId,
13439        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13440        snapshot: &MultiBufferSnapshot,
13441        cx: &mut Context<Self>,
13442    ) {
13443        let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13444            log::debug!("no buffer for id");
13445            return;
13446        };
13447        let buffer_snapshot = buffer.read(cx).snapshot();
13448        let Some((repo, path)) = project
13449            .read(cx)
13450            .repository_and_path_for_buffer_id(buffer_id, cx)
13451        else {
13452            log::debug!("no git repo for buffer id");
13453            return;
13454        };
13455        let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13456            log::debug!("no diff for buffer id");
13457            return;
13458        };
13459        let Some(secondary_diff) = diff.secondary_diff() else {
13460            log::debug!("no secondary diff for buffer id");
13461            return;
13462        };
13463
13464        let edits = diff.secondary_edits_for_stage_or_unstage(
13465            stage,
13466            hunks.filter_map(|hunk| {
13467                if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13468                    return None;
13469                } else if !stage
13470                    && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13471                {
13472                    return None;
13473                }
13474                Some((
13475                    hunk.diff_base_byte_range.clone(),
13476                    hunk.secondary_diff_base_byte_range.clone(),
13477                    hunk.buffer_range.clone(),
13478                ))
13479            }),
13480            &buffer_snapshot,
13481        );
13482
13483        let Some(index_base) = secondary_diff
13484            .base_text()
13485            .map(|snapshot| snapshot.text.as_rope().clone())
13486        else {
13487            log::debug!("no index base");
13488            return;
13489        };
13490        let index_buffer = cx.new(|cx| {
13491            Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
13492        });
13493        let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
13494            index_buffer.edit(edits, None, cx);
13495            index_buffer.snapshot().as_rope().to_string()
13496        });
13497        let new_index_text = if new_index_text.is_empty()
13498            && !stage
13499            && (diff.is_single_insertion
13500                || buffer_snapshot
13501                    .file()
13502                    .map_or(false, |file| file.disk_state() == DiskState::New))
13503        {
13504            log::debug!("removing from index");
13505            None
13506        } else {
13507            Some(new_index_text)
13508        };
13509        let buffer_store = project.read(cx).buffer_store().clone();
13510        buffer_store
13511            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13512            .detach_and_log_err(cx);
13513
13514        cx.background_spawn(
13515            repo.read(cx)
13516                .set_index_text(&path, new_index_text)
13517                .log_err(),
13518        )
13519        .detach();
13520    }
13521
13522    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13523        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13524        self.buffer
13525            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13526    }
13527
13528    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13529        self.buffer.update(cx, |buffer, cx| {
13530            let ranges = vec![Anchor::min()..Anchor::max()];
13531            if !buffer.all_diff_hunks_expanded()
13532                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13533            {
13534                buffer.collapse_diff_hunks(ranges, cx);
13535                true
13536            } else {
13537                false
13538            }
13539        })
13540    }
13541
13542    fn toggle_diff_hunks_in_ranges(
13543        &mut self,
13544        ranges: Vec<Range<Anchor>>,
13545        cx: &mut Context<'_, Editor>,
13546    ) {
13547        self.buffer.update(cx, |buffer, cx| {
13548            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13549            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13550        })
13551    }
13552
13553    fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13554        self.buffer.update(cx, |buffer, cx| {
13555            let snapshot = buffer.snapshot(cx);
13556            let excerpt_id = range.end.excerpt_id;
13557            let point_range = range.to_point(&snapshot);
13558            let expand = !buffer.single_hunk_is_expanded(range, cx);
13559            buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13560        })
13561    }
13562
13563    pub(crate) fn apply_all_diff_hunks(
13564        &mut self,
13565        _: &ApplyAllDiffHunks,
13566        window: &mut Window,
13567        cx: &mut Context<Self>,
13568    ) {
13569        let buffers = self.buffer.read(cx).all_buffers();
13570        for branch_buffer in buffers {
13571            branch_buffer.update(cx, |branch_buffer, cx| {
13572                branch_buffer.merge_into_base(Vec::new(), cx);
13573            });
13574        }
13575
13576        if let Some(project) = self.project.clone() {
13577            self.save(true, project, window, cx).detach_and_log_err(cx);
13578        }
13579    }
13580
13581    pub(crate) fn apply_selected_diff_hunks(
13582        &mut self,
13583        _: &ApplyDiffHunk,
13584        window: &mut Window,
13585        cx: &mut Context<Self>,
13586    ) {
13587        let snapshot = self.snapshot(window, cx);
13588        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13589        let mut ranges_by_buffer = HashMap::default();
13590        self.transact(window, cx, |editor, _window, cx| {
13591            for hunk in hunks {
13592                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13593                    ranges_by_buffer
13594                        .entry(buffer.clone())
13595                        .or_insert_with(Vec::new)
13596                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13597                }
13598            }
13599
13600            for (buffer, ranges) in ranges_by_buffer {
13601                buffer.update(cx, |buffer, cx| {
13602                    buffer.merge_into_base(ranges, cx);
13603                });
13604            }
13605        });
13606
13607        if let Some(project) = self.project.clone() {
13608            self.save(true, project, window, cx).detach_and_log_err(cx);
13609        }
13610    }
13611
13612    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13613        if hovered != self.gutter_hovered {
13614            self.gutter_hovered = hovered;
13615            cx.notify();
13616        }
13617    }
13618
13619    pub fn insert_blocks(
13620        &mut self,
13621        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13622        autoscroll: Option<Autoscroll>,
13623        cx: &mut Context<Self>,
13624    ) -> Vec<CustomBlockId> {
13625        let blocks = self
13626            .display_map
13627            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13628        if let Some(autoscroll) = autoscroll {
13629            self.request_autoscroll(autoscroll, cx);
13630        }
13631        cx.notify();
13632        blocks
13633    }
13634
13635    pub fn resize_blocks(
13636        &mut self,
13637        heights: HashMap<CustomBlockId, u32>,
13638        autoscroll: Option<Autoscroll>,
13639        cx: &mut Context<Self>,
13640    ) {
13641        self.display_map
13642            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13643        if let Some(autoscroll) = autoscroll {
13644            self.request_autoscroll(autoscroll, cx);
13645        }
13646        cx.notify();
13647    }
13648
13649    pub fn replace_blocks(
13650        &mut self,
13651        renderers: HashMap<CustomBlockId, RenderBlock>,
13652        autoscroll: Option<Autoscroll>,
13653        cx: &mut Context<Self>,
13654    ) {
13655        self.display_map
13656            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13657        if let Some(autoscroll) = autoscroll {
13658            self.request_autoscroll(autoscroll, cx);
13659        }
13660        cx.notify();
13661    }
13662
13663    pub fn remove_blocks(
13664        &mut self,
13665        block_ids: HashSet<CustomBlockId>,
13666        autoscroll: Option<Autoscroll>,
13667        cx: &mut Context<Self>,
13668    ) {
13669        self.display_map.update(cx, |display_map, cx| {
13670            display_map.remove_blocks(block_ids, cx)
13671        });
13672        if let Some(autoscroll) = autoscroll {
13673            self.request_autoscroll(autoscroll, cx);
13674        }
13675        cx.notify();
13676    }
13677
13678    pub fn row_for_block(
13679        &self,
13680        block_id: CustomBlockId,
13681        cx: &mut Context<Self>,
13682    ) -> Option<DisplayRow> {
13683        self.display_map
13684            .update(cx, |map, cx| map.row_for_block(block_id, cx))
13685    }
13686
13687    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13688        self.focused_block = Some(focused_block);
13689    }
13690
13691    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13692        self.focused_block.take()
13693    }
13694
13695    pub fn insert_creases(
13696        &mut self,
13697        creases: impl IntoIterator<Item = Crease<Anchor>>,
13698        cx: &mut Context<Self>,
13699    ) -> Vec<CreaseId> {
13700        self.display_map
13701            .update(cx, |map, cx| map.insert_creases(creases, cx))
13702    }
13703
13704    pub fn remove_creases(
13705        &mut self,
13706        ids: impl IntoIterator<Item = CreaseId>,
13707        cx: &mut Context<Self>,
13708    ) {
13709        self.display_map
13710            .update(cx, |map, cx| map.remove_creases(ids, cx));
13711    }
13712
13713    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13714        self.display_map
13715            .update(cx, |map, cx| map.snapshot(cx))
13716            .longest_row()
13717    }
13718
13719    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13720        self.display_map
13721            .update(cx, |map, cx| map.snapshot(cx))
13722            .max_point()
13723    }
13724
13725    pub fn text(&self, cx: &App) -> String {
13726        self.buffer.read(cx).read(cx).text()
13727    }
13728
13729    pub fn is_empty(&self, cx: &App) -> bool {
13730        self.buffer.read(cx).read(cx).is_empty()
13731    }
13732
13733    pub fn text_option(&self, cx: &App) -> Option<String> {
13734        let text = self.text(cx);
13735        let text = text.trim();
13736
13737        if text.is_empty() {
13738            return None;
13739        }
13740
13741        Some(text.to_string())
13742    }
13743
13744    pub fn set_text(
13745        &mut self,
13746        text: impl Into<Arc<str>>,
13747        window: &mut Window,
13748        cx: &mut Context<Self>,
13749    ) {
13750        self.transact(window, cx, |this, _, cx| {
13751            this.buffer
13752                .read(cx)
13753                .as_singleton()
13754                .expect("you can only call set_text on editors for singleton buffers")
13755                .update(cx, |buffer, cx| buffer.set_text(text, cx));
13756        });
13757    }
13758
13759    pub fn display_text(&self, cx: &mut App) -> String {
13760        self.display_map
13761            .update(cx, |map, cx| map.snapshot(cx))
13762            .text()
13763    }
13764
13765    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13766        let mut wrap_guides = smallvec::smallvec![];
13767
13768        if self.show_wrap_guides == Some(false) {
13769            return wrap_guides;
13770        }
13771
13772        let settings = self.buffer.read(cx).settings_at(0, cx);
13773        if settings.show_wrap_guides {
13774            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13775                wrap_guides.push((soft_wrap as usize, true));
13776            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13777                wrap_guides.push((soft_wrap as usize, true));
13778            }
13779            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13780        }
13781
13782        wrap_guides
13783    }
13784
13785    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13786        let settings = self.buffer.read(cx).settings_at(0, cx);
13787        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13788        match mode {
13789            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13790                SoftWrap::None
13791            }
13792            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13793            language_settings::SoftWrap::PreferredLineLength => {
13794                SoftWrap::Column(settings.preferred_line_length)
13795            }
13796            language_settings::SoftWrap::Bounded => {
13797                SoftWrap::Bounded(settings.preferred_line_length)
13798            }
13799        }
13800    }
13801
13802    pub fn set_soft_wrap_mode(
13803        &mut self,
13804        mode: language_settings::SoftWrap,
13805
13806        cx: &mut Context<Self>,
13807    ) {
13808        self.soft_wrap_mode_override = Some(mode);
13809        cx.notify();
13810    }
13811
13812    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13813        self.text_style_refinement = Some(style);
13814    }
13815
13816    /// called by the Element so we know what style we were most recently rendered with.
13817    pub(crate) fn set_style(
13818        &mut self,
13819        style: EditorStyle,
13820        window: &mut Window,
13821        cx: &mut Context<Self>,
13822    ) {
13823        let rem_size = window.rem_size();
13824        self.display_map.update(cx, |map, cx| {
13825            map.set_font(
13826                style.text.font(),
13827                style.text.font_size.to_pixels(rem_size),
13828                cx,
13829            )
13830        });
13831        self.style = Some(style);
13832    }
13833
13834    pub fn style(&self) -> Option<&EditorStyle> {
13835        self.style.as_ref()
13836    }
13837
13838    // Called by the element. This method is not designed to be called outside of the editor
13839    // element's layout code because it does not notify when rewrapping is computed synchronously.
13840    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13841        self.display_map
13842            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13843    }
13844
13845    pub fn set_soft_wrap(&mut self) {
13846        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13847    }
13848
13849    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13850        if self.soft_wrap_mode_override.is_some() {
13851            self.soft_wrap_mode_override.take();
13852        } else {
13853            let soft_wrap = match self.soft_wrap_mode(cx) {
13854                SoftWrap::GitDiff => return,
13855                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13856                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13857                    language_settings::SoftWrap::None
13858                }
13859            };
13860            self.soft_wrap_mode_override = Some(soft_wrap);
13861        }
13862        cx.notify();
13863    }
13864
13865    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13866        let Some(workspace) = self.workspace() else {
13867            return;
13868        };
13869        let fs = workspace.read(cx).app_state().fs.clone();
13870        let current_show = TabBarSettings::get_global(cx).show;
13871        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13872            setting.show = Some(!current_show);
13873        });
13874    }
13875
13876    pub fn toggle_indent_guides(
13877        &mut self,
13878        _: &ToggleIndentGuides,
13879        _: &mut Window,
13880        cx: &mut Context<Self>,
13881    ) {
13882        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13883            self.buffer
13884                .read(cx)
13885                .settings_at(0, cx)
13886                .indent_guides
13887                .enabled
13888        });
13889        self.show_indent_guides = Some(!currently_enabled);
13890        cx.notify();
13891    }
13892
13893    fn should_show_indent_guides(&self) -> Option<bool> {
13894        self.show_indent_guides
13895    }
13896
13897    pub fn toggle_line_numbers(
13898        &mut self,
13899        _: &ToggleLineNumbers,
13900        _: &mut Window,
13901        cx: &mut Context<Self>,
13902    ) {
13903        let mut editor_settings = EditorSettings::get_global(cx).clone();
13904        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13905        EditorSettings::override_global(editor_settings, cx);
13906    }
13907
13908    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13909        self.use_relative_line_numbers
13910            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13911    }
13912
13913    pub fn toggle_relative_line_numbers(
13914        &mut self,
13915        _: &ToggleRelativeLineNumbers,
13916        _: &mut Window,
13917        cx: &mut Context<Self>,
13918    ) {
13919        let is_relative = self.should_use_relative_line_numbers(cx);
13920        self.set_relative_line_number(Some(!is_relative), cx)
13921    }
13922
13923    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13924        self.use_relative_line_numbers = is_relative;
13925        cx.notify();
13926    }
13927
13928    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13929        self.show_gutter = show_gutter;
13930        cx.notify();
13931    }
13932
13933    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13934        self.show_scrollbars = show_scrollbars;
13935        cx.notify();
13936    }
13937
13938    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13939        self.show_line_numbers = Some(show_line_numbers);
13940        cx.notify();
13941    }
13942
13943    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13944        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13945        cx.notify();
13946    }
13947
13948    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13949        self.show_code_actions = Some(show_code_actions);
13950        cx.notify();
13951    }
13952
13953    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13954        self.show_runnables = Some(show_runnables);
13955        cx.notify();
13956    }
13957
13958    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13959        if self.display_map.read(cx).masked != masked {
13960            self.display_map.update(cx, |map, _| map.masked = masked);
13961        }
13962        cx.notify()
13963    }
13964
13965    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13966        self.show_wrap_guides = Some(show_wrap_guides);
13967        cx.notify();
13968    }
13969
13970    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13971        self.show_indent_guides = Some(show_indent_guides);
13972        cx.notify();
13973    }
13974
13975    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13976        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13977            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13978                if let Some(dir) = file.abs_path(cx).parent() {
13979                    return Some(dir.to_owned());
13980                }
13981            }
13982
13983            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13984                return Some(project_path.path.to_path_buf());
13985            }
13986        }
13987
13988        None
13989    }
13990
13991    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13992        self.active_excerpt(cx)?
13993            .1
13994            .read(cx)
13995            .file()
13996            .and_then(|f| f.as_local())
13997    }
13998
13999    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14000        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14001            let buffer = buffer.read(cx);
14002            if let Some(project_path) = buffer.project_path(cx) {
14003                let project = self.project.as_ref()?.read(cx);
14004                project.absolute_path(&project_path, cx)
14005            } else {
14006                buffer
14007                    .file()
14008                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14009            }
14010        })
14011    }
14012
14013    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14014        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14015            let project_path = buffer.read(cx).project_path(cx)?;
14016            let project = self.project.as_ref()?.read(cx);
14017            let entry = project.entry_for_path(&project_path, cx)?;
14018            let path = entry.path.to_path_buf();
14019            Some(path)
14020        })
14021    }
14022
14023    pub fn reveal_in_finder(
14024        &mut self,
14025        _: &RevealInFileManager,
14026        _window: &mut Window,
14027        cx: &mut Context<Self>,
14028    ) {
14029        if let Some(target) = self.target_file(cx) {
14030            cx.reveal_path(&target.abs_path(cx));
14031        }
14032    }
14033
14034    pub fn copy_path(
14035        &mut self,
14036        _: &zed_actions::workspace::CopyPath,
14037        _window: &mut Window,
14038        cx: &mut Context<Self>,
14039    ) {
14040        if let Some(path) = self.target_file_abs_path(cx) {
14041            if let Some(path) = path.to_str() {
14042                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14043            }
14044        }
14045    }
14046
14047    pub fn copy_relative_path(
14048        &mut self,
14049        _: &zed_actions::workspace::CopyRelativePath,
14050        _window: &mut Window,
14051        cx: &mut Context<Self>,
14052    ) {
14053        if let Some(path) = self.target_file_path(cx) {
14054            if let Some(path) = path.to_str() {
14055                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14056            }
14057        }
14058    }
14059
14060    pub fn copy_file_name_without_extension(
14061        &mut self,
14062        _: &CopyFileNameWithoutExtension,
14063        _: &mut Window,
14064        cx: &mut Context<Self>,
14065    ) {
14066        if let Some(file) = self.target_file(cx) {
14067            if let Some(file_stem) = file.path().file_stem() {
14068                if let Some(name) = file_stem.to_str() {
14069                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14070                }
14071            }
14072        }
14073    }
14074
14075    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14076        if let Some(file) = self.target_file(cx) {
14077            if let Some(file_name) = file.path().file_name() {
14078                if let Some(name) = file_name.to_str() {
14079                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14080                }
14081            }
14082        }
14083    }
14084
14085    pub fn toggle_git_blame(
14086        &mut self,
14087        _: &ToggleGitBlame,
14088        window: &mut Window,
14089        cx: &mut Context<Self>,
14090    ) {
14091        self.show_git_blame_gutter = !self.show_git_blame_gutter;
14092
14093        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14094            self.start_git_blame(true, window, cx);
14095        }
14096
14097        cx.notify();
14098    }
14099
14100    pub fn toggle_git_blame_inline(
14101        &mut self,
14102        _: &ToggleGitBlameInline,
14103        window: &mut Window,
14104        cx: &mut Context<Self>,
14105    ) {
14106        self.toggle_git_blame_inline_internal(true, window, cx);
14107        cx.notify();
14108    }
14109
14110    pub fn git_blame_inline_enabled(&self) -> bool {
14111        self.git_blame_inline_enabled
14112    }
14113
14114    pub fn toggle_selection_menu(
14115        &mut self,
14116        _: &ToggleSelectionMenu,
14117        _: &mut Window,
14118        cx: &mut Context<Self>,
14119    ) {
14120        self.show_selection_menu = self
14121            .show_selection_menu
14122            .map(|show_selections_menu| !show_selections_menu)
14123            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14124
14125        cx.notify();
14126    }
14127
14128    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14129        self.show_selection_menu
14130            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14131    }
14132
14133    fn start_git_blame(
14134        &mut self,
14135        user_triggered: bool,
14136        window: &mut Window,
14137        cx: &mut Context<Self>,
14138    ) {
14139        if let Some(project) = self.project.as_ref() {
14140            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14141                return;
14142            };
14143
14144            if buffer.read(cx).file().is_none() {
14145                return;
14146            }
14147
14148            let focused = self.focus_handle(cx).contains_focused(window, cx);
14149
14150            let project = project.clone();
14151            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14152            self.blame_subscription =
14153                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14154            self.blame = Some(blame);
14155        }
14156    }
14157
14158    fn toggle_git_blame_inline_internal(
14159        &mut self,
14160        user_triggered: bool,
14161        window: &mut Window,
14162        cx: &mut Context<Self>,
14163    ) {
14164        if self.git_blame_inline_enabled {
14165            self.git_blame_inline_enabled = false;
14166            self.show_git_blame_inline = false;
14167            self.show_git_blame_inline_delay_task.take();
14168        } else {
14169            self.git_blame_inline_enabled = true;
14170            self.start_git_blame_inline(user_triggered, window, cx);
14171        }
14172
14173        cx.notify();
14174    }
14175
14176    fn start_git_blame_inline(
14177        &mut self,
14178        user_triggered: bool,
14179        window: &mut Window,
14180        cx: &mut Context<Self>,
14181    ) {
14182        self.start_git_blame(user_triggered, window, cx);
14183
14184        if ProjectSettings::get_global(cx)
14185            .git
14186            .inline_blame_delay()
14187            .is_some()
14188        {
14189            self.start_inline_blame_timer(window, cx);
14190        } else {
14191            self.show_git_blame_inline = true
14192        }
14193    }
14194
14195    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14196        self.blame.as_ref()
14197    }
14198
14199    pub fn show_git_blame_gutter(&self) -> bool {
14200        self.show_git_blame_gutter
14201    }
14202
14203    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14204        self.show_git_blame_gutter && self.has_blame_entries(cx)
14205    }
14206
14207    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14208        self.show_git_blame_inline
14209            && (self.focus_handle.is_focused(window)
14210                || self
14211                    .git_blame_inline_tooltip
14212                    .as_ref()
14213                    .and_then(|t| t.upgrade())
14214                    .is_some())
14215            && !self.newest_selection_head_on_empty_line(cx)
14216            && self.has_blame_entries(cx)
14217    }
14218
14219    fn has_blame_entries(&self, cx: &App) -> bool {
14220        self.blame()
14221            .map_or(false, |blame| blame.read(cx).has_generated_entries())
14222    }
14223
14224    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14225        let cursor_anchor = self.selections.newest_anchor().head();
14226
14227        let snapshot = self.buffer.read(cx).snapshot(cx);
14228        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14229
14230        snapshot.line_len(buffer_row) == 0
14231    }
14232
14233    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14234        let buffer_and_selection = maybe!({
14235            let selection = self.selections.newest::<Point>(cx);
14236            let selection_range = selection.range();
14237
14238            let multi_buffer = self.buffer().read(cx);
14239            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14240            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14241
14242            let (buffer, range, _) = if selection.reversed {
14243                buffer_ranges.first()
14244            } else {
14245                buffer_ranges.last()
14246            }?;
14247
14248            let selection = text::ToPoint::to_point(&range.start, &buffer).row
14249                ..text::ToPoint::to_point(&range.end, &buffer).row;
14250            Some((
14251                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14252                selection,
14253            ))
14254        });
14255
14256        let Some((buffer, selection)) = buffer_and_selection else {
14257            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14258        };
14259
14260        let Some(project) = self.project.as_ref() else {
14261            return Task::ready(Err(anyhow!("editor does not have project")));
14262        };
14263
14264        project.update(cx, |project, cx| {
14265            project.get_permalink_to_line(&buffer, selection, cx)
14266        })
14267    }
14268
14269    pub fn copy_permalink_to_line(
14270        &mut self,
14271        _: &CopyPermalinkToLine,
14272        window: &mut Window,
14273        cx: &mut Context<Self>,
14274    ) {
14275        let permalink_task = self.get_permalink_to_line(cx);
14276        let workspace = self.workspace();
14277
14278        cx.spawn_in(window, |_, mut cx| async move {
14279            match permalink_task.await {
14280                Ok(permalink) => {
14281                    cx.update(|_, cx| {
14282                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14283                    })
14284                    .ok();
14285                }
14286                Err(err) => {
14287                    let message = format!("Failed to copy permalink: {err}");
14288
14289                    Err::<(), anyhow::Error>(err).log_err();
14290
14291                    if let Some(workspace) = workspace {
14292                        workspace
14293                            .update_in(&mut cx, |workspace, _, cx| {
14294                                struct CopyPermalinkToLine;
14295
14296                                workspace.show_toast(
14297                                    Toast::new(
14298                                        NotificationId::unique::<CopyPermalinkToLine>(),
14299                                        message,
14300                                    ),
14301                                    cx,
14302                                )
14303                            })
14304                            .ok();
14305                    }
14306                }
14307            }
14308        })
14309        .detach();
14310    }
14311
14312    pub fn copy_file_location(
14313        &mut self,
14314        _: &CopyFileLocation,
14315        _: &mut Window,
14316        cx: &mut Context<Self>,
14317    ) {
14318        let selection = self.selections.newest::<Point>(cx).start.row + 1;
14319        if let Some(file) = self.target_file(cx) {
14320            if let Some(path) = file.path().to_str() {
14321                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14322            }
14323        }
14324    }
14325
14326    pub fn open_permalink_to_line(
14327        &mut self,
14328        _: &OpenPermalinkToLine,
14329        window: &mut Window,
14330        cx: &mut Context<Self>,
14331    ) {
14332        let permalink_task = self.get_permalink_to_line(cx);
14333        let workspace = self.workspace();
14334
14335        cx.spawn_in(window, |_, mut cx| async move {
14336            match permalink_task.await {
14337                Ok(permalink) => {
14338                    cx.update(|_, cx| {
14339                        cx.open_url(permalink.as_ref());
14340                    })
14341                    .ok();
14342                }
14343                Err(err) => {
14344                    let message = format!("Failed to open permalink: {err}");
14345
14346                    Err::<(), anyhow::Error>(err).log_err();
14347
14348                    if let Some(workspace) = workspace {
14349                        workspace
14350                            .update(&mut cx, |workspace, cx| {
14351                                struct OpenPermalinkToLine;
14352
14353                                workspace.show_toast(
14354                                    Toast::new(
14355                                        NotificationId::unique::<OpenPermalinkToLine>(),
14356                                        message,
14357                                    ),
14358                                    cx,
14359                                )
14360                            })
14361                            .ok();
14362                    }
14363                }
14364            }
14365        })
14366        .detach();
14367    }
14368
14369    pub fn insert_uuid_v4(
14370        &mut self,
14371        _: &InsertUuidV4,
14372        window: &mut Window,
14373        cx: &mut Context<Self>,
14374    ) {
14375        self.insert_uuid(UuidVersion::V4, window, cx);
14376    }
14377
14378    pub fn insert_uuid_v7(
14379        &mut self,
14380        _: &InsertUuidV7,
14381        window: &mut Window,
14382        cx: &mut Context<Self>,
14383    ) {
14384        self.insert_uuid(UuidVersion::V7, window, cx);
14385    }
14386
14387    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14388        self.transact(window, cx, |this, window, cx| {
14389            let edits = this
14390                .selections
14391                .all::<Point>(cx)
14392                .into_iter()
14393                .map(|selection| {
14394                    let uuid = match version {
14395                        UuidVersion::V4 => uuid::Uuid::new_v4(),
14396                        UuidVersion::V7 => uuid::Uuid::now_v7(),
14397                    };
14398
14399                    (selection.range(), uuid.to_string())
14400                });
14401            this.edit(edits, cx);
14402            this.refresh_inline_completion(true, false, window, cx);
14403        });
14404    }
14405
14406    pub fn open_selections_in_multibuffer(
14407        &mut self,
14408        _: &OpenSelectionsInMultibuffer,
14409        window: &mut Window,
14410        cx: &mut Context<Self>,
14411    ) {
14412        let multibuffer = self.buffer.read(cx);
14413
14414        let Some(buffer) = multibuffer.as_singleton() else {
14415            return;
14416        };
14417
14418        let Some(workspace) = self.workspace() else {
14419            return;
14420        };
14421
14422        let locations = self
14423            .selections
14424            .disjoint_anchors()
14425            .iter()
14426            .map(|range| Location {
14427                buffer: buffer.clone(),
14428                range: range.start.text_anchor..range.end.text_anchor,
14429            })
14430            .collect::<Vec<_>>();
14431
14432        let title = multibuffer.title(cx).to_string();
14433
14434        cx.spawn_in(window, |_, mut cx| async move {
14435            workspace.update_in(&mut cx, |workspace, window, cx| {
14436                Self::open_locations_in_multibuffer(
14437                    workspace,
14438                    locations,
14439                    format!("Selections for '{title}'"),
14440                    false,
14441                    MultibufferSelectionMode::All,
14442                    window,
14443                    cx,
14444                );
14445            })
14446        })
14447        .detach();
14448    }
14449
14450    /// Adds a row highlight for the given range. If a row has multiple highlights, the
14451    /// last highlight added will be used.
14452    ///
14453    /// If the range ends at the beginning of a line, then that line will not be highlighted.
14454    pub fn highlight_rows<T: 'static>(
14455        &mut self,
14456        range: Range<Anchor>,
14457        color: Hsla,
14458        should_autoscroll: bool,
14459        cx: &mut Context<Self>,
14460    ) {
14461        let snapshot = self.buffer().read(cx).snapshot(cx);
14462        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14463        let ix = row_highlights.binary_search_by(|highlight| {
14464            Ordering::Equal
14465                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14466                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14467        });
14468
14469        if let Err(mut ix) = ix {
14470            let index = post_inc(&mut self.highlight_order);
14471
14472            // If this range intersects with the preceding highlight, then merge it with
14473            // the preceding highlight. Otherwise insert a new highlight.
14474            let mut merged = false;
14475            if ix > 0 {
14476                let prev_highlight = &mut row_highlights[ix - 1];
14477                if prev_highlight
14478                    .range
14479                    .end
14480                    .cmp(&range.start, &snapshot)
14481                    .is_ge()
14482                {
14483                    ix -= 1;
14484                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14485                        prev_highlight.range.end = range.end;
14486                    }
14487                    merged = true;
14488                    prev_highlight.index = index;
14489                    prev_highlight.color = color;
14490                    prev_highlight.should_autoscroll = should_autoscroll;
14491                }
14492            }
14493
14494            if !merged {
14495                row_highlights.insert(
14496                    ix,
14497                    RowHighlight {
14498                        range: range.clone(),
14499                        index,
14500                        color,
14501                        should_autoscroll,
14502                    },
14503                );
14504            }
14505
14506            // If any of the following highlights intersect with this one, merge them.
14507            while let Some(next_highlight) = row_highlights.get(ix + 1) {
14508                let highlight = &row_highlights[ix];
14509                if next_highlight
14510                    .range
14511                    .start
14512                    .cmp(&highlight.range.end, &snapshot)
14513                    .is_le()
14514                {
14515                    if next_highlight
14516                        .range
14517                        .end
14518                        .cmp(&highlight.range.end, &snapshot)
14519                        .is_gt()
14520                    {
14521                        row_highlights[ix].range.end = next_highlight.range.end;
14522                    }
14523                    row_highlights.remove(ix + 1);
14524                } else {
14525                    break;
14526                }
14527            }
14528        }
14529    }
14530
14531    /// Remove any highlighted row ranges of the given type that intersect the
14532    /// given ranges.
14533    pub fn remove_highlighted_rows<T: 'static>(
14534        &mut self,
14535        ranges_to_remove: Vec<Range<Anchor>>,
14536        cx: &mut Context<Self>,
14537    ) {
14538        let snapshot = self.buffer().read(cx).snapshot(cx);
14539        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14540        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14541        row_highlights.retain(|highlight| {
14542            while let Some(range_to_remove) = ranges_to_remove.peek() {
14543                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14544                    Ordering::Less | Ordering::Equal => {
14545                        ranges_to_remove.next();
14546                    }
14547                    Ordering::Greater => {
14548                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14549                            Ordering::Less | Ordering::Equal => {
14550                                return false;
14551                            }
14552                            Ordering::Greater => break,
14553                        }
14554                    }
14555                }
14556            }
14557
14558            true
14559        })
14560    }
14561
14562    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14563    pub fn clear_row_highlights<T: 'static>(&mut self) {
14564        self.highlighted_rows.remove(&TypeId::of::<T>());
14565    }
14566
14567    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14568    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14569        self.highlighted_rows
14570            .get(&TypeId::of::<T>())
14571            .map_or(&[] as &[_], |vec| vec.as_slice())
14572            .iter()
14573            .map(|highlight| (highlight.range.clone(), highlight.color))
14574    }
14575
14576    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14577    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14578    /// Allows to ignore certain kinds of highlights.
14579    pub fn highlighted_display_rows(
14580        &self,
14581        window: &mut Window,
14582        cx: &mut App,
14583    ) -> BTreeMap<DisplayRow, Background> {
14584        let snapshot = self.snapshot(window, cx);
14585        let mut used_highlight_orders = HashMap::default();
14586        self.highlighted_rows
14587            .iter()
14588            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14589            .fold(
14590                BTreeMap::<DisplayRow, Background>::new(),
14591                |mut unique_rows, highlight| {
14592                    let start = highlight.range.start.to_display_point(&snapshot);
14593                    let end = highlight.range.end.to_display_point(&snapshot);
14594                    let start_row = start.row().0;
14595                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14596                        && end.column() == 0
14597                    {
14598                        end.row().0.saturating_sub(1)
14599                    } else {
14600                        end.row().0
14601                    };
14602                    for row in start_row..=end_row {
14603                        let used_index =
14604                            used_highlight_orders.entry(row).or_insert(highlight.index);
14605                        if highlight.index >= *used_index {
14606                            *used_index = highlight.index;
14607                            unique_rows.insert(DisplayRow(row), highlight.color.into());
14608                        }
14609                    }
14610                    unique_rows
14611                },
14612            )
14613    }
14614
14615    pub fn highlighted_display_row_for_autoscroll(
14616        &self,
14617        snapshot: &DisplaySnapshot,
14618    ) -> Option<DisplayRow> {
14619        self.highlighted_rows
14620            .values()
14621            .flat_map(|highlighted_rows| highlighted_rows.iter())
14622            .filter_map(|highlight| {
14623                if highlight.should_autoscroll {
14624                    Some(highlight.range.start.to_display_point(snapshot).row())
14625                } else {
14626                    None
14627                }
14628            })
14629            .min()
14630    }
14631
14632    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14633        self.highlight_background::<SearchWithinRange>(
14634            ranges,
14635            |colors| colors.editor_document_highlight_read_background,
14636            cx,
14637        )
14638    }
14639
14640    pub fn set_breadcrumb_header(&mut self, new_header: String) {
14641        self.breadcrumb_header = Some(new_header);
14642    }
14643
14644    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14645        self.clear_background_highlights::<SearchWithinRange>(cx);
14646    }
14647
14648    pub fn highlight_background<T: 'static>(
14649        &mut self,
14650        ranges: &[Range<Anchor>],
14651        color_fetcher: fn(&ThemeColors) -> Hsla,
14652        cx: &mut Context<Self>,
14653    ) {
14654        self.background_highlights
14655            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14656        self.scrollbar_marker_state.dirty = true;
14657        cx.notify();
14658    }
14659
14660    pub fn clear_background_highlights<T: 'static>(
14661        &mut self,
14662        cx: &mut Context<Self>,
14663    ) -> Option<BackgroundHighlight> {
14664        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14665        if !text_highlights.1.is_empty() {
14666            self.scrollbar_marker_state.dirty = true;
14667            cx.notify();
14668        }
14669        Some(text_highlights)
14670    }
14671
14672    pub fn highlight_gutter<T: 'static>(
14673        &mut self,
14674        ranges: &[Range<Anchor>],
14675        color_fetcher: fn(&App) -> Hsla,
14676        cx: &mut Context<Self>,
14677    ) {
14678        self.gutter_highlights
14679            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14680        cx.notify();
14681    }
14682
14683    pub fn clear_gutter_highlights<T: 'static>(
14684        &mut self,
14685        cx: &mut Context<Self>,
14686    ) -> Option<GutterHighlight> {
14687        cx.notify();
14688        self.gutter_highlights.remove(&TypeId::of::<T>())
14689    }
14690
14691    #[cfg(feature = "test-support")]
14692    pub fn all_text_background_highlights(
14693        &self,
14694        window: &mut Window,
14695        cx: &mut Context<Self>,
14696    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14697        let snapshot = self.snapshot(window, cx);
14698        let buffer = &snapshot.buffer_snapshot;
14699        let start = buffer.anchor_before(0);
14700        let end = buffer.anchor_after(buffer.len());
14701        let theme = cx.theme().colors();
14702        self.background_highlights_in_range(start..end, &snapshot, theme)
14703    }
14704
14705    #[cfg(feature = "test-support")]
14706    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14707        let snapshot = self.buffer().read(cx).snapshot(cx);
14708
14709        let highlights = self
14710            .background_highlights
14711            .get(&TypeId::of::<items::BufferSearchHighlights>());
14712
14713        if let Some((_color, ranges)) = highlights {
14714            ranges
14715                .iter()
14716                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14717                .collect_vec()
14718        } else {
14719            vec![]
14720        }
14721    }
14722
14723    fn document_highlights_for_position<'a>(
14724        &'a self,
14725        position: Anchor,
14726        buffer: &'a MultiBufferSnapshot,
14727    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14728        let read_highlights = self
14729            .background_highlights
14730            .get(&TypeId::of::<DocumentHighlightRead>())
14731            .map(|h| &h.1);
14732        let write_highlights = self
14733            .background_highlights
14734            .get(&TypeId::of::<DocumentHighlightWrite>())
14735            .map(|h| &h.1);
14736        let left_position = position.bias_left(buffer);
14737        let right_position = position.bias_right(buffer);
14738        read_highlights
14739            .into_iter()
14740            .chain(write_highlights)
14741            .flat_map(move |ranges| {
14742                let start_ix = match ranges.binary_search_by(|probe| {
14743                    let cmp = probe.end.cmp(&left_position, buffer);
14744                    if cmp.is_ge() {
14745                        Ordering::Greater
14746                    } else {
14747                        Ordering::Less
14748                    }
14749                }) {
14750                    Ok(i) | Err(i) => i,
14751                };
14752
14753                ranges[start_ix..]
14754                    .iter()
14755                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14756            })
14757    }
14758
14759    pub fn has_background_highlights<T: 'static>(&self) -> bool {
14760        self.background_highlights
14761            .get(&TypeId::of::<T>())
14762            .map_or(false, |(_, highlights)| !highlights.is_empty())
14763    }
14764
14765    pub fn background_highlights_in_range(
14766        &self,
14767        search_range: Range<Anchor>,
14768        display_snapshot: &DisplaySnapshot,
14769        theme: &ThemeColors,
14770    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14771        let mut results = Vec::new();
14772        for (color_fetcher, ranges) in self.background_highlights.values() {
14773            let color = color_fetcher(theme);
14774            let start_ix = match ranges.binary_search_by(|probe| {
14775                let cmp = probe
14776                    .end
14777                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14778                if cmp.is_gt() {
14779                    Ordering::Greater
14780                } else {
14781                    Ordering::Less
14782                }
14783            }) {
14784                Ok(i) | Err(i) => i,
14785            };
14786            for range in &ranges[start_ix..] {
14787                if range
14788                    .start
14789                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14790                    .is_ge()
14791                {
14792                    break;
14793                }
14794
14795                let start = range.start.to_display_point(display_snapshot);
14796                let end = range.end.to_display_point(display_snapshot);
14797                results.push((start..end, color))
14798            }
14799        }
14800        results
14801    }
14802
14803    pub fn background_highlight_row_ranges<T: 'static>(
14804        &self,
14805        search_range: Range<Anchor>,
14806        display_snapshot: &DisplaySnapshot,
14807        count: usize,
14808    ) -> Vec<RangeInclusive<DisplayPoint>> {
14809        let mut results = Vec::new();
14810        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14811            return vec![];
14812        };
14813
14814        let start_ix = match ranges.binary_search_by(|probe| {
14815            let cmp = probe
14816                .end
14817                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14818            if cmp.is_gt() {
14819                Ordering::Greater
14820            } else {
14821                Ordering::Less
14822            }
14823        }) {
14824            Ok(i) | Err(i) => i,
14825        };
14826        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14827            if let (Some(start_display), Some(end_display)) = (start, end) {
14828                results.push(
14829                    start_display.to_display_point(display_snapshot)
14830                        ..=end_display.to_display_point(display_snapshot),
14831                );
14832            }
14833        };
14834        let mut start_row: Option<Point> = None;
14835        let mut end_row: Option<Point> = None;
14836        if ranges.len() > count {
14837            return Vec::new();
14838        }
14839        for range in &ranges[start_ix..] {
14840            if range
14841                .start
14842                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14843                .is_ge()
14844            {
14845                break;
14846            }
14847            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14848            if let Some(current_row) = &end_row {
14849                if end.row == current_row.row {
14850                    continue;
14851                }
14852            }
14853            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14854            if start_row.is_none() {
14855                assert_eq!(end_row, None);
14856                start_row = Some(start);
14857                end_row = Some(end);
14858                continue;
14859            }
14860            if let Some(current_end) = end_row.as_mut() {
14861                if start.row > current_end.row + 1 {
14862                    push_region(start_row, end_row);
14863                    start_row = Some(start);
14864                    end_row = Some(end);
14865                } else {
14866                    // Merge two hunks.
14867                    *current_end = end;
14868                }
14869            } else {
14870                unreachable!();
14871            }
14872        }
14873        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14874        push_region(start_row, end_row);
14875        results
14876    }
14877
14878    pub fn gutter_highlights_in_range(
14879        &self,
14880        search_range: Range<Anchor>,
14881        display_snapshot: &DisplaySnapshot,
14882        cx: &App,
14883    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14884        let mut results = Vec::new();
14885        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14886            let color = color_fetcher(cx);
14887            let start_ix = match ranges.binary_search_by(|probe| {
14888                let cmp = probe
14889                    .end
14890                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14891                if cmp.is_gt() {
14892                    Ordering::Greater
14893                } else {
14894                    Ordering::Less
14895                }
14896            }) {
14897                Ok(i) | Err(i) => i,
14898            };
14899            for range in &ranges[start_ix..] {
14900                if range
14901                    .start
14902                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14903                    .is_ge()
14904                {
14905                    break;
14906                }
14907
14908                let start = range.start.to_display_point(display_snapshot);
14909                let end = range.end.to_display_point(display_snapshot);
14910                results.push((start..end, color))
14911            }
14912        }
14913        results
14914    }
14915
14916    /// Get the text ranges corresponding to the redaction query
14917    pub fn redacted_ranges(
14918        &self,
14919        search_range: Range<Anchor>,
14920        display_snapshot: &DisplaySnapshot,
14921        cx: &App,
14922    ) -> Vec<Range<DisplayPoint>> {
14923        display_snapshot
14924            .buffer_snapshot
14925            .redacted_ranges(search_range, |file| {
14926                if let Some(file) = file {
14927                    file.is_private()
14928                        && EditorSettings::get(
14929                            Some(SettingsLocation {
14930                                worktree_id: file.worktree_id(cx),
14931                                path: file.path().as_ref(),
14932                            }),
14933                            cx,
14934                        )
14935                        .redact_private_values
14936                } else {
14937                    false
14938                }
14939            })
14940            .map(|range| {
14941                range.start.to_display_point(display_snapshot)
14942                    ..range.end.to_display_point(display_snapshot)
14943            })
14944            .collect()
14945    }
14946
14947    pub fn highlight_text<T: 'static>(
14948        &mut self,
14949        ranges: Vec<Range<Anchor>>,
14950        style: HighlightStyle,
14951        cx: &mut Context<Self>,
14952    ) {
14953        self.display_map.update(cx, |map, _| {
14954            map.highlight_text(TypeId::of::<T>(), ranges, style)
14955        });
14956        cx.notify();
14957    }
14958
14959    pub(crate) fn highlight_inlays<T: 'static>(
14960        &mut self,
14961        highlights: Vec<InlayHighlight>,
14962        style: HighlightStyle,
14963        cx: &mut Context<Self>,
14964    ) {
14965        self.display_map.update(cx, |map, _| {
14966            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14967        });
14968        cx.notify();
14969    }
14970
14971    pub fn text_highlights<'a, T: 'static>(
14972        &'a self,
14973        cx: &'a App,
14974    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14975        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14976    }
14977
14978    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14979        let cleared = self
14980            .display_map
14981            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14982        if cleared {
14983            cx.notify();
14984        }
14985    }
14986
14987    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14988        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14989            && self.focus_handle.is_focused(window)
14990    }
14991
14992    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14993        self.show_cursor_when_unfocused = is_enabled;
14994        cx.notify();
14995    }
14996
14997    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14998        cx.notify();
14999    }
15000
15001    fn on_buffer_event(
15002        &mut self,
15003        multibuffer: &Entity<MultiBuffer>,
15004        event: &multi_buffer::Event,
15005        window: &mut Window,
15006        cx: &mut Context<Self>,
15007    ) {
15008        match event {
15009            multi_buffer::Event::Edited {
15010                singleton_buffer_edited,
15011                edited_buffer: buffer_edited,
15012            } => {
15013                self.scrollbar_marker_state.dirty = true;
15014                self.active_indent_guides_state.dirty = true;
15015                self.refresh_active_diagnostics(cx);
15016                self.refresh_code_actions(window, cx);
15017                if self.has_active_inline_completion() {
15018                    self.update_visible_inline_completion(window, cx);
15019                }
15020                if let Some(buffer) = buffer_edited {
15021                    let buffer_id = buffer.read(cx).remote_id();
15022                    if !self.registered_buffers.contains_key(&buffer_id) {
15023                        if let Some(project) = self.project.as_ref() {
15024                            project.update(cx, |project, cx| {
15025                                self.registered_buffers.insert(
15026                                    buffer_id,
15027                                    project.register_buffer_with_language_servers(&buffer, cx),
15028                                );
15029                            })
15030                        }
15031                    }
15032                }
15033                cx.emit(EditorEvent::BufferEdited);
15034                cx.emit(SearchEvent::MatchesInvalidated);
15035                if *singleton_buffer_edited {
15036                    if let Some(project) = &self.project {
15037                        #[allow(clippy::mutable_key_type)]
15038                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15039                            multibuffer
15040                                .all_buffers()
15041                                .into_iter()
15042                                .filter_map(|buffer| {
15043                                    buffer.update(cx, |buffer, cx| {
15044                                        let language = buffer.language()?;
15045                                        let should_discard = project.update(cx, |project, cx| {
15046                                            project.is_local()
15047                                                && !project.has_language_servers_for(buffer, cx)
15048                                        });
15049                                        should_discard.not().then_some(language.clone())
15050                                    })
15051                                })
15052                                .collect::<HashSet<_>>()
15053                        });
15054                        if !languages_affected.is_empty() {
15055                            self.refresh_inlay_hints(
15056                                InlayHintRefreshReason::BufferEdited(languages_affected),
15057                                cx,
15058                            );
15059                        }
15060                    }
15061                }
15062
15063                let Some(project) = &self.project else { return };
15064                let (telemetry, is_via_ssh) = {
15065                    let project = project.read(cx);
15066                    let telemetry = project.client().telemetry().clone();
15067                    let is_via_ssh = project.is_via_ssh();
15068                    (telemetry, is_via_ssh)
15069                };
15070                refresh_linked_ranges(self, window, cx);
15071                telemetry.log_edit_event("editor", is_via_ssh);
15072            }
15073            multi_buffer::Event::ExcerptsAdded {
15074                buffer,
15075                predecessor,
15076                excerpts,
15077            } => {
15078                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15079                let buffer_id = buffer.read(cx).remote_id();
15080                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15081                    if let Some(project) = &self.project {
15082                        get_uncommitted_diff_for_buffer(
15083                            project,
15084                            [buffer.clone()],
15085                            self.buffer.clone(),
15086                            cx,
15087                        )
15088                        .detach();
15089                    }
15090                }
15091                cx.emit(EditorEvent::ExcerptsAdded {
15092                    buffer: buffer.clone(),
15093                    predecessor: *predecessor,
15094                    excerpts: excerpts.clone(),
15095                });
15096                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15097            }
15098            multi_buffer::Event::ExcerptsRemoved { ids } => {
15099                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15100                let buffer = self.buffer.read(cx);
15101                self.registered_buffers
15102                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15103                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15104            }
15105            multi_buffer::Event::ExcerptsEdited { ids } => {
15106                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15107            }
15108            multi_buffer::Event::ExcerptsExpanded { ids } => {
15109                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15110                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15111            }
15112            multi_buffer::Event::Reparsed(buffer_id) => {
15113                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15114
15115                cx.emit(EditorEvent::Reparsed(*buffer_id));
15116            }
15117            multi_buffer::Event::DiffHunksToggled => {
15118                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15119            }
15120            multi_buffer::Event::LanguageChanged(buffer_id) => {
15121                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15122                cx.emit(EditorEvent::Reparsed(*buffer_id));
15123                cx.notify();
15124            }
15125            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15126            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15127            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15128                cx.emit(EditorEvent::TitleChanged)
15129            }
15130            // multi_buffer::Event::DiffBaseChanged => {
15131            //     self.scrollbar_marker_state.dirty = true;
15132            //     cx.emit(EditorEvent::DiffBaseChanged);
15133            //     cx.notify();
15134            // }
15135            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15136            multi_buffer::Event::DiagnosticsUpdated => {
15137                self.refresh_active_diagnostics(cx);
15138                self.refresh_inline_diagnostics(true, window, cx);
15139                self.scrollbar_marker_state.dirty = true;
15140                cx.notify();
15141            }
15142            _ => {}
15143        };
15144    }
15145
15146    fn on_display_map_changed(
15147        &mut self,
15148        _: Entity<DisplayMap>,
15149        _: &mut Window,
15150        cx: &mut Context<Self>,
15151    ) {
15152        cx.notify();
15153    }
15154
15155    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15156        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15157        self.refresh_inline_completion(true, false, window, cx);
15158        self.refresh_inlay_hints(
15159            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15160                self.selections.newest_anchor().head(),
15161                &self.buffer.read(cx).snapshot(cx),
15162                cx,
15163            )),
15164            cx,
15165        );
15166
15167        let old_cursor_shape = self.cursor_shape;
15168
15169        {
15170            let editor_settings = EditorSettings::get_global(cx);
15171            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15172            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15173            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15174        }
15175
15176        if old_cursor_shape != self.cursor_shape {
15177            cx.emit(EditorEvent::CursorShapeChanged);
15178        }
15179
15180        let project_settings = ProjectSettings::get_global(cx);
15181        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15182
15183        if self.mode == EditorMode::Full {
15184            let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15185            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15186            if self.show_inline_diagnostics != show_inline_diagnostics {
15187                self.show_inline_diagnostics = show_inline_diagnostics;
15188                self.refresh_inline_diagnostics(false, window, cx);
15189            }
15190
15191            if self.git_blame_inline_enabled != inline_blame_enabled {
15192                self.toggle_git_blame_inline_internal(false, window, cx);
15193            }
15194        }
15195
15196        cx.notify();
15197    }
15198
15199    pub fn set_searchable(&mut self, searchable: bool) {
15200        self.searchable = searchable;
15201    }
15202
15203    pub fn searchable(&self) -> bool {
15204        self.searchable
15205    }
15206
15207    fn open_proposed_changes_editor(
15208        &mut self,
15209        _: &OpenProposedChangesEditor,
15210        window: &mut Window,
15211        cx: &mut Context<Self>,
15212    ) {
15213        let Some(workspace) = self.workspace() else {
15214            cx.propagate();
15215            return;
15216        };
15217
15218        let selections = self.selections.all::<usize>(cx);
15219        let multi_buffer = self.buffer.read(cx);
15220        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15221        let mut new_selections_by_buffer = HashMap::default();
15222        for selection in selections {
15223            for (buffer, range, _) in
15224                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15225            {
15226                let mut range = range.to_point(buffer);
15227                range.start.column = 0;
15228                range.end.column = buffer.line_len(range.end.row);
15229                new_selections_by_buffer
15230                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15231                    .or_insert(Vec::new())
15232                    .push(range)
15233            }
15234        }
15235
15236        let proposed_changes_buffers = new_selections_by_buffer
15237            .into_iter()
15238            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15239            .collect::<Vec<_>>();
15240        let proposed_changes_editor = cx.new(|cx| {
15241            ProposedChangesEditor::new(
15242                "Proposed changes",
15243                proposed_changes_buffers,
15244                self.project.clone(),
15245                window,
15246                cx,
15247            )
15248        });
15249
15250        window.defer(cx, move |window, cx| {
15251            workspace.update(cx, |workspace, cx| {
15252                workspace.active_pane().update(cx, |pane, cx| {
15253                    pane.add_item(
15254                        Box::new(proposed_changes_editor),
15255                        true,
15256                        true,
15257                        None,
15258                        window,
15259                        cx,
15260                    );
15261                });
15262            });
15263        });
15264    }
15265
15266    pub fn open_excerpts_in_split(
15267        &mut self,
15268        _: &OpenExcerptsSplit,
15269        window: &mut Window,
15270        cx: &mut Context<Self>,
15271    ) {
15272        self.open_excerpts_common(None, true, window, cx)
15273    }
15274
15275    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15276        self.open_excerpts_common(None, false, window, cx)
15277    }
15278
15279    fn open_excerpts_common(
15280        &mut self,
15281        jump_data: Option<JumpData>,
15282        split: bool,
15283        window: &mut Window,
15284        cx: &mut Context<Self>,
15285    ) {
15286        let Some(workspace) = self.workspace() else {
15287            cx.propagate();
15288            return;
15289        };
15290
15291        if self.buffer.read(cx).is_singleton() {
15292            cx.propagate();
15293            return;
15294        }
15295
15296        let mut new_selections_by_buffer = HashMap::default();
15297        match &jump_data {
15298            Some(JumpData::MultiBufferPoint {
15299                excerpt_id,
15300                position,
15301                anchor,
15302                line_offset_from_top,
15303            }) => {
15304                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15305                if let Some(buffer) = multi_buffer_snapshot
15306                    .buffer_id_for_excerpt(*excerpt_id)
15307                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15308                {
15309                    let buffer_snapshot = buffer.read(cx).snapshot();
15310                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15311                        language::ToPoint::to_point(anchor, &buffer_snapshot)
15312                    } else {
15313                        buffer_snapshot.clip_point(*position, Bias::Left)
15314                    };
15315                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15316                    new_selections_by_buffer.insert(
15317                        buffer,
15318                        (
15319                            vec![jump_to_offset..jump_to_offset],
15320                            Some(*line_offset_from_top),
15321                        ),
15322                    );
15323                }
15324            }
15325            Some(JumpData::MultiBufferRow {
15326                row,
15327                line_offset_from_top,
15328            }) => {
15329                let point = MultiBufferPoint::new(row.0, 0);
15330                if let Some((buffer, buffer_point, _)) =
15331                    self.buffer.read(cx).point_to_buffer_point(point, cx)
15332                {
15333                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15334                    new_selections_by_buffer
15335                        .entry(buffer)
15336                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
15337                        .0
15338                        .push(buffer_offset..buffer_offset)
15339                }
15340            }
15341            None => {
15342                let selections = self.selections.all::<usize>(cx);
15343                let multi_buffer = self.buffer.read(cx);
15344                for selection in selections {
15345                    for (snapshot, range, _, anchor) in multi_buffer
15346                        .snapshot(cx)
15347                        .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15348                    {
15349                        if let Some(anchor) = anchor {
15350                            // selection is in a deleted hunk
15351                            let Some(buffer_id) = anchor.buffer_id else {
15352                                continue;
15353                            };
15354                            let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15355                                continue;
15356                            };
15357                            let offset = text::ToOffset::to_offset(
15358                                &anchor.text_anchor,
15359                                &buffer_handle.read(cx).snapshot(),
15360                            );
15361                            let range = offset..offset;
15362                            new_selections_by_buffer
15363                                .entry(buffer_handle)
15364                                .or_insert((Vec::new(), None))
15365                                .0
15366                                .push(range)
15367                        } else {
15368                            let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15369                            else {
15370                                continue;
15371                            };
15372                            new_selections_by_buffer
15373                                .entry(buffer_handle)
15374                                .or_insert((Vec::new(), None))
15375                                .0
15376                                .push(range)
15377                        }
15378                    }
15379                }
15380            }
15381        }
15382
15383        if new_selections_by_buffer.is_empty() {
15384            return;
15385        }
15386
15387        // We defer the pane interaction because we ourselves are a workspace item
15388        // and activating a new item causes the pane to call a method on us reentrantly,
15389        // which panics if we're on the stack.
15390        window.defer(cx, move |window, cx| {
15391            workspace.update(cx, |workspace, cx| {
15392                let pane = if split {
15393                    workspace.adjacent_pane(window, cx)
15394                } else {
15395                    workspace.active_pane().clone()
15396                };
15397
15398                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15399                    let editor = buffer
15400                        .read(cx)
15401                        .file()
15402                        .is_none()
15403                        .then(|| {
15404                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15405                            // so `workspace.open_project_item` will never find them, always opening a new editor.
15406                            // Instead, we try to activate the existing editor in the pane first.
15407                            let (editor, pane_item_index) =
15408                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
15409                                    let editor = item.downcast::<Editor>()?;
15410                                    let singleton_buffer =
15411                                        editor.read(cx).buffer().read(cx).as_singleton()?;
15412                                    if singleton_buffer == buffer {
15413                                        Some((editor, i))
15414                                    } else {
15415                                        None
15416                                    }
15417                                })?;
15418                            pane.update(cx, |pane, cx| {
15419                                pane.activate_item(pane_item_index, true, true, window, cx)
15420                            });
15421                            Some(editor)
15422                        })
15423                        .flatten()
15424                        .unwrap_or_else(|| {
15425                            workspace.open_project_item::<Self>(
15426                                pane.clone(),
15427                                buffer,
15428                                true,
15429                                true,
15430                                window,
15431                                cx,
15432                            )
15433                        });
15434
15435                    editor.update(cx, |editor, cx| {
15436                        let autoscroll = match scroll_offset {
15437                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15438                            None => Autoscroll::newest(),
15439                        };
15440                        let nav_history = editor.nav_history.take();
15441                        editor.change_selections(Some(autoscroll), window, cx, |s| {
15442                            s.select_ranges(ranges);
15443                        });
15444                        editor.nav_history = nav_history;
15445                    });
15446                }
15447            })
15448        });
15449    }
15450
15451    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15452        let snapshot = self.buffer.read(cx).read(cx);
15453        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15454        Some(
15455            ranges
15456                .iter()
15457                .map(move |range| {
15458                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15459                })
15460                .collect(),
15461        )
15462    }
15463
15464    fn selection_replacement_ranges(
15465        &self,
15466        range: Range<OffsetUtf16>,
15467        cx: &mut App,
15468    ) -> Vec<Range<OffsetUtf16>> {
15469        let selections = self.selections.all::<OffsetUtf16>(cx);
15470        let newest_selection = selections
15471            .iter()
15472            .max_by_key(|selection| selection.id)
15473            .unwrap();
15474        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15475        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15476        let snapshot = self.buffer.read(cx).read(cx);
15477        selections
15478            .into_iter()
15479            .map(|mut selection| {
15480                selection.start.0 =
15481                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
15482                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15483                snapshot.clip_offset_utf16(selection.start, Bias::Left)
15484                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15485            })
15486            .collect()
15487    }
15488
15489    fn report_editor_event(
15490        &self,
15491        event_type: &'static str,
15492        file_extension: Option<String>,
15493        cx: &App,
15494    ) {
15495        if cfg!(any(test, feature = "test-support")) {
15496            return;
15497        }
15498
15499        let Some(project) = &self.project else { return };
15500
15501        // If None, we are in a file without an extension
15502        let file = self
15503            .buffer
15504            .read(cx)
15505            .as_singleton()
15506            .and_then(|b| b.read(cx).file());
15507        let file_extension = file_extension.or(file
15508            .as_ref()
15509            .and_then(|file| Path::new(file.file_name(cx)).extension())
15510            .and_then(|e| e.to_str())
15511            .map(|a| a.to_string()));
15512
15513        let vim_mode = cx
15514            .global::<SettingsStore>()
15515            .raw_user_settings()
15516            .get("vim_mode")
15517            == Some(&serde_json::Value::Bool(true));
15518
15519        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15520        let copilot_enabled = edit_predictions_provider
15521            == language::language_settings::EditPredictionProvider::Copilot;
15522        let copilot_enabled_for_language = self
15523            .buffer
15524            .read(cx)
15525            .settings_at(0, cx)
15526            .show_edit_predictions;
15527
15528        let project = project.read(cx);
15529        telemetry::event!(
15530            event_type,
15531            file_extension,
15532            vim_mode,
15533            copilot_enabled,
15534            copilot_enabled_for_language,
15535            edit_predictions_provider,
15536            is_via_ssh = project.is_via_ssh(),
15537        );
15538    }
15539
15540    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15541    /// with each line being an array of {text, highlight} objects.
15542    fn copy_highlight_json(
15543        &mut self,
15544        _: &CopyHighlightJson,
15545        window: &mut Window,
15546        cx: &mut Context<Self>,
15547    ) {
15548        #[derive(Serialize)]
15549        struct Chunk<'a> {
15550            text: String,
15551            highlight: Option<&'a str>,
15552        }
15553
15554        let snapshot = self.buffer.read(cx).snapshot(cx);
15555        let range = self
15556            .selected_text_range(false, window, cx)
15557            .and_then(|selection| {
15558                if selection.range.is_empty() {
15559                    None
15560                } else {
15561                    Some(selection.range)
15562                }
15563            })
15564            .unwrap_or_else(|| 0..snapshot.len());
15565
15566        let chunks = snapshot.chunks(range, true);
15567        let mut lines = Vec::new();
15568        let mut line: VecDeque<Chunk> = VecDeque::new();
15569
15570        let Some(style) = self.style.as_ref() else {
15571            return;
15572        };
15573
15574        for chunk in chunks {
15575            let highlight = chunk
15576                .syntax_highlight_id
15577                .and_then(|id| id.name(&style.syntax));
15578            let mut chunk_lines = chunk.text.split('\n').peekable();
15579            while let Some(text) = chunk_lines.next() {
15580                let mut merged_with_last_token = false;
15581                if let Some(last_token) = line.back_mut() {
15582                    if last_token.highlight == highlight {
15583                        last_token.text.push_str(text);
15584                        merged_with_last_token = true;
15585                    }
15586                }
15587
15588                if !merged_with_last_token {
15589                    line.push_back(Chunk {
15590                        text: text.into(),
15591                        highlight,
15592                    });
15593                }
15594
15595                if chunk_lines.peek().is_some() {
15596                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
15597                        line.pop_front();
15598                    }
15599                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
15600                        line.pop_back();
15601                    }
15602
15603                    lines.push(mem::take(&mut line));
15604                }
15605            }
15606        }
15607
15608        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15609            return;
15610        };
15611        cx.write_to_clipboard(ClipboardItem::new_string(lines));
15612    }
15613
15614    pub fn open_context_menu(
15615        &mut self,
15616        _: &OpenContextMenu,
15617        window: &mut Window,
15618        cx: &mut Context<Self>,
15619    ) {
15620        self.request_autoscroll(Autoscroll::newest(), cx);
15621        let position = self.selections.newest_display(cx).start;
15622        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15623    }
15624
15625    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15626        &self.inlay_hint_cache
15627    }
15628
15629    pub fn replay_insert_event(
15630        &mut self,
15631        text: &str,
15632        relative_utf16_range: Option<Range<isize>>,
15633        window: &mut Window,
15634        cx: &mut Context<Self>,
15635    ) {
15636        if !self.input_enabled {
15637            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15638            return;
15639        }
15640        if let Some(relative_utf16_range) = relative_utf16_range {
15641            let selections = self.selections.all::<OffsetUtf16>(cx);
15642            self.change_selections(None, window, cx, |s| {
15643                let new_ranges = selections.into_iter().map(|range| {
15644                    let start = OffsetUtf16(
15645                        range
15646                            .head()
15647                            .0
15648                            .saturating_add_signed(relative_utf16_range.start),
15649                    );
15650                    let end = OffsetUtf16(
15651                        range
15652                            .head()
15653                            .0
15654                            .saturating_add_signed(relative_utf16_range.end),
15655                    );
15656                    start..end
15657                });
15658                s.select_ranges(new_ranges);
15659            });
15660        }
15661
15662        self.handle_input(text, window, cx);
15663    }
15664
15665    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15666        let Some(provider) = self.semantics_provider.as_ref() else {
15667            return false;
15668        };
15669
15670        let mut supports = false;
15671        self.buffer().update(cx, |this, cx| {
15672            this.for_each_buffer(|buffer| {
15673                supports |= provider.supports_inlay_hints(buffer, cx);
15674            });
15675        });
15676
15677        supports
15678    }
15679
15680    pub fn is_focused(&self, window: &Window) -> bool {
15681        self.focus_handle.is_focused(window)
15682    }
15683
15684    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15685        cx.emit(EditorEvent::Focused);
15686
15687        if let Some(descendant) = self
15688            .last_focused_descendant
15689            .take()
15690            .and_then(|descendant| descendant.upgrade())
15691        {
15692            window.focus(&descendant);
15693        } else {
15694            if let Some(blame) = self.blame.as_ref() {
15695                blame.update(cx, GitBlame::focus)
15696            }
15697
15698            self.blink_manager.update(cx, BlinkManager::enable);
15699            self.show_cursor_names(window, cx);
15700            self.buffer.update(cx, |buffer, cx| {
15701                buffer.finalize_last_transaction(cx);
15702                if self.leader_peer_id.is_none() {
15703                    buffer.set_active_selections(
15704                        &self.selections.disjoint_anchors(),
15705                        self.selections.line_mode,
15706                        self.cursor_shape,
15707                        cx,
15708                    );
15709                }
15710            });
15711        }
15712    }
15713
15714    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15715        cx.emit(EditorEvent::FocusedIn)
15716    }
15717
15718    fn handle_focus_out(
15719        &mut self,
15720        event: FocusOutEvent,
15721        _window: &mut Window,
15722        _cx: &mut Context<Self>,
15723    ) {
15724        if event.blurred != self.focus_handle {
15725            self.last_focused_descendant = Some(event.blurred);
15726        }
15727    }
15728
15729    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15730        self.blink_manager.update(cx, BlinkManager::disable);
15731        self.buffer
15732            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15733
15734        if let Some(blame) = self.blame.as_ref() {
15735            blame.update(cx, GitBlame::blur)
15736        }
15737        if !self.hover_state.focused(window, cx) {
15738            hide_hover(self, cx);
15739        }
15740        if !self
15741            .context_menu
15742            .borrow()
15743            .as_ref()
15744            .is_some_and(|context_menu| context_menu.focused(window, cx))
15745        {
15746            self.hide_context_menu(window, cx);
15747        }
15748        self.discard_inline_completion(false, cx);
15749        cx.emit(EditorEvent::Blurred);
15750        cx.notify();
15751    }
15752
15753    pub fn register_action<A: Action>(
15754        &mut self,
15755        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15756    ) -> Subscription {
15757        let id = self.next_editor_action_id.post_inc();
15758        let listener = Arc::new(listener);
15759        self.editor_actions.borrow_mut().insert(
15760            id,
15761            Box::new(move |window, _| {
15762                let listener = listener.clone();
15763                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15764                    let action = action.downcast_ref().unwrap();
15765                    if phase == DispatchPhase::Bubble {
15766                        listener(action, window, cx)
15767                    }
15768                })
15769            }),
15770        );
15771
15772        let editor_actions = self.editor_actions.clone();
15773        Subscription::new(move || {
15774            editor_actions.borrow_mut().remove(&id);
15775        })
15776    }
15777
15778    pub fn file_header_size(&self) -> u32 {
15779        FILE_HEADER_HEIGHT
15780    }
15781
15782    pub fn revert(
15783        &mut self,
15784        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15785        window: &mut Window,
15786        cx: &mut Context<Self>,
15787    ) {
15788        self.buffer().update(cx, |multi_buffer, cx| {
15789            for (buffer_id, changes) in revert_changes {
15790                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15791                    buffer.update(cx, |buffer, cx| {
15792                        buffer.edit(
15793                            changes.into_iter().map(|(range, text)| {
15794                                (range, text.to_string().map(Arc::<str>::from))
15795                            }),
15796                            None,
15797                            cx,
15798                        );
15799                    });
15800                }
15801            }
15802        });
15803        self.change_selections(None, window, cx, |selections| selections.refresh());
15804    }
15805
15806    pub fn to_pixel_point(
15807        &self,
15808        source: multi_buffer::Anchor,
15809        editor_snapshot: &EditorSnapshot,
15810        window: &mut Window,
15811    ) -> Option<gpui::Point<Pixels>> {
15812        let source_point = source.to_display_point(editor_snapshot);
15813        self.display_to_pixel_point(source_point, editor_snapshot, window)
15814    }
15815
15816    pub fn display_to_pixel_point(
15817        &self,
15818        source: DisplayPoint,
15819        editor_snapshot: &EditorSnapshot,
15820        window: &mut Window,
15821    ) -> Option<gpui::Point<Pixels>> {
15822        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15823        let text_layout_details = self.text_layout_details(window);
15824        let scroll_top = text_layout_details
15825            .scroll_anchor
15826            .scroll_position(editor_snapshot)
15827            .y;
15828
15829        if source.row().as_f32() < scroll_top.floor() {
15830            return None;
15831        }
15832        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15833        let source_y = line_height * (source.row().as_f32() - scroll_top);
15834        Some(gpui::Point::new(source_x, source_y))
15835    }
15836
15837    pub fn has_visible_completions_menu(&self) -> bool {
15838        !self.edit_prediction_preview_is_active()
15839            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15840                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15841            })
15842    }
15843
15844    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15845        self.addons
15846            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15847    }
15848
15849    pub fn unregister_addon<T: Addon>(&mut self) {
15850        self.addons.remove(&std::any::TypeId::of::<T>());
15851    }
15852
15853    pub fn addon<T: Addon>(&self) -> Option<&T> {
15854        let type_id = std::any::TypeId::of::<T>();
15855        self.addons
15856            .get(&type_id)
15857            .and_then(|item| item.to_any().downcast_ref::<T>())
15858    }
15859
15860    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15861        let text_layout_details = self.text_layout_details(window);
15862        let style = &text_layout_details.editor_style;
15863        let font_id = window.text_system().resolve_font(&style.text.font());
15864        let font_size = style.text.font_size.to_pixels(window.rem_size());
15865        let line_height = style.text.line_height_in_pixels(window.rem_size());
15866        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15867
15868        gpui::Size::new(em_width, line_height)
15869    }
15870
15871    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15872        self.load_diff_task.clone()
15873    }
15874
15875    fn read_selections_from_db(
15876        &mut self,
15877        item_id: u64,
15878        workspace_id: WorkspaceId,
15879        window: &mut Window,
15880        cx: &mut Context<Editor>,
15881    ) {
15882        if !self.is_singleton(cx)
15883            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15884        {
15885            return;
15886        }
15887        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15888            return;
15889        };
15890        if selections.is_empty() {
15891            return;
15892        }
15893
15894        let snapshot = self.buffer.read(cx).snapshot(cx);
15895        self.change_selections(None, window, cx, |s| {
15896            s.select_ranges(selections.into_iter().map(|(start, end)| {
15897                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15898            }));
15899        });
15900    }
15901}
15902
15903fn insert_extra_newline_brackets(
15904    buffer: &MultiBufferSnapshot,
15905    range: Range<usize>,
15906    language: &language::LanguageScope,
15907) -> bool {
15908    let leading_whitespace_len = buffer
15909        .reversed_chars_at(range.start)
15910        .take_while(|c| c.is_whitespace() && *c != '\n')
15911        .map(|c| c.len_utf8())
15912        .sum::<usize>();
15913    let trailing_whitespace_len = buffer
15914        .chars_at(range.end)
15915        .take_while(|c| c.is_whitespace() && *c != '\n')
15916        .map(|c| c.len_utf8())
15917        .sum::<usize>();
15918    let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15919
15920    language.brackets().any(|(pair, enabled)| {
15921        let pair_start = pair.start.trim_end();
15922        let pair_end = pair.end.trim_start();
15923
15924        enabled
15925            && pair.newline
15926            && buffer.contains_str_at(range.end, pair_end)
15927            && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15928    })
15929}
15930
15931fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15932    let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15933        [(buffer, range, _)] => (*buffer, range.clone()),
15934        _ => return false,
15935    };
15936    let pair = {
15937        let mut result: Option<BracketMatch> = None;
15938
15939        for pair in buffer
15940            .all_bracket_ranges(range.clone())
15941            .filter(move |pair| {
15942                pair.open_range.start <= range.start && pair.close_range.end >= range.end
15943            })
15944        {
15945            let len = pair.close_range.end - pair.open_range.start;
15946
15947            if let Some(existing) = &result {
15948                let existing_len = existing.close_range.end - existing.open_range.start;
15949                if len > existing_len {
15950                    continue;
15951                }
15952            }
15953
15954            result = Some(pair);
15955        }
15956
15957        result
15958    };
15959    let Some(pair) = pair else {
15960        return false;
15961    };
15962    pair.newline_only
15963        && buffer
15964            .chars_for_range(pair.open_range.end..range.start)
15965            .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15966            .all(|c| c.is_whitespace() && c != '\n')
15967}
15968
15969fn get_uncommitted_diff_for_buffer(
15970    project: &Entity<Project>,
15971    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15972    buffer: Entity<MultiBuffer>,
15973    cx: &mut App,
15974) -> Task<()> {
15975    let mut tasks = Vec::new();
15976    project.update(cx, |project, cx| {
15977        for buffer in buffers {
15978            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15979        }
15980    });
15981    cx.spawn(|mut cx| async move {
15982        let diffs = futures::future::join_all(tasks).await;
15983        buffer
15984            .update(&mut cx, |buffer, cx| {
15985                for diff in diffs.into_iter().flatten() {
15986                    buffer.add_diff(diff, cx);
15987                }
15988            })
15989            .ok();
15990    })
15991}
15992
15993fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15994    let tab_size = tab_size.get() as usize;
15995    let mut width = offset;
15996
15997    for ch in text.chars() {
15998        width += if ch == '\t' {
15999            tab_size - (width % tab_size)
16000        } else {
16001            1
16002        };
16003    }
16004
16005    width - offset
16006}
16007
16008#[cfg(test)]
16009mod tests {
16010    use super::*;
16011
16012    #[test]
16013    fn test_string_size_with_expanded_tabs() {
16014        let nz = |val| NonZeroU32::new(val).unwrap();
16015        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16016        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16017        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16018        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16019        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16020        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16021        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16022        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16023    }
16024}
16025
16026/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16027struct WordBreakingTokenizer<'a> {
16028    input: &'a str,
16029}
16030
16031impl<'a> WordBreakingTokenizer<'a> {
16032    fn new(input: &'a str) -> Self {
16033        Self { input }
16034    }
16035}
16036
16037fn is_char_ideographic(ch: char) -> bool {
16038    use unicode_script::Script::*;
16039    use unicode_script::UnicodeScript;
16040    matches!(ch.script(), Han | Tangut | Yi)
16041}
16042
16043fn is_grapheme_ideographic(text: &str) -> bool {
16044    text.chars().any(is_char_ideographic)
16045}
16046
16047fn is_grapheme_whitespace(text: &str) -> bool {
16048    text.chars().any(|x| x.is_whitespace())
16049}
16050
16051fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16052    text.chars().next().map_or(false, |ch| {
16053        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16054    })
16055}
16056
16057#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16058struct WordBreakToken<'a> {
16059    token: &'a str,
16060    grapheme_len: usize,
16061    is_whitespace: bool,
16062}
16063
16064impl<'a> Iterator for WordBreakingTokenizer<'a> {
16065    /// Yields a span, the count of graphemes in the token, and whether it was
16066    /// whitespace. Note that it also breaks at word boundaries.
16067    type Item = WordBreakToken<'a>;
16068
16069    fn next(&mut self) -> Option<Self::Item> {
16070        use unicode_segmentation::UnicodeSegmentation;
16071        if self.input.is_empty() {
16072            return None;
16073        }
16074
16075        let mut iter = self.input.graphemes(true).peekable();
16076        let mut offset = 0;
16077        let mut graphemes = 0;
16078        if let Some(first_grapheme) = iter.next() {
16079            let is_whitespace = is_grapheme_whitespace(first_grapheme);
16080            offset += first_grapheme.len();
16081            graphemes += 1;
16082            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16083                if let Some(grapheme) = iter.peek().copied() {
16084                    if should_stay_with_preceding_ideograph(grapheme) {
16085                        offset += grapheme.len();
16086                        graphemes += 1;
16087                    }
16088                }
16089            } else {
16090                let mut words = self.input[offset..].split_word_bound_indices().peekable();
16091                let mut next_word_bound = words.peek().copied();
16092                if next_word_bound.map_or(false, |(i, _)| i == 0) {
16093                    next_word_bound = words.next();
16094                }
16095                while let Some(grapheme) = iter.peek().copied() {
16096                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
16097                        break;
16098                    };
16099                    if is_grapheme_whitespace(grapheme) != is_whitespace {
16100                        break;
16101                    };
16102                    offset += grapheme.len();
16103                    graphemes += 1;
16104                    iter.next();
16105                }
16106            }
16107            let token = &self.input[..offset];
16108            self.input = &self.input[offset..];
16109            if is_whitespace {
16110                Some(WordBreakToken {
16111                    token: " ",
16112                    grapheme_len: 1,
16113                    is_whitespace: true,
16114                })
16115            } else {
16116                Some(WordBreakToken {
16117                    token,
16118                    grapheme_len: graphemes,
16119                    is_whitespace: false,
16120                })
16121            }
16122        } else {
16123            None
16124        }
16125    }
16126}
16127
16128#[test]
16129fn test_word_breaking_tokenizer() {
16130    let tests: &[(&str, &[(&str, usize, bool)])] = &[
16131        ("", &[]),
16132        ("  ", &[(" ", 1, true)]),
16133        ("Ʒ", &[("Ʒ", 1, false)]),
16134        ("Ǽ", &[("Ǽ", 1, false)]),
16135        ("", &[("", 1, false)]),
16136        ("⋑⋑", &[("⋑⋑", 2, false)]),
16137        (
16138            "原理,进而",
16139            &[
16140                ("", 1, false),
16141                ("理,", 2, false),
16142                ("", 1, false),
16143                ("", 1, false),
16144            ],
16145        ),
16146        (
16147            "hello world",
16148            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16149        ),
16150        (
16151            "hello, world",
16152            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16153        ),
16154        (
16155            "  hello world",
16156            &[
16157                (" ", 1, true),
16158                ("hello", 5, false),
16159                (" ", 1, true),
16160                ("world", 5, false),
16161            ],
16162        ),
16163        (
16164            "这是什么 \n 钢笔",
16165            &[
16166                ("", 1, false),
16167                ("", 1, false),
16168                ("", 1, false),
16169                ("", 1, false),
16170                (" ", 1, true),
16171                ("", 1, false),
16172                ("", 1, false),
16173            ],
16174        ),
16175        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16176    ];
16177
16178    for (input, result) in tests {
16179        assert_eq!(
16180            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16181            result
16182                .iter()
16183                .copied()
16184                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16185                    token,
16186                    grapheme_len,
16187                    is_whitespace,
16188                })
16189                .collect::<Vec<_>>()
16190        );
16191    }
16192}
16193
16194fn wrap_with_prefix(
16195    line_prefix: String,
16196    unwrapped_text: String,
16197    wrap_column: usize,
16198    tab_size: NonZeroU32,
16199) -> String {
16200    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16201    let mut wrapped_text = String::new();
16202    let mut current_line = line_prefix.clone();
16203
16204    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16205    let mut current_line_len = line_prefix_len;
16206    for WordBreakToken {
16207        token,
16208        grapheme_len,
16209        is_whitespace,
16210    } in tokenizer
16211    {
16212        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16213            wrapped_text.push_str(current_line.trim_end());
16214            wrapped_text.push('\n');
16215            current_line.truncate(line_prefix.len());
16216            current_line_len = line_prefix_len;
16217            if !is_whitespace {
16218                current_line.push_str(token);
16219                current_line_len += grapheme_len;
16220            }
16221        } else if !is_whitespace {
16222            current_line.push_str(token);
16223            current_line_len += grapheme_len;
16224        } else if current_line_len != line_prefix_len {
16225            current_line.push(' ');
16226            current_line_len += 1;
16227        }
16228    }
16229
16230    if !current_line.is_empty() {
16231        wrapped_text.push_str(&current_line);
16232    }
16233    wrapped_text
16234}
16235
16236#[test]
16237fn test_wrap_with_prefix() {
16238    assert_eq!(
16239        wrap_with_prefix(
16240            "# ".to_string(),
16241            "abcdefg".to_string(),
16242            4,
16243            NonZeroU32::new(4).unwrap()
16244        ),
16245        "# abcdefg"
16246    );
16247    assert_eq!(
16248        wrap_with_prefix(
16249            "".to_string(),
16250            "\thello world".to_string(),
16251            8,
16252            NonZeroU32::new(4).unwrap()
16253        ),
16254        "hello\nworld"
16255    );
16256    assert_eq!(
16257        wrap_with_prefix(
16258            "// ".to_string(),
16259            "xx \nyy zz aa bb cc".to_string(),
16260            12,
16261            NonZeroU32::new(4).unwrap()
16262        ),
16263        "// xx yy zz\n// aa bb cc"
16264    );
16265    assert_eq!(
16266        wrap_with_prefix(
16267            String::new(),
16268            "这是什么 \n 钢笔".to_string(),
16269            3,
16270            NonZeroU32::new(4).unwrap()
16271        ),
16272        "这是什\n么 钢\n"
16273    );
16274}
16275
16276pub trait CollaborationHub {
16277    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16278    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16279    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16280}
16281
16282impl CollaborationHub for Entity<Project> {
16283    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16284        self.read(cx).collaborators()
16285    }
16286
16287    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16288        self.read(cx).user_store().read(cx).participant_indices()
16289    }
16290
16291    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16292        let this = self.read(cx);
16293        let user_ids = this.collaborators().values().map(|c| c.user_id);
16294        this.user_store().read_with(cx, |user_store, cx| {
16295            user_store.participant_names(user_ids, cx)
16296        })
16297    }
16298}
16299
16300pub trait SemanticsProvider {
16301    fn hover(
16302        &self,
16303        buffer: &Entity<Buffer>,
16304        position: text::Anchor,
16305        cx: &mut App,
16306    ) -> Option<Task<Vec<project::Hover>>>;
16307
16308    fn inlay_hints(
16309        &self,
16310        buffer_handle: Entity<Buffer>,
16311        range: Range<text::Anchor>,
16312        cx: &mut App,
16313    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16314
16315    fn resolve_inlay_hint(
16316        &self,
16317        hint: InlayHint,
16318        buffer_handle: Entity<Buffer>,
16319        server_id: LanguageServerId,
16320        cx: &mut App,
16321    ) -> Option<Task<anyhow::Result<InlayHint>>>;
16322
16323    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16324
16325    fn document_highlights(
16326        &self,
16327        buffer: &Entity<Buffer>,
16328        position: text::Anchor,
16329        cx: &mut App,
16330    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16331
16332    fn definitions(
16333        &self,
16334        buffer: &Entity<Buffer>,
16335        position: text::Anchor,
16336        kind: GotoDefinitionKind,
16337        cx: &mut App,
16338    ) -> Option<Task<Result<Vec<LocationLink>>>>;
16339
16340    fn range_for_rename(
16341        &self,
16342        buffer: &Entity<Buffer>,
16343        position: text::Anchor,
16344        cx: &mut App,
16345    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16346
16347    fn perform_rename(
16348        &self,
16349        buffer: &Entity<Buffer>,
16350        position: text::Anchor,
16351        new_name: String,
16352        cx: &mut App,
16353    ) -> Option<Task<Result<ProjectTransaction>>>;
16354}
16355
16356pub trait CompletionProvider {
16357    fn completions(
16358        &self,
16359        buffer: &Entity<Buffer>,
16360        buffer_position: text::Anchor,
16361        trigger: CompletionContext,
16362        window: &mut Window,
16363        cx: &mut Context<Editor>,
16364    ) -> Task<Result<Vec<Completion>>>;
16365
16366    fn resolve_completions(
16367        &self,
16368        buffer: Entity<Buffer>,
16369        completion_indices: Vec<usize>,
16370        completions: Rc<RefCell<Box<[Completion]>>>,
16371        cx: &mut Context<Editor>,
16372    ) -> Task<Result<bool>>;
16373
16374    fn apply_additional_edits_for_completion(
16375        &self,
16376        _buffer: Entity<Buffer>,
16377        _completions: Rc<RefCell<Box<[Completion]>>>,
16378        _completion_index: usize,
16379        _push_to_history: bool,
16380        _cx: &mut Context<Editor>,
16381    ) -> Task<Result<Option<language::Transaction>>> {
16382        Task::ready(Ok(None))
16383    }
16384
16385    fn is_completion_trigger(
16386        &self,
16387        buffer: &Entity<Buffer>,
16388        position: language::Anchor,
16389        text: &str,
16390        trigger_in_words: bool,
16391        cx: &mut Context<Editor>,
16392    ) -> bool;
16393
16394    fn sort_completions(&self) -> bool {
16395        true
16396    }
16397}
16398
16399pub trait CodeActionProvider {
16400    fn id(&self) -> Arc<str>;
16401
16402    fn code_actions(
16403        &self,
16404        buffer: &Entity<Buffer>,
16405        range: Range<text::Anchor>,
16406        window: &mut Window,
16407        cx: &mut App,
16408    ) -> Task<Result<Vec<CodeAction>>>;
16409
16410    fn apply_code_action(
16411        &self,
16412        buffer_handle: Entity<Buffer>,
16413        action: CodeAction,
16414        excerpt_id: ExcerptId,
16415        push_to_history: bool,
16416        window: &mut Window,
16417        cx: &mut App,
16418    ) -> Task<Result<ProjectTransaction>>;
16419}
16420
16421impl CodeActionProvider for Entity<Project> {
16422    fn id(&self) -> Arc<str> {
16423        "project".into()
16424    }
16425
16426    fn code_actions(
16427        &self,
16428        buffer: &Entity<Buffer>,
16429        range: Range<text::Anchor>,
16430        _window: &mut Window,
16431        cx: &mut App,
16432    ) -> Task<Result<Vec<CodeAction>>> {
16433        self.update(cx, |project, cx| {
16434            project.code_actions(buffer, range, None, cx)
16435        })
16436    }
16437
16438    fn apply_code_action(
16439        &self,
16440        buffer_handle: Entity<Buffer>,
16441        action: CodeAction,
16442        _excerpt_id: ExcerptId,
16443        push_to_history: bool,
16444        _window: &mut Window,
16445        cx: &mut App,
16446    ) -> Task<Result<ProjectTransaction>> {
16447        self.update(cx, |project, cx| {
16448            project.apply_code_action(buffer_handle, action, push_to_history, cx)
16449        })
16450    }
16451}
16452
16453fn snippet_completions(
16454    project: &Project,
16455    buffer: &Entity<Buffer>,
16456    buffer_position: text::Anchor,
16457    cx: &mut App,
16458) -> Task<Result<Vec<Completion>>> {
16459    let language = buffer.read(cx).language_at(buffer_position);
16460    let language_name = language.as_ref().map(|language| language.lsp_id());
16461    let snippet_store = project.snippets().read(cx);
16462    let snippets = snippet_store.snippets_for(language_name, cx);
16463
16464    if snippets.is_empty() {
16465        return Task::ready(Ok(vec![]));
16466    }
16467    let snapshot = buffer.read(cx).text_snapshot();
16468    let chars: String = snapshot
16469        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16470        .collect();
16471
16472    let scope = language.map(|language| language.default_scope());
16473    let executor = cx.background_executor().clone();
16474
16475    cx.background_spawn(async move {
16476        let classifier = CharClassifier::new(scope).for_completion(true);
16477        let mut last_word = chars
16478            .chars()
16479            .take_while(|c| classifier.is_word(*c))
16480            .collect::<String>();
16481        last_word = last_word.chars().rev().collect();
16482
16483        if last_word.is_empty() {
16484            return Ok(vec![]);
16485        }
16486
16487        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16488        let to_lsp = |point: &text::Anchor| {
16489            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16490            point_to_lsp(end)
16491        };
16492        let lsp_end = to_lsp(&buffer_position);
16493
16494        let candidates = snippets
16495            .iter()
16496            .enumerate()
16497            .flat_map(|(ix, snippet)| {
16498                snippet
16499                    .prefix
16500                    .iter()
16501                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16502            })
16503            .collect::<Vec<StringMatchCandidate>>();
16504
16505        let mut matches = fuzzy::match_strings(
16506            &candidates,
16507            &last_word,
16508            last_word.chars().any(|c| c.is_uppercase()),
16509            100,
16510            &Default::default(),
16511            executor,
16512        )
16513        .await;
16514
16515        // Remove all candidates where the query's start does not match the start of any word in the candidate
16516        if let Some(query_start) = last_word.chars().next() {
16517            matches.retain(|string_match| {
16518                split_words(&string_match.string).any(|word| {
16519                    // Check that the first codepoint of the word as lowercase matches the first
16520                    // codepoint of the query as lowercase
16521                    word.chars()
16522                        .flat_map(|codepoint| codepoint.to_lowercase())
16523                        .zip(query_start.to_lowercase())
16524                        .all(|(word_cp, query_cp)| word_cp == query_cp)
16525                })
16526            });
16527        }
16528
16529        let matched_strings = matches
16530            .into_iter()
16531            .map(|m| m.string)
16532            .collect::<HashSet<_>>();
16533
16534        let result: Vec<Completion> = snippets
16535            .into_iter()
16536            .filter_map(|snippet| {
16537                let matching_prefix = snippet
16538                    .prefix
16539                    .iter()
16540                    .find(|prefix| matched_strings.contains(*prefix))?;
16541                let start = as_offset - last_word.len();
16542                let start = snapshot.anchor_before(start);
16543                let range = start..buffer_position;
16544                let lsp_start = to_lsp(&start);
16545                let lsp_range = lsp::Range {
16546                    start: lsp_start,
16547                    end: lsp_end,
16548                };
16549                Some(Completion {
16550                    old_range: range,
16551                    new_text: snippet.body.clone(),
16552                    resolved: false,
16553                    label: CodeLabel {
16554                        text: matching_prefix.clone(),
16555                        runs: vec![],
16556                        filter_range: 0..matching_prefix.len(),
16557                    },
16558                    server_id: LanguageServerId(usize::MAX),
16559                    documentation: snippet
16560                        .description
16561                        .clone()
16562                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
16563                    lsp_completion: lsp::CompletionItem {
16564                        label: snippet.prefix.first().unwrap().clone(),
16565                        kind: Some(CompletionItemKind::SNIPPET),
16566                        label_details: snippet.description.as_ref().map(|description| {
16567                            lsp::CompletionItemLabelDetails {
16568                                detail: Some(description.clone()),
16569                                description: None,
16570                            }
16571                        }),
16572                        insert_text_format: Some(InsertTextFormat::SNIPPET),
16573                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16574                            lsp::InsertReplaceEdit {
16575                                new_text: snippet.body.clone(),
16576                                insert: lsp_range,
16577                                replace: lsp_range,
16578                            },
16579                        )),
16580                        filter_text: Some(snippet.body.clone()),
16581                        sort_text: Some(char::MAX.to_string()),
16582                        ..Default::default()
16583                    },
16584                    confirm: None,
16585                })
16586            })
16587            .collect();
16588
16589        Ok(result)
16590    })
16591}
16592
16593impl CompletionProvider for Entity<Project> {
16594    fn completions(
16595        &self,
16596        buffer: &Entity<Buffer>,
16597        buffer_position: text::Anchor,
16598        options: CompletionContext,
16599        _window: &mut Window,
16600        cx: &mut Context<Editor>,
16601    ) -> Task<Result<Vec<Completion>>> {
16602        self.update(cx, |project, cx| {
16603            let snippets = snippet_completions(project, buffer, buffer_position, cx);
16604            let project_completions = project.completions(buffer, buffer_position, options, cx);
16605            cx.background_spawn(async move {
16606                let mut completions = project_completions.await?;
16607                let snippets_completions = snippets.await?;
16608                completions.extend(snippets_completions);
16609                Ok(completions)
16610            })
16611        })
16612    }
16613
16614    fn resolve_completions(
16615        &self,
16616        buffer: Entity<Buffer>,
16617        completion_indices: Vec<usize>,
16618        completions: Rc<RefCell<Box<[Completion]>>>,
16619        cx: &mut Context<Editor>,
16620    ) -> Task<Result<bool>> {
16621        self.update(cx, |project, cx| {
16622            project.lsp_store().update(cx, |lsp_store, cx| {
16623                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16624            })
16625        })
16626    }
16627
16628    fn apply_additional_edits_for_completion(
16629        &self,
16630        buffer: Entity<Buffer>,
16631        completions: Rc<RefCell<Box<[Completion]>>>,
16632        completion_index: usize,
16633        push_to_history: bool,
16634        cx: &mut Context<Editor>,
16635    ) -> Task<Result<Option<language::Transaction>>> {
16636        self.update(cx, |project, cx| {
16637            project.lsp_store().update(cx, |lsp_store, cx| {
16638                lsp_store.apply_additional_edits_for_completion(
16639                    buffer,
16640                    completions,
16641                    completion_index,
16642                    push_to_history,
16643                    cx,
16644                )
16645            })
16646        })
16647    }
16648
16649    fn is_completion_trigger(
16650        &self,
16651        buffer: &Entity<Buffer>,
16652        position: language::Anchor,
16653        text: &str,
16654        trigger_in_words: bool,
16655        cx: &mut Context<Editor>,
16656    ) -> bool {
16657        let mut chars = text.chars();
16658        let char = if let Some(char) = chars.next() {
16659            char
16660        } else {
16661            return false;
16662        };
16663        if chars.next().is_some() {
16664            return false;
16665        }
16666
16667        let buffer = buffer.read(cx);
16668        let snapshot = buffer.snapshot();
16669        if !snapshot.settings_at(position, cx).show_completions_on_input {
16670            return false;
16671        }
16672        let classifier = snapshot.char_classifier_at(position).for_completion(true);
16673        if trigger_in_words && classifier.is_word(char) {
16674            return true;
16675        }
16676
16677        buffer.completion_triggers().contains(text)
16678    }
16679}
16680
16681impl SemanticsProvider for Entity<Project> {
16682    fn hover(
16683        &self,
16684        buffer: &Entity<Buffer>,
16685        position: text::Anchor,
16686        cx: &mut App,
16687    ) -> Option<Task<Vec<project::Hover>>> {
16688        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16689    }
16690
16691    fn document_highlights(
16692        &self,
16693        buffer: &Entity<Buffer>,
16694        position: text::Anchor,
16695        cx: &mut App,
16696    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16697        Some(self.update(cx, |project, cx| {
16698            project.document_highlights(buffer, position, cx)
16699        }))
16700    }
16701
16702    fn definitions(
16703        &self,
16704        buffer: &Entity<Buffer>,
16705        position: text::Anchor,
16706        kind: GotoDefinitionKind,
16707        cx: &mut App,
16708    ) -> Option<Task<Result<Vec<LocationLink>>>> {
16709        Some(self.update(cx, |project, cx| match kind {
16710            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16711            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16712            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16713            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16714        }))
16715    }
16716
16717    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16718        // TODO: make this work for remote projects
16719        self.update(cx, |this, cx| {
16720            buffer.update(cx, |buffer, cx| {
16721                this.any_language_server_supports_inlay_hints(buffer, cx)
16722            })
16723        })
16724    }
16725
16726    fn inlay_hints(
16727        &self,
16728        buffer_handle: Entity<Buffer>,
16729        range: Range<text::Anchor>,
16730        cx: &mut App,
16731    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16732        Some(self.update(cx, |project, cx| {
16733            project.inlay_hints(buffer_handle, range, cx)
16734        }))
16735    }
16736
16737    fn resolve_inlay_hint(
16738        &self,
16739        hint: InlayHint,
16740        buffer_handle: Entity<Buffer>,
16741        server_id: LanguageServerId,
16742        cx: &mut App,
16743    ) -> Option<Task<anyhow::Result<InlayHint>>> {
16744        Some(self.update(cx, |project, cx| {
16745            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16746        }))
16747    }
16748
16749    fn range_for_rename(
16750        &self,
16751        buffer: &Entity<Buffer>,
16752        position: text::Anchor,
16753        cx: &mut App,
16754    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16755        Some(self.update(cx, |project, cx| {
16756            let buffer = buffer.clone();
16757            let task = project.prepare_rename(buffer.clone(), position, cx);
16758            cx.spawn(|_, mut cx| async move {
16759                Ok(match task.await? {
16760                    PrepareRenameResponse::Success(range) => Some(range),
16761                    PrepareRenameResponse::InvalidPosition => None,
16762                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16763                        // Fallback on using TreeSitter info to determine identifier range
16764                        buffer.update(&mut cx, |buffer, _| {
16765                            let snapshot = buffer.snapshot();
16766                            let (range, kind) = snapshot.surrounding_word(position);
16767                            if kind != Some(CharKind::Word) {
16768                                return None;
16769                            }
16770                            Some(
16771                                snapshot.anchor_before(range.start)
16772                                    ..snapshot.anchor_after(range.end),
16773                            )
16774                        })?
16775                    }
16776                })
16777            })
16778        }))
16779    }
16780
16781    fn perform_rename(
16782        &self,
16783        buffer: &Entity<Buffer>,
16784        position: text::Anchor,
16785        new_name: String,
16786        cx: &mut App,
16787    ) -> Option<Task<Result<ProjectTransaction>>> {
16788        Some(self.update(cx, |project, cx| {
16789            project.perform_rename(buffer.clone(), position, new_name, cx)
16790        }))
16791    }
16792}
16793
16794fn inlay_hint_settings(
16795    location: Anchor,
16796    snapshot: &MultiBufferSnapshot,
16797    cx: &mut Context<Editor>,
16798) -> InlayHintSettings {
16799    let file = snapshot.file_at(location);
16800    let language = snapshot.language_at(location).map(|l| l.name());
16801    language_settings(language, file, cx).inlay_hints
16802}
16803
16804fn consume_contiguous_rows(
16805    contiguous_row_selections: &mut Vec<Selection<Point>>,
16806    selection: &Selection<Point>,
16807    display_map: &DisplaySnapshot,
16808    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16809) -> (MultiBufferRow, MultiBufferRow) {
16810    contiguous_row_selections.push(selection.clone());
16811    let start_row = MultiBufferRow(selection.start.row);
16812    let mut end_row = ending_row(selection, display_map);
16813
16814    while let Some(next_selection) = selections.peek() {
16815        if next_selection.start.row <= end_row.0 {
16816            end_row = ending_row(next_selection, display_map);
16817            contiguous_row_selections.push(selections.next().unwrap().clone());
16818        } else {
16819            break;
16820        }
16821    }
16822    (start_row, end_row)
16823}
16824
16825fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16826    if next_selection.end.column > 0 || next_selection.is_empty() {
16827        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16828    } else {
16829        MultiBufferRow(next_selection.end.row)
16830    }
16831}
16832
16833impl EditorSnapshot {
16834    pub fn remote_selections_in_range<'a>(
16835        &'a self,
16836        range: &'a Range<Anchor>,
16837        collaboration_hub: &dyn CollaborationHub,
16838        cx: &'a App,
16839    ) -> impl 'a + Iterator<Item = RemoteSelection> {
16840        let participant_names = collaboration_hub.user_names(cx);
16841        let participant_indices = collaboration_hub.user_participant_indices(cx);
16842        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16843        let collaborators_by_replica_id = collaborators_by_peer_id
16844            .iter()
16845            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16846            .collect::<HashMap<_, _>>();
16847        self.buffer_snapshot
16848            .selections_in_range(range, false)
16849            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16850                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16851                let participant_index = participant_indices.get(&collaborator.user_id).copied();
16852                let user_name = participant_names.get(&collaborator.user_id).cloned();
16853                Some(RemoteSelection {
16854                    replica_id,
16855                    selection,
16856                    cursor_shape,
16857                    line_mode,
16858                    participant_index,
16859                    peer_id: collaborator.peer_id,
16860                    user_name,
16861                })
16862            })
16863    }
16864
16865    pub fn hunks_for_ranges(
16866        &self,
16867        ranges: impl Iterator<Item = Range<Point>>,
16868    ) -> Vec<MultiBufferDiffHunk> {
16869        let mut hunks = Vec::new();
16870        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16871            HashMap::default();
16872        for query_range in ranges {
16873            let query_rows =
16874                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16875            for hunk in self.buffer_snapshot.diff_hunks_in_range(
16876                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16877            ) {
16878                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16879                // when the caret is just above or just below the deleted hunk.
16880                let allow_adjacent = hunk.status().is_deleted();
16881                let related_to_selection = if allow_adjacent {
16882                    hunk.row_range.overlaps(&query_rows)
16883                        || hunk.row_range.start == query_rows.end
16884                        || hunk.row_range.end == query_rows.start
16885                } else {
16886                    hunk.row_range.overlaps(&query_rows)
16887                };
16888                if related_to_selection {
16889                    if !processed_buffer_rows
16890                        .entry(hunk.buffer_id)
16891                        .or_default()
16892                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16893                    {
16894                        continue;
16895                    }
16896                    hunks.push(hunk);
16897                }
16898            }
16899        }
16900
16901        hunks
16902    }
16903
16904    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16905        self.display_snapshot.buffer_snapshot.language_at(position)
16906    }
16907
16908    pub fn is_focused(&self) -> bool {
16909        self.is_focused
16910    }
16911
16912    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16913        self.placeholder_text.as_ref()
16914    }
16915
16916    pub fn scroll_position(&self) -> gpui::Point<f32> {
16917        self.scroll_anchor.scroll_position(&self.display_snapshot)
16918    }
16919
16920    fn gutter_dimensions(
16921        &self,
16922        font_id: FontId,
16923        font_size: Pixels,
16924        max_line_number_width: Pixels,
16925        cx: &App,
16926    ) -> Option<GutterDimensions> {
16927        if !self.show_gutter {
16928            return None;
16929        }
16930
16931        let descent = cx.text_system().descent(font_id, font_size);
16932        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16933        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16934
16935        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16936            matches!(
16937                ProjectSettings::get_global(cx).git.git_gutter,
16938                Some(GitGutterSetting::TrackedFiles)
16939            )
16940        });
16941        let gutter_settings = EditorSettings::get_global(cx).gutter;
16942        let show_line_numbers = self
16943            .show_line_numbers
16944            .unwrap_or(gutter_settings.line_numbers);
16945        let line_gutter_width = if show_line_numbers {
16946            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16947            let min_width_for_number_on_gutter = em_advance * 4.0;
16948            max_line_number_width.max(min_width_for_number_on_gutter)
16949        } else {
16950            0.0.into()
16951        };
16952
16953        let show_code_actions = self
16954            .show_code_actions
16955            .unwrap_or(gutter_settings.code_actions);
16956
16957        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16958
16959        let git_blame_entries_width =
16960            self.git_blame_gutter_max_author_length
16961                .map(|max_author_length| {
16962                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16963
16964                    /// The number of characters to dedicate to gaps and margins.
16965                    const SPACING_WIDTH: usize = 4;
16966
16967                    let max_char_count = max_author_length
16968                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16969                        + ::git::SHORT_SHA_LENGTH
16970                        + MAX_RELATIVE_TIMESTAMP.len()
16971                        + SPACING_WIDTH;
16972
16973                    em_advance * max_char_count
16974                });
16975
16976        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16977        left_padding += if show_code_actions || show_runnables {
16978            em_width * 3.0
16979        } else if show_git_gutter && show_line_numbers {
16980            em_width * 2.0
16981        } else if show_git_gutter || show_line_numbers {
16982            em_width
16983        } else {
16984            px(0.)
16985        };
16986
16987        let right_padding = if gutter_settings.folds && show_line_numbers {
16988            em_width * 4.0
16989        } else if gutter_settings.folds {
16990            em_width * 3.0
16991        } else if show_line_numbers {
16992            em_width
16993        } else {
16994            px(0.)
16995        };
16996
16997        Some(GutterDimensions {
16998            left_padding,
16999            right_padding,
17000            width: line_gutter_width + left_padding + right_padding,
17001            margin: -descent,
17002            git_blame_entries_width,
17003        })
17004    }
17005
17006    pub fn render_crease_toggle(
17007        &self,
17008        buffer_row: MultiBufferRow,
17009        row_contains_cursor: bool,
17010        editor: Entity<Editor>,
17011        window: &mut Window,
17012        cx: &mut App,
17013    ) -> Option<AnyElement> {
17014        let folded = self.is_line_folded(buffer_row);
17015        let mut is_foldable = false;
17016
17017        if let Some(crease) = self
17018            .crease_snapshot
17019            .query_row(buffer_row, &self.buffer_snapshot)
17020        {
17021            is_foldable = true;
17022            match crease {
17023                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17024                    if let Some(render_toggle) = render_toggle {
17025                        let toggle_callback =
17026                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17027                                if folded {
17028                                    editor.update(cx, |editor, cx| {
17029                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17030                                    });
17031                                } else {
17032                                    editor.update(cx, |editor, cx| {
17033                                        editor.unfold_at(
17034                                            &crate::UnfoldAt { buffer_row },
17035                                            window,
17036                                            cx,
17037                                        )
17038                                    });
17039                                }
17040                            });
17041                        return Some((render_toggle)(
17042                            buffer_row,
17043                            folded,
17044                            toggle_callback,
17045                            window,
17046                            cx,
17047                        ));
17048                    }
17049                }
17050            }
17051        }
17052
17053        is_foldable |= self.starts_indent(buffer_row);
17054
17055        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17056            Some(
17057                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17058                    .toggle_state(folded)
17059                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17060                        if folded {
17061                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17062                        } else {
17063                            this.fold_at(&FoldAt { buffer_row }, window, cx);
17064                        }
17065                    }))
17066                    .into_any_element(),
17067            )
17068        } else {
17069            None
17070        }
17071    }
17072
17073    pub fn render_crease_trailer(
17074        &self,
17075        buffer_row: MultiBufferRow,
17076        window: &mut Window,
17077        cx: &mut App,
17078    ) -> Option<AnyElement> {
17079        let folded = self.is_line_folded(buffer_row);
17080        if let Crease::Inline { render_trailer, .. } = self
17081            .crease_snapshot
17082            .query_row(buffer_row, &self.buffer_snapshot)?
17083        {
17084            let render_trailer = render_trailer.as_ref()?;
17085            Some(render_trailer(buffer_row, folded, window, cx))
17086        } else {
17087            None
17088        }
17089    }
17090}
17091
17092impl Deref for EditorSnapshot {
17093    type Target = DisplaySnapshot;
17094
17095    fn deref(&self) -> &Self::Target {
17096        &self.display_snapshot
17097    }
17098}
17099
17100#[derive(Clone, Debug, PartialEq, Eq)]
17101pub enum EditorEvent {
17102    InputIgnored {
17103        text: Arc<str>,
17104    },
17105    InputHandled {
17106        utf16_range_to_replace: Option<Range<isize>>,
17107        text: Arc<str>,
17108    },
17109    ExcerptsAdded {
17110        buffer: Entity<Buffer>,
17111        predecessor: ExcerptId,
17112        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17113    },
17114    ExcerptsRemoved {
17115        ids: Vec<ExcerptId>,
17116    },
17117    BufferFoldToggled {
17118        ids: Vec<ExcerptId>,
17119        folded: bool,
17120    },
17121    ExcerptsEdited {
17122        ids: Vec<ExcerptId>,
17123    },
17124    ExcerptsExpanded {
17125        ids: Vec<ExcerptId>,
17126    },
17127    BufferEdited,
17128    Edited {
17129        transaction_id: clock::Lamport,
17130    },
17131    Reparsed(BufferId),
17132    Focused,
17133    FocusedIn,
17134    Blurred,
17135    DirtyChanged,
17136    Saved,
17137    TitleChanged,
17138    DiffBaseChanged,
17139    SelectionsChanged {
17140        local: bool,
17141    },
17142    ScrollPositionChanged {
17143        local: bool,
17144        autoscroll: bool,
17145    },
17146    Closed,
17147    TransactionUndone {
17148        transaction_id: clock::Lamport,
17149    },
17150    TransactionBegun {
17151        transaction_id: clock::Lamport,
17152    },
17153    Reloaded,
17154    CursorShapeChanged,
17155}
17156
17157impl EventEmitter<EditorEvent> for Editor {}
17158
17159impl Focusable for Editor {
17160    fn focus_handle(&self, _cx: &App) -> FocusHandle {
17161        self.focus_handle.clone()
17162    }
17163}
17164
17165impl Render for Editor {
17166    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17167        let settings = ThemeSettings::get_global(cx);
17168
17169        let mut text_style = match self.mode {
17170            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17171                color: cx.theme().colors().editor_foreground,
17172                font_family: settings.ui_font.family.clone(),
17173                font_features: settings.ui_font.features.clone(),
17174                font_fallbacks: settings.ui_font.fallbacks.clone(),
17175                font_size: rems(0.875).into(),
17176                font_weight: settings.ui_font.weight,
17177                line_height: relative(settings.buffer_line_height.value()),
17178                ..Default::default()
17179            },
17180            EditorMode::Full => TextStyle {
17181                color: cx.theme().colors().editor_foreground,
17182                font_family: settings.buffer_font.family.clone(),
17183                font_features: settings.buffer_font.features.clone(),
17184                font_fallbacks: settings.buffer_font.fallbacks.clone(),
17185                font_size: settings.buffer_font_size(cx).into(),
17186                font_weight: settings.buffer_font.weight,
17187                line_height: relative(settings.buffer_line_height.value()),
17188                ..Default::default()
17189            },
17190        };
17191        if let Some(text_style_refinement) = &self.text_style_refinement {
17192            text_style.refine(text_style_refinement)
17193        }
17194
17195        let background = match self.mode {
17196            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17197            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17198            EditorMode::Full => cx.theme().colors().editor_background,
17199        };
17200
17201        EditorElement::new(
17202            &cx.entity(),
17203            EditorStyle {
17204                background,
17205                local_player: cx.theme().players().local(),
17206                text: text_style,
17207                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17208                syntax: cx.theme().syntax().clone(),
17209                status: cx.theme().status().clone(),
17210                inlay_hints_style: make_inlay_hints_style(cx),
17211                inline_completion_styles: make_suggestion_styles(cx),
17212                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17213            },
17214        )
17215    }
17216}
17217
17218impl EntityInputHandler for Editor {
17219    fn text_for_range(
17220        &mut self,
17221        range_utf16: Range<usize>,
17222        adjusted_range: &mut Option<Range<usize>>,
17223        _: &mut Window,
17224        cx: &mut Context<Self>,
17225    ) -> Option<String> {
17226        let snapshot = self.buffer.read(cx).read(cx);
17227        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17228        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17229        if (start.0..end.0) != range_utf16 {
17230            adjusted_range.replace(start.0..end.0);
17231        }
17232        Some(snapshot.text_for_range(start..end).collect())
17233    }
17234
17235    fn selected_text_range(
17236        &mut self,
17237        ignore_disabled_input: bool,
17238        _: &mut Window,
17239        cx: &mut Context<Self>,
17240    ) -> Option<UTF16Selection> {
17241        // Prevent the IME menu from appearing when holding down an alphabetic key
17242        // while input is disabled.
17243        if !ignore_disabled_input && !self.input_enabled {
17244            return None;
17245        }
17246
17247        let selection = self.selections.newest::<OffsetUtf16>(cx);
17248        let range = selection.range();
17249
17250        Some(UTF16Selection {
17251            range: range.start.0..range.end.0,
17252            reversed: selection.reversed,
17253        })
17254    }
17255
17256    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17257        let snapshot = self.buffer.read(cx).read(cx);
17258        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17259        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17260    }
17261
17262    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17263        self.clear_highlights::<InputComposition>(cx);
17264        self.ime_transaction.take();
17265    }
17266
17267    fn replace_text_in_range(
17268        &mut self,
17269        range_utf16: Option<Range<usize>>,
17270        text: &str,
17271        window: &mut Window,
17272        cx: &mut Context<Self>,
17273    ) {
17274        if !self.input_enabled {
17275            cx.emit(EditorEvent::InputIgnored { text: text.into() });
17276            return;
17277        }
17278
17279        self.transact(window, cx, |this, window, cx| {
17280            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17281                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17282                Some(this.selection_replacement_ranges(range_utf16, cx))
17283            } else {
17284                this.marked_text_ranges(cx)
17285            };
17286
17287            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17288                let newest_selection_id = this.selections.newest_anchor().id;
17289                this.selections
17290                    .all::<OffsetUtf16>(cx)
17291                    .iter()
17292                    .zip(ranges_to_replace.iter())
17293                    .find_map(|(selection, range)| {
17294                        if selection.id == newest_selection_id {
17295                            Some(
17296                                (range.start.0 as isize - selection.head().0 as isize)
17297                                    ..(range.end.0 as isize - selection.head().0 as isize),
17298                            )
17299                        } else {
17300                            None
17301                        }
17302                    })
17303            });
17304
17305            cx.emit(EditorEvent::InputHandled {
17306                utf16_range_to_replace: range_to_replace,
17307                text: text.into(),
17308            });
17309
17310            if let Some(new_selected_ranges) = new_selected_ranges {
17311                this.change_selections(None, window, cx, |selections| {
17312                    selections.select_ranges(new_selected_ranges)
17313                });
17314                this.backspace(&Default::default(), window, cx);
17315            }
17316
17317            this.handle_input(text, window, cx);
17318        });
17319
17320        if let Some(transaction) = self.ime_transaction {
17321            self.buffer.update(cx, |buffer, cx| {
17322                buffer.group_until_transaction(transaction, cx);
17323            });
17324        }
17325
17326        self.unmark_text(window, cx);
17327    }
17328
17329    fn replace_and_mark_text_in_range(
17330        &mut self,
17331        range_utf16: Option<Range<usize>>,
17332        text: &str,
17333        new_selected_range_utf16: Option<Range<usize>>,
17334        window: &mut Window,
17335        cx: &mut Context<Self>,
17336    ) {
17337        if !self.input_enabled {
17338            return;
17339        }
17340
17341        let transaction = self.transact(window, cx, |this, window, cx| {
17342            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17343                let snapshot = this.buffer.read(cx).read(cx);
17344                if let Some(relative_range_utf16) = range_utf16.as_ref() {
17345                    for marked_range in &mut marked_ranges {
17346                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17347                        marked_range.start.0 += relative_range_utf16.start;
17348                        marked_range.start =
17349                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17350                        marked_range.end =
17351                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17352                    }
17353                }
17354                Some(marked_ranges)
17355            } else if let Some(range_utf16) = range_utf16 {
17356                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17357                Some(this.selection_replacement_ranges(range_utf16, cx))
17358            } else {
17359                None
17360            };
17361
17362            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17363                let newest_selection_id = this.selections.newest_anchor().id;
17364                this.selections
17365                    .all::<OffsetUtf16>(cx)
17366                    .iter()
17367                    .zip(ranges_to_replace.iter())
17368                    .find_map(|(selection, range)| {
17369                        if selection.id == newest_selection_id {
17370                            Some(
17371                                (range.start.0 as isize - selection.head().0 as isize)
17372                                    ..(range.end.0 as isize - selection.head().0 as isize),
17373                            )
17374                        } else {
17375                            None
17376                        }
17377                    })
17378            });
17379
17380            cx.emit(EditorEvent::InputHandled {
17381                utf16_range_to_replace: range_to_replace,
17382                text: text.into(),
17383            });
17384
17385            if let Some(ranges) = ranges_to_replace {
17386                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17387            }
17388
17389            let marked_ranges = {
17390                let snapshot = this.buffer.read(cx).read(cx);
17391                this.selections
17392                    .disjoint_anchors()
17393                    .iter()
17394                    .map(|selection| {
17395                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17396                    })
17397                    .collect::<Vec<_>>()
17398            };
17399
17400            if text.is_empty() {
17401                this.unmark_text(window, cx);
17402            } else {
17403                this.highlight_text::<InputComposition>(
17404                    marked_ranges.clone(),
17405                    HighlightStyle {
17406                        underline: Some(UnderlineStyle {
17407                            thickness: px(1.),
17408                            color: None,
17409                            wavy: false,
17410                        }),
17411                        ..Default::default()
17412                    },
17413                    cx,
17414                );
17415            }
17416
17417            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17418            let use_autoclose = this.use_autoclose;
17419            let use_auto_surround = this.use_auto_surround;
17420            this.set_use_autoclose(false);
17421            this.set_use_auto_surround(false);
17422            this.handle_input(text, window, cx);
17423            this.set_use_autoclose(use_autoclose);
17424            this.set_use_auto_surround(use_auto_surround);
17425
17426            if let Some(new_selected_range) = new_selected_range_utf16 {
17427                let snapshot = this.buffer.read(cx).read(cx);
17428                let new_selected_ranges = marked_ranges
17429                    .into_iter()
17430                    .map(|marked_range| {
17431                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17432                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17433                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17434                        snapshot.clip_offset_utf16(new_start, Bias::Left)
17435                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17436                    })
17437                    .collect::<Vec<_>>();
17438
17439                drop(snapshot);
17440                this.change_selections(None, window, cx, |selections| {
17441                    selections.select_ranges(new_selected_ranges)
17442                });
17443            }
17444        });
17445
17446        self.ime_transaction = self.ime_transaction.or(transaction);
17447        if let Some(transaction) = self.ime_transaction {
17448            self.buffer.update(cx, |buffer, cx| {
17449                buffer.group_until_transaction(transaction, cx);
17450            });
17451        }
17452
17453        if self.text_highlights::<InputComposition>(cx).is_none() {
17454            self.ime_transaction.take();
17455        }
17456    }
17457
17458    fn bounds_for_range(
17459        &mut self,
17460        range_utf16: Range<usize>,
17461        element_bounds: gpui::Bounds<Pixels>,
17462        window: &mut Window,
17463        cx: &mut Context<Self>,
17464    ) -> Option<gpui::Bounds<Pixels>> {
17465        let text_layout_details = self.text_layout_details(window);
17466        let gpui::Size {
17467            width: em_width,
17468            height: line_height,
17469        } = self.character_size(window);
17470
17471        let snapshot = self.snapshot(window, cx);
17472        let scroll_position = snapshot.scroll_position();
17473        let scroll_left = scroll_position.x * em_width;
17474
17475        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17476        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17477            + self.gutter_dimensions.width
17478            + self.gutter_dimensions.margin;
17479        let y = line_height * (start.row().as_f32() - scroll_position.y);
17480
17481        Some(Bounds {
17482            origin: element_bounds.origin + point(x, y),
17483            size: size(em_width, line_height),
17484        })
17485    }
17486
17487    fn character_index_for_point(
17488        &mut self,
17489        point: gpui::Point<Pixels>,
17490        _window: &mut Window,
17491        _cx: &mut Context<Self>,
17492    ) -> Option<usize> {
17493        let position_map = self.last_position_map.as_ref()?;
17494        if !position_map.text_hitbox.contains(&point) {
17495            return None;
17496        }
17497        let display_point = position_map.point_for_position(point).previous_valid;
17498        let anchor = position_map
17499            .snapshot
17500            .display_point_to_anchor(display_point, Bias::Left);
17501        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17502        Some(utf16_offset.0)
17503    }
17504}
17505
17506trait SelectionExt {
17507    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17508    fn spanned_rows(
17509        &self,
17510        include_end_if_at_line_start: bool,
17511        map: &DisplaySnapshot,
17512    ) -> Range<MultiBufferRow>;
17513}
17514
17515impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17516    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17517        let start = self
17518            .start
17519            .to_point(&map.buffer_snapshot)
17520            .to_display_point(map);
17521        let end = self
17522            .end
17523            .to_point(&map.buffer_snapshot)
17524            .to_display_point(map);
17525        if self.reversed {
17526            end..start
17527        } else {
17528            start..end
17529        }
17530    }
17531
17532    fn spanned_rows(
17533        &self,
17534        include_end_if_at_line_start: bool,
17535        map: &DisplaySnapshot,
17536    ) -> Range<MultiBufferRow> {
17537        let start = self.start.to_point(&map.buffer_snapshot);
17538        let mut end = self.end.to_point(&map.buffer_snapshot);
17539        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17540            end.row -= 1;
17541        }
17542
17543        let buffer_start = map.prev_line_boundary(start).0;
17544        let buffer_end = map.next_line_boundary(end).0;
17545        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17546    }
17547}
17548
17549impl<T: InvalidationRegion> InvalidationStack<T> {
17550    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17551    where
17552        S: Clone + ToOffset,
17553    {
17554        while let Some(region) = self.last() {
17555            let all_selections_inside_invalidation_ranges =
17556                if selections.len() == region.ranges().len() {
17557                    selections
17558                        .iter()
17559                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17560                        .all(|(selection, invalidation_range)| {
17561                            let head = selection.head().to_offset(buffer);
17562                            invalidation_range.start <= head && invalidation_range.end >= head
17563                        })
17564                } else {
17565                    false
17566                };
17567
17568            if all_selections_inside_invalidation_ranges {
17569                break;
17570            } else {
17571                self.pop();
17572            }
17573        }
17574    }
17575}
17576
17577impl<T> Default for InvalidationStack<T> {
17578    fn default() -> Self {
17579        Self(Default::default())
17580    }
17581}
17582
17583impl<T> Deref for InvalidationStack<T> {
17584    type Target = Vec<T>;
17585
17586    fn deref(&self) -> &Self::Target {
17587        &self.0
17588    }
17589}
17590
17591impl<T> DerefMut for InvalidationStack<T> {
17592    fn deref_mut(&mut self) -> &mut Self::Target {
17593        &mut self.0
17594    }
17595}
17596
17597impl InvalidationRegion for SnippetState {
17598    fn ranges(&self) -> &[Range<Anchor>] {
17599        &self.ranges[self.active_index]
17600    }
17601}
17602
17603pub fn diagnostic_block_renderer(
17604    diagnostic: Diagnostic,
17605    max_message_rows: Option<u8>,
17606    allow_closing: bool,
17607    _is_valid: bool,
17608) -> RenderBlock {
17609    let (text_without_backticks, code_ranges) =
17610        highlight_diagnostic_message(&diagnostic, max_message_rows);
17611
17612    Arc::new(move |cx: &mut BlockContext| {
17613        let group_id: SharedString = cx.block_id.to_string().into();
17614
17615        let mut text_style = cx.window.text_style().clone();
17616        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17617        let theme_settings = ThemeSettings::get_global(cx);
17618        text_style.font_family = theme_settings.buffer_font.family.clone();
17619        text_style.font_style = theme_settings.buffer_font.style;
17620        text_style.font_features = theme_settings.buffer_font.features.clone();
17621        text_style.font_weight = theme_settings.buffer_font.weight;
17622
17623        let multi_line_diagnostic = diagnostic.message.contains('\n');
17624
17625        let buttons = |diagnostic: &Diagnostic| {
17626            if multi_line_diagnostic {
17627                v_flex()
17628            } else {
17629                h_flex()
17630            }
17631            .when(allow_closing, |div| {
17632                div.children(diagnostic.is_primary.then(|| {
17633                    IconButton::new("close-block", IconName::XCircle)
17634                        .icon_color(Color::Muted)
17635                        .size(ButtonSize::Compact)
17636                        .style(ButtonStyle::Transparent)
17637                        .visible_on_hover(group_id.clone())
17638                        .on_click(move |_click, window, cx| {
17639                            window.dispatch_action(Box::new(Cancel), cx)
17640                        })
17641                        .tooltip(|window, cx| {
17642                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17643                        })
17644                }))
17645            })
17646            .child(
17647                IconButton::new("copy-block", IconName::Copy)
17648                    .icon_color(Color::Muted)
17649                    .size(ButtonSize::Compact)
17650                    .style(ButtonStyle::Transparent)
17651                    .visible_on_hover(group_id.clone())
17652                    .on_click({
17653                        let message = diagnostic.message.clone();
17654                        move |_click, _, cx| {
17655                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17656                        }
17657                    })
17658                    .tooltip(Tooltip::text("Copy diagnostic message")),
17659            )
17660        };
17661
17662        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17663            AvailableSpace::min_size(),
17664            cx.window,
17665            cx.app,
17666        );
17667
17668        h_flex()
17669            .id(cx.block_id)
17670            .group(group_id.clone())
17671            .relative()
17672            .size_full()
17673            .block_mouse_down()
17674            .pl(cx.gutter_dimensions.width)
17675            .w(cx.max_width - cx.gutter_dimensions.full_width())
17676            .child(
17677                div()
17678                    .flex()
17679                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17680                    .flex_shrink(),
17681            )
17682            .child(buttons(&diagnostic))
17683            .child(div().flex().flex_shrink_0().child(
17684                StyledText::new(text_without_backticks.clone()).with_highlights(
17685                    &text_style,
17686                    code_ranges.iter().map(|range| {
17687                        (
17688                            range.clone(),
17689                            HighlightStyle {
17690                                font_weight: Some(FontWeight::BOLD),
17691                                ..Default::default()
17692                            },
17693                        )
17694                    }),
17695                ),
17696            ))
17697            .into_any_element()
17698    })
17699}
17700
17701fn inline_completion_edit_text(
17702    current_snapshot: &BufferSnapshot,
17703    edits: &[(Range<Anchor>, String)],
17704    edit_preview: &EditPreview,
17705    include_deletions: bool,
17706    cx: &App,
17707) -> HighlightedText {
17708    let edits = edits
17709        .iter()
17710        .map(|(anchor, text)| {
17711            (
17712                anchor.start.text_anchor..anchor.end.text_anchor,
17713                text.clone(),
17714            )
17715        })
17716        .collect::<Vec<_>>();
17717
17718    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17719}
17720
17721pub fn highlight_diagnostic_message(
17722    diagnostic: &Diagnostic,
17723    mut max_message_rows: Option<u8>,
17724) -> (SharedString, Vec<Range<usize>>) {
17725    let mut text_without_backticks = String::new();
17726    let mut code_ranges = Vec::new();
17727
17728    if let Some(source) = &diagnostic.source {
17729        text_without_backticks.push_str(source);
17730        code_ranges.push(0..source.len());
17731        text_without_backticks.push_str(": ");
17732    }
17733
17734    let mut prev_offset = 0;
17735    let mut in_code_block = false;
17736    let has_row_limit = max_message_rows.is_some();
17737    let mut newline_indices = diagnostic
17738        .message
17739        .match_indices('\n')
17740        .filter(|_| has_row_limit)
17741        .map(|(ix, _)| ix)
17742        .fuse()
17743        .peekable();
17744
17745    for (quote_ix, _) in diagnostic
17746        .message
17747        .match_indices('`')
17748        .chain([(diagnostic.message.len(), "")])
17749    {
17750        let mut first_newline_ix = None;
17751        let mut last_newline_ix = None;
17752        while let Some(newline_ix) = newline_indices.peek() {
17753            if *newline_ix < quote_ix {
17754                if first_newline_ix.is_none() {
17755                    first_newline_ix = Some(*newline_ix);
17756                }
17757                last_newline_ix = Some(*newline_ix);
17758
17759                if let Some(rows_left) = &mut max_message_rows {
17760                    if *rows_left == 0 {
17761                        break;
17762                    } else {
17763                        *rows_left -= 1;
17764                    }
17765                }
17766                let _ = newline_indices.next();
17767            } else {
17768                break;
17769            }
17770        }
17771        let prev_len = text_without_backticks.len();
17772        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17773        text_without_backticks.push_str(new_text);
17774        if in_code_block {
17775            code_ranges.push(prev_len..text_without_backticks.len());
17776        }
17777        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17778        in_code_block = !in_code_block;
17779        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17780            text_without_backticks.push_str("...");
17781            break;
17782        }
17783    }
17784
17785    (text_without_backticks.into(), code_ranges)
17786}
17787
17788fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17789    match severity {
17790        DiagnosticSeverity::ERROR => colors.error,
17791        DiagnosticSeverity::WARNING => colors.warning,
17792        DiagnosticSeverity::INFORMATION => colors.info,
17793        DiagnosticSeverity::HINT => colors.info,
17794        _ => colors.ignored,
17795    }
17796}
17797
17798pub fn styled_runs_for_code_label<'a>(
17799    label: &'a CodeLabel,
17800    syntax_theme: &'a theme::SyntaxTheme,
17801) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17802    let fade_out = HighlightStyle {
17803        fade_out: Some(0.35),
17804        ..Default::default()
17805    };
17806
17807    let mut prev_end = label.filter_range.end;
17808    label
17809        .runs
17810        .iter()
17811        .enumerate()
17812        .flat_map(move |(ix, (range, highlight_id))| {
17813            let style = if let Some(style) = highlight_id.style(syntax_theme) {
17814                style
17815            } else {
17816                return Default::default();
17817            };
17818            let mut muted_style = style;
17819            muted_style.highlight(fade_out);
17820
17821            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17822            if range.start >= label.filter_range.end {
17823                if range.start > prev_end {
17824                    runs.push((prev_end..range.start, fade_out));
17825                }
17826                runs.push((range.clone(), muted_style));
17827            } else if range.end <= label.filter_range.end {
17828                runs.push((range.clone(), style));
17829            } else {
17830                runs.push((range.start..label.filter_range.end, style));
17831                runs.push((label.filter_range.end..range.end, muted_style));
17832            }
17833            prev_end = cmp::max(prev_end, range.end);
17834
17835            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17836                runs.push((prev_end..label.text.len(), fade_out));
17837            }
17838
17839            runs
17840        })
17841}
17842
17843pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17844    let mut prev_index = 0;
17845    let mut prev_codepoint: Option<char> = None;
17846    text.char_indices()
17847        .chain([(text.len(), '\0')])
17848        .filter_map(move |(index, codepoint)| {
17849            let prev_codepoint = prev_codepoint.replace(codepoint)?;
17850            let is_boundary = index == text.len()
17851                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17852                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17853            if is_boundary {
17854                let chunk = &text[prev_index..index];
17855                prev_index = index;
17856                Some(chunk)
17857            } else {
17858                None
17859            }
17860        })
17861}
17862
17863pub trait RangeToAnchorExt: Sized {
17864    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17865
17866    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17867        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17868        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17869    }
17870}
17871
17872impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17873    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17874        let start_offset = self.start.to_offset(snapshot);
17875        let end_offset = self.end.to_offset(snapshot);
17876        if start_offset == end_offset {
17877            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17878        } else {
17879            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17880        }
17881    }
17882}
17883
17884pub trait RowExt {
17885    fn as_f32(&self) -> f32;
17886
17887    fn next_row(&self) -> Self;
17888
17889    fn previous_row(&self) -> Self;
17890
17891    fn minus(&self, other: Self) -> u32;
17892}
17893
17894impl RowExt for DisplayRow {
17895    fn as_f32(&self) -> f32 {
17896        self.0 as f32
17897    }
17898
17899    fn next_row(&self) -> Self {
17900        Self(self.0 + 1)
17901    }
17902
17903    fn previous_row(&self) -> Self {
17904        Self(self.0.saturating_sub(1))
17905    }
17906
17907    fn minus(&self, other: Self) -> u32 {
17908        self.0 - other.0
17909    }
17910}
17911
17912impl RowExt for MultiBufferRow {
17913    fn as_f32(&self) -> f32 {
17914        self.0 as f32
17915    }
17916
17917    fn next_row(&self) -> Self {
17918        Self(self.0 + 1)
17919    }
17920
17921    fn previous_row(&self) -> Self {
17922        Self(self.0.saturating_sub(1))
17923    }
17924
17925    fn minus(&self, other: Self) -> u32 {
17926        self.0 - other.0
17927    }
17928}
17929
17930trait RowRangeExt {
17931    type Row;
17932
17933    fn len(&self) -> usize;
17934
17935    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17936}
17937
17938impl RowRangeExt for Range<MultiBufferRow> {
17939    type Row = MultiBufferRow;
17940
17941    fn len(&self) -> usize {
17942        (self.end.0 - self.start.0) as usize
17943    }
17944
17945    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17946        (self.start.0..self.end.0).map(MultiBufferRow)
17947    }
17948}
17949
17950impl RowRangeExt for Range<DisplayRow> {
17951    type Row = DisplayRow;
17952
17953    fn len(&self) -> usize {
17954        (self.end.0 - self.start.0) as usize
17955    }
17956
17957    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17958        (self.start.0..self.end.0).map(DisplayRow)
17959    }
17960}
17961
17962/// If select range has more than one line, we
17963/// just point the cursor to range.start.
17964fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17965    if range.start.row == range.end.row {
17966        range
17967    } else {
17968        range.start..range.start
17969    }
17970}
17971pub struct KillRing(ClipboardItem);
17972impl Global for KillRing {}
17973
17974const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17975
17976fn all_edits_insertions_or_deletions(
17977    edits: &Vec<(Range<Anchor>, String)>,
17978    snapshot: &MultiBufferSnapshot,
17979) -> bool {
17980    let mut all_insertions = true;
17981    let mut all_deletions = true;
17982
17983    for (range, new_text) in edits.iter() {
17984        let range_is_empty = range.to_offset(&snapshot).is_empty();
17985        let text_is_empty = new_text.is_empty();
17986
17987        if range_is_empty != text_is_empty {
17988            if range_is_empty {
17989                all_deletions = false;
17990            } else {
17991                all_insertions = false;
17992            }
17993        } else {
17994            return false;
17995        }
17996
17997        if !all_insertions && !all_deletions {
17998            return false;
17999        }
18000    }
18001    all_insertions || all_deletions
18002}